summaryrefslogtreecommitdiff
path: root/src/mscorlib/src
diff options
context:
space:
mode:
Diffstat (limited to 'src/mscorlib/src')
-rw-r--r--src/mscorlib/src/Internal/Console.cs (renamed from src/mscorlib/src/System/LowLevelConsole.cs)29
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs12
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs2
-rw-r--r--src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs72
-rw-r--r--src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.ICU.cs16
-rw-r--r--src/mscorlib/src/Interop/Windows/Normaliz/Interop.Idna.cs38
-rw-r--r--src/mscorlib/src/Interop/Windows/Normaliz/Interop.Normalization.cs24
-rw-r--r--src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs131
-rw-r--r--src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs43
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Registry.cs133
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryKey.cs1290
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs26
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryView.cs19
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs5
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs10
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs29
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs4
-rw-r--r--src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs42
-rw-r--r--src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs26
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Win32Native.cs516
-rw-r--r--src/mscorlib/src/System.Private.CoreLib.txt2235
-rw-r--r--src/mscorlib/src/System/Action.cs35
-rw-r--r--src/mscorlib/src/System/Activator.cs133
-rw-r--r--src/mscorlib/src/System/AggregateException.cs25
-rw-r--r--src/mscorlib/src/System/AppContext/AppContext.cs28
-rw-r--r--src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs1
-rw-r--r--src/mscorlib/src/System/AppContext/AppContextSwitches.cs6
-rw-r--r--src/mscorlib/src/System/AppDomain.cs490
-rw-r--r--src/mscorlib/src/System/AppDomainAttributes.cs18
-rw-r--r--src/mscorlib/src/System/AppDomainManager.cs31
-rw-r--r--src/mscorlib/src/System/AppDomainSetup.cs401
-rw-r--r--src/mscorlib/src/System/AppDomainUnloadedException.cs18
-rw-r--r--src/mscorlib/src/System/ApplicationException.cs56
-rw-r--r--src/mscorlib/src/System/ArgIterator.cs42
-rw-r--r--src/mscorlib/src/System/ArgumentException.cs97
-rw-r--r--src/mscorlib/src/System/ArgumentNullException.cs53
-rw-r--r--src/mscorlib/src/System/ArgumentOutOfRangeException.cs101
-rw-r--r--src/mscorlib/src/System/ArithmeticException.cs51
-rw-r--r--src/mscorlib/src/System/Array.cs1052
-rw-r--r--src/mscorlib/src/System/ArraySegment.cs178
-rw-r--r--src/mscorlib/src/System/ArrayTypeMismatchException.cs51
-rw-r--r--src/mscorlib/src/System/AsyncCallback.cs17
-rw-r--r--src/mscorlib/src/System/Attribute.cs204
-rw-r--r--src/mscorlib/src/System/AttributeTargets.cs36
-rw-r--r--src/mscorlib/src/System/AttributeUsageAttribute.cs56
-rw-r--r--src/mscorlib/src/System/BCLDebug.cs195
-rw-r--r--src/mscorlib/src/System/BadImageFormatException.cs87
-rw-r--r--src/mscorlib/src/System/BitConverter.cs462
-rw-r--r--src/mscorlib/src/System/Boolean.cs351
-rw-r--r--src/mscorlib/src/System/Buffer.cs485
-rw-r--r--src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs78
-rw-r--r--src/mscorlib/src/System/Byte.cs185
-rw-r--r--src/mscorlib/src/System/CLRConfig.cs17
-rw-r--r--src/mscorlib/src/System/CLSCompliantAttribute.cs34
-rw-r--r--src/mscorlib/src/System/Char.cs1000
-rw-r--r--src/mscorlib/src/System/CharEnumerator.cs81
-rw-r--r--src/mscorlib/src/System/Collections/ArrayList.cs453
-rw-r--r--src/mscorlib/src/System/Collections/CollectionBase.cs199
-rw-r--r--src/mscorlib/src/System/Collections/Comparer.cs64
-rw-r--r--src/mscorlib/src/System/Collections/CompatibleComparer.cs44
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs10
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs6
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs18
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs2
-rw-r--r--src/mscorlib/src/System/Collections/DictionaryEntry.cs62
-rw-r--r--src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs182
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs113
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Comparer.cs127
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ComparerHelpers.cs210
-rw-r--r--src/mscorlib/src/System/Collections/Generic/DebugView.cs120
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Dictionary.cs1060
-rw-r--r--src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs290
-rw-r--r--src/mscorlib/src/System/Collections/Generic/ICollection.cs52
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IComparer.cs30
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IDictionary.cs58
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IEnumerable.cs38
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IEnumerator.cs35
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs19
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IList.cs54
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs34
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs29
-rw-r--r--src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs34
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs44
-rw-r--r--src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs74
-rw-r--r--src/mscorlib/src/System/Collections/Generic/List.cs754
-rw-r--r--src/mscorlib/src/System/Collections/Hashtable.cs970
-rw-r--r--src/mscorlib/src/System/Collections/ICollection.cs80
-rw-r--r--src/mscorlib/src/System/Collections/IComparer.cs31
-rw-r--r--src/mscorlib/src/System/Collections/IDictionary.cs68
-rw-r--r--src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs78
-rw-r--r--src/mscorlib/src/System/Collections/IEnumerable.cs33
-rw-r--r--src/mscorlib/src/System/Collections/IEnumerator.cs52
-rw-r--r--src/mscorlib/src/System/Collections/IEqualityComparer.cs26
-rw-r--r--src/mscorlib/src/System/Collections/IHashCodeProvider.cs12
-rw-r--r--src/mscorlib/src/System/Collections/IList.cs70
-rw-r--r--src/mscorlib/src/System/Collections/IStructuralComparable.cs11
-rw-r--r--src/mscorlib/src/System/Collections/IStructuralEquatable.cs10
-rw-r--r--src/mscorlib/src/System/Collections/ListDictionaryInternal.cs404
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/Collection.cs303
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs244
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs196
-rw-r--r--src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs371
-rw-r--r--src/mscorlib/src/System/Collections/StructuralComparisons.cs89
-rw-r--r--src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs48
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs28
-rw-r--r--src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs23
-rw-r--r--src/mscorlib/src/System/Convert.cs2703
-rw-r--r--src/mscorlib/src/System/Currency.cs39
-rw-r--r--src/mscorlib/src/System/CurrentSystemTimeZone.Cache.cs35
-rw-r--r--src/mscorlib/src/System/CurrentTimeZone.cs214
-rw-r--r--src/mscorlib/src/System/DBNull.cs119
-rw-r--r--src/mscorlib/src/System/DataMisalignedException.cs39
-rw-r--r--src/mscorlib/src/System/DateTime.CoreCLR.cs29
-rw-r--r--src/mscorlib/src/System/DateTime.cs1360
-rw-r--r--src/mscorlib/src/System/DateTimeKind.cs17
-rw-r--r--src/mscorlib/src/System/DateTimeOffset.cs830
-rw-r--r--src/mscorlib/src/System/DayOfWeek.cs27
-rw-r--r--src/mscorlib/src/System/Decimal.cs883
-rw-r--r--src/mscorlib/src/System/DefaultBinder.CanConvert.cs30
-rw-r--r--src/mscorlib/src/System/DefaultBinder.cs1162
-rw-r--r--src/mscorlib/src/System/Delegate.cs220
-rw-r--r--src/mscorlib/src/System/DelegateSerializationHolder.cs48
-rw-r--r--src/mscorlib/src/System/Diagnostics/Assert.cs45
-rw-r--r--src/mscorlib/src/System/Diagnostics/AssertFilter.cs37
-rw-r--r--src/mscorlib/src/System/Diagnostics/AssertFilters.cs33
-rw-r--r--src/mscorlib/src/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs76
-rw-r--r--src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs25
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs48
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs59
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debug.Unix.cs95
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debug.Windows.cs63
-rw-r--r--src/mscorlib/src/System/Diagnostics/Debugger.cs21
-rw-r--r--src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs110
-rw-r--r--src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs11
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs665
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventActivityOptions.cs39
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventCounter.cs436
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs195
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs1207
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs6912
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs53
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs16
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs239
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs373
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs63
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs127
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSetItem.cs25
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs318
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EmptyStruct.cs17
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumHelper.cs30
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs64
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs146
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldAttribute.cs76
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldFormat.cs130
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventIgnoreAttribute.cs25
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs155
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs321
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceOptions.cs130
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs231
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs96
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs79
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyAnalysis.cs39
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs252
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleEventTypes.cs39
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs297
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs727
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs104
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataType.cs349
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs890
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTraits.cs28
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs262
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs370
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs209
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TypeAnalysis.cs103
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs196
-rw-r--r--src/mscorlib/src/System/Diagnostics/ICustomDebuggerNotification.cs8
-rw-r--r--src/mscorlib/src/System/Diagnostics/LogSwitch.cs90
-rw-r--r--src/mscorlib/src/System/Diagnostics/LoggingLevels.cs61
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stackframe.cs104
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stacktrace.cs224
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs11
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs33
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs24
-rw-r--r--src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs25
-rw-r--r--src/mscorlib/src/System/Diagnostics/log.cs80
-rw-r--r--src/mscorlib/src/System/DivideByZeroException.cs41
-rw-r--r--src/mscorlib/src/System/DllNotFoundException.cs42
-rw-r--r--src/mscorlib/src/System/Double.cs226
-rw-r--r--src/mscorlib/src/System/DuplicateWaitObjectException.cs65
-rw-r--r--src/mscorlib/src/System/Empty.cs27
-rw-r--r--src/mscorlib/src/System/EntryPointNotFoundException.cs42
-rw-r--r--src/mscorlib/src/System/Enum.cs208
-rw-r--r--src/mscorlib/src/System/Environment.cs476
-rw-r--r--src/mscorlib/src/System/EventHandler.cs14
-rw-r--r--src/mscorlib/src/System/Exception.cs267
-rw-r--r--src/mscorlib/src/System/ExecutionEngineException.cs47
-rw-r--r--src/mscorlib/src/System/FieldAccessException.cs39
-rw-r--r--src/mscorlib/src/System/FlagsAttribute.cs22
-rw-r--r--src/mscorlib/src/System/FormatException.cs41
-rw-r--r--src/mscorlib/src/System/FormattableString.cs81
-rw-r--r--src/mscorlib/src/System/GC.cs167
-rw-r--r--src/mscorlib/src/System/Globalization/BidiCategory.cs9
-rw-r--r--src/mscorlib/src/System/Globalization/Calendar.cs297
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs19
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.Unix.cs339
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.Windows.cs502
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarData.cs274
-rw-r--r--src/mscorlib/src/System/Globalization/CalendarWeekRule.cs19
-rw-r--r--src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs414
-rw-r--r--src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs360
-rw-r--r--src/mscorlib/src/System/Globalization/CharUnicodeInfoData.cs1247
-rw-r--r--src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs397
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs238
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs439
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs486
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.cs897
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.Unix.cs431
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.Windows.cs830
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.cs2503
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.Unix.cs128
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.Windows.cs278
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.cs1357
-rw-r--r--src/mscorlib/src/System/Globalization/CultureNotFoundException.cs129
-rw-r--r--src/mscorlib/src/System/Globalization/CultureTypes.cs30
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormat.cs1130
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs2858
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs747
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeParse.cs5035
-rw-r--r--src/mscorlib/src/System/Globalization/DateTimeStyles.cs49
-rw-r--r--src/mscorlib/src/System/Globalization/DaylightTime.cs63
-rw-r--r--src/mscorlib/src/System/Globalization/DigitShapes.cs21
-rw-r--r--src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs643
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs2
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingDataItem.cs77
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/EncodingTable.cs134
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs52
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationMode.Unix.cs24
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationMode.Windows.cs (renamed from src/mscorlib/src/System/EventArgs.cs)13
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationMode.cs12
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendar.cs266
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs419
-rw-r--r--src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs17
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewCalendar.cs1084
-rw-r--r--src/mscorlib/src/System/Globalization/HebrewNumber.cs403
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs (renamed from src/mscorlib/src/System/Runtime/CompilerServices/CallerFilePathAttribute.cs)12
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs83
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs (renamed from src/mscorlib/src/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs)11
-rw-r--r--src/mscorlib/src/System/Globalization/HijriCalendar.cs716
-rw-r--r--src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs142
-rw-r--r--src/mscorlib/src/System/Globalization/IdnMapping.Windows.cs121
-rw-r--r--src/mscorlib/src/System/Globalization/IdnMapping.cs929
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs96
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs209
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs62
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseCalendar.cs581
-rw-r--r--src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs293
-rw-r--r--src/mscorlib/src/System/Globalization/JulianCalendar.cs436
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanCalendar.cs259
-rw-r--r--src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs1334
-rw-r--r--src/mscorlib/src/System/Globalization/NumberFormatInfo.cs542
-rw-r--r--src/mscorlib/src/System/Globalization/NumberStyles.cs66
-rw-r--r--src/mscorlib/src/System/Globalization/PersianCalendar.cs578
-rw-r--r--src/mscorlib/src/System/Globalization/RegionInfo.cs201
-rw-r--r--src/mscorlib/src/System/Globalization/SortKey.cs109
-rw-r--r--src/mscorlib/src/System/Globalization/SortVersion.cs102
-rw-r--r--src/mscorlib/src/System/Globalization/StringInfo.cs240
-rw-r--r--src/mscorlib/src/System/Globalization/Tables/charinfo.nlpbin36992 -> 0 bytes
-rw-r--r--src/mscorlib/src/System/Globalization/TaiwanCalendar.cs256
-rw-r--r--src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs330
-rw-r--r--src/mscorlib/src/System/Globalization/TextElementEnumerator.cs136
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.Unix.cs117
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.Windows.cs113
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.cs860
-rw-r--r--src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs219
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanFormat.cs246
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanParse.cs1074
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanStyles.cs12
-rw-r--r--src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs850
-rw-r--r--src/mscorlib/src/System/Globalization/UnicodeCategory.cs78
-rw-r--r--src/mscorlib/src/System/Guid.cs873
-rw-r--r--src/mscorlib/src/System/HResults.cs236
-rw-r--r--src/mscorlib/src/System/IAppDomainPauseManager.cs22
-rw-r--r--src/mscorlib/src/System/IAsyncResult.cs30
-rw-r--r--src/mscorlib/src/System/ICloneable.cs28
-rw-r--r--src/mscorlib/src/System/IComparable.cs37
-rw-r--r--src/mscorlib/src/System/IConvertible.cs63
-rw-r--r--src/mscorlib/src/System/ICustomFormatter.cs24
-rw-r--r--src/mscorlib/src/System/IDisposable.cs60
-rw-r--r--src/mscorlib/src/System/IEquatable.cs14
-rw-r--r--src/mscorlib/src/System/IFormatProvider.cs23
-rw-r--r--src/mscorlib/src/System/IFormattable.cs15
-rw-r--r--src/mscorlib/src/System/IO/BinaryReader.cs347
-rw-r--r--src/mscorlib/src/System/IO/BinaryWriter.cs211
-rw-r--r--src/mscorlib/src/System/IO/Directory.cs28
-rw-r--r--src/mscorlib/src/System/IO/DirectoryNotFoundException.cs45
-rw-r--r--src/mscorlib/src/System/IO/DriveNotFoundException.cs29
-rw-r--r--src/mscorlib/src/System/IO/EndOfStreamException.cs42
-rw-r--r--src/mscorlib/src/System/IO/File.cs81
-rw-r--r--src/mscorlib/src/System/IO/FileAccess.cs41
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs43
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.cs175
-rw-r--r--src/mscorlib/src/System/IO/FileMode.cs53
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs20
-rw-r--r--src/mscorlib/src/System/IO/FileNotFoundException.cs157
-rw-r--r--src/mscorlib/src/System/IO/FileOptions.cs46
-rw-r--r--src/mscorlib/src/System/IO/FileShare.cs59
-rw-r--r--src/mscorlib/src/System/IO/IOException.cs46
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs393
-rw-r--r--src/mscorlib/src/System/IO/PathTooLongException.cs43
-rw-r--r--src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs17
-rw-r--r--src/mscorlib/src/System/IO/SearchOption.cs5
-rw-r--r--src/mscorlib/src/System/IO/SeekOrigin.cs31
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs355
-rw-r--r--src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs46
-rw-r--r--src/mscorlib/src/System/IO/StreamReader.cs249
-rw-r--r--src/mscorlib/src/System/IO/TextReader.cs32
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs1132
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs481
-rw-r--r--src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs153
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs196
-rw-r--r--src/mscorlib/src/System/IO/__HResults.cs7
-rw-r--r--src/mscorlib/src/System/IObserver.cs13
-rw-r--r--src/mscorlib/src/System/IProgress.cs15
-rw-r--r--src/mscorlib/src/System/IServiceObjectProvider.cs16
-rw-r--r--src/mscorlib/src/System/IndexOutOfRangeException.cs41
-rw-r--r--src/mscorlib/src/System/InsufficientExecutionStackException.cs32
-rw-r--r--src/mscorlib/src/System/InsufficientMemoryException.cs37
-rw-r--r--src/mscorlib/src/System/Int16.cs220
-rw-r--r--src/mscorlib/src/System/Int32.cs153
-rw-r--r--src/mscorlib/src/System/Int64.cs151
-rw-r--r--src/mscorlib/src/System/IntPtr.cs100
-rw-r--r--src/mscorlib/src/System/Internal.cs49
-rw-r--r--src/mscorlib/src/System/InvalidCastException.cs44
-rw-r--r--src/mscorlib/src/System/InvalidOperationException.cs42
-rw-r--r--src/mscorlib/src/System/InvalidProgramException.cs41
-rw-r--r--src/mscorlib/src/System/InvalidTimeZoneException.cs28
-rw-r--r--src/mscorlib/src/System/Lazy.cs506
-rw-r--r--src/mscorlib/src/System/MarshalByRefObject.cs30
-rw-r--r--src/mscorlib/src/System/Math.cs921
-rw-r--r--src/mscorlib/src/System/MathF.cs38
-rw-r--r--src/mscorlib/src/System/MemberAccessException.cs48
-rw-r--r--src/mscorlib/src/System/MethodAccessException.cs39
-rw-r--r--src/mscorlib/src/System/MissingFieldException.cs71
-rw-r--r--src/mscorlib/src/System/MissingMemberException.cs96
-rw-r--r--src/mscorlib/src/System/MissingMethodException.cs65
-rw-r--r--src/mscorlib/src/System/MulticastDelegate.cs176
-rw-r--r--src/mscorlib/src/System/MulticastNotSupportedException.cs37
-rw-r--r--src/mscorlib/src/System/NonSerializedAttribute.cs19
-rw-r--r--src/mscorlib/src/System/NotFiniteNumberException.cs71
-rw-r--r--src/mscorlib/src/System/NotImplementedException.cs40
-rw-r--r--src/mscorlib/src/System/NotSupportedException.cs41
-rw-r--r--src/mscorlib/src/System/NullReferenceException.cs41
-rw-r--r--src/mscorlib/src/System/Nullable.cs105
-rw-r--r--src/mscorlib/src/System/Number.cs782
-rw-r--r--src/mscorlib/src/System/Object.cs320
-rw-r--r--src/mscorlib/src/System/ObjectDisposedException.cs82
-rw-r--r--src/mscorlib/src/System/ObsoleteAttribute.cs61
-rw-r--r--src/mscorlib/src/System/OleAutBinder.cs28
-rw-r--r--src/mscorlib/src/System/OperatingSystem.cs91
-rw-r--r--src/mscorlib/src/System/OperationCanceledException.cs44
-rw-r--r--src/mscorlib/src/System/OutOfMemoryException.cs40
-rw-r--r--src/mscorlib/src/System/OverflowException.cs41
-rw-r--r--src/mscorlib/src/System/ParamArrayAttribute.cs21
-rw-r--r--src/mscorlib/src/System/ParamsArray.cs81
-rw-r--r--src/mscorlib/src/System/ParseNumbers.cs71
-rw-r--r--src/mscorlib/src/System/PlatformID.cs18
-rw-r--r--src/mscorlib/src/System/PlatformNotSupportedException.cs41
-rw-r--r--src/mscorlib/src/System/Progress.cs105
-rw-r--r--src/mscorlib/src/System/Random.cs249
-rw-r--r--src/mscorlib/src/System/RankException.cs42
-rw-r--r--src/mscorlib/src/System/ReadOnlySpan.cs31
-rw-r--r--src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs41
-rw-r--r--src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs211
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyAttributes.cs387
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyName.cs191
-rw-r--r--src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs53
-rw-r--r--src/mscorlib/src/System/Reflection/Associates.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/Binder.cs49
-rw-r--r--src/mscorlib/src/System/Reflection/BindingFlags.cs63
-rw-r--r--src/mscorlib/src/System/Reflection/CallingConventions.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.cs (renamed from src/mscorlib/src/System/MidpointRounding.cs)7
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttribute.cs166
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttributeExtensions.cs1
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs37
-rw-r--r--src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs39
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs18
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs155
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs5
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs126
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs92
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs88
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs126
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs484
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs223
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs54
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/EventToken.cs37
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs77
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FieldToken.cs34
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/FlowControl.cs30
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs774
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs188
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/Label.cs38
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs44
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs304
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodToken.cs30
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs267
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs36
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OpCodes.cs5063
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/Opcode.cs271
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs24
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/OperandType.cs48
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs10
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs93
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs36
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs130
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs34
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs308
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs36
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs68
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/StringToken.cs46
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs66
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/SymbolType.cs269
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs614
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs60
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeToken.cs40
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs56
-rw-r--r--src/mscorlib/src/System/Reflection/EventAttributes.cs29
-rw-r--r--src/mscorlib/src/System/Reflection/EventInfo.cs401
-rw-r--r--src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs93
-rw-r--r--src/mscorlib/src/System/Reflection/FieldAttributes.cs42
-rw-r--r--src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/FieldInfo.cs862
-rw-r--r--src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs22
-rw-r--r--src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs33
-rw-r--r--src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs38
-rw-r--r--src/mscorlib/src/System/Reflection/IReflect.cs116
-rw-r--r--src/mscorlib/src/System/Reflection/IReflectableType.cs20
-rw-r--r--src/mscorlib/src/System/Reflection/InterfaceMapping.cs22
-rw-r--r--src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs39
-rw-r--r--src/mscorlib/src/System/Reflection/LoaderAllocator.cs11
-rw-r--r--src/mscorlib/src/System/Reflection/LocalVariableInfo.cs40
-rw-r--r--src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs65
-rw-r--r--src/mscorlib/src/System/Reflection/MdConstant.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/MdFieldInfo.cs141
-rw-r--r--src/mscorlib/src/System/Reflection/MdImport.cs476
-rw-r--r--src/mscorlib/src/System/Reflection/MemberFilter.cs18
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfo.Internal.cs (renamed from src/mscorlib/src/System/IObservable.cs)6
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfo.cs113
-rw-r--r--src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs285
-rw-r--r--src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs39
-rw-r--r--src/mscorlib/src/System/Reflection/MemberTypes.cs33
-rw-r--r--src/mscorlib/src/System/Reflection/MethodAttributes.cs55
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBase.CoreCLR.cs157
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBase.cs330
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBody.cs136
-rw-r--r--src/mscorlib/src/System/Reflection/MethodImplAttributes.cs43
-rw-r--r--src/mscorlib/src/System/Reflection/Missing.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/Module.cs1120
-rw-r--r--src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs45
-rw-r--r--src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs74
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterAttributes.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/ParameterModifier.cs45
-rw-r--r--src/mscorlib/src/System/Reflection/Pointer.cs75
-rw-r--r--src/mscorlib/src/System/Reflection/PropertyAttributes.cs32
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionContext.cs36
-rw-r--r--src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs72
-rw-r--r--src/mscorlib/src/System/Reflection/ResourceAttributes.cs23
-rw-r--r--src/mscorlib/src/System/Reflection/RtFieldInfo.cs390
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeAssembly.cs (renamed from src/mscorlib/src/System/Reflection/Assembly.cs)987
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs (renamed from src/mscorlib/src/System/Reflection/ConstructorInfo.cs)267
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs220
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs136
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs (renamed from src/mscorlib/src/System/Reflection/MethodInfo.cs)333
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeModule.cs602
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs (renamed from src/mscorlib/src/System/Reflection/ParameterInfo.cs)259
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs (renamed from src/mscorlib/src/System/Reflection/PropertyInfo.cs)252
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs88
-rw-r--r--src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs95
-rw-r--r--src/mscorlib/src/System/Reflection/TargetException.cs37
-rw-r--r--src/mscorlib/src/System/Reflection/TargetInvocationException.cs46
-rw-r--r--src/mscorlib/src/System/Reflection/TargetParameterCountException.cs40
-rw-r--r--src/mscorlib/src/System/Reflection/TypeAttributes.cs64
-rw-r--r--src/mscorlib/src/System/Reflection/TypeDelegator.cs257
-rw-r--r--src/mscorlib/src/System/Reflection/TypeFilter.cs18
-rw-r--r--src/mscorlib/src/System/Reflection/TypeInfo.cs194
-rw-r--r--src/mscorlib/src/System/Reflection/__Filters.cs67
-rw-r--r--src/mscorlib/src/System/ResId.cs156
-rw-r--r--src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs16
-rw-r--r--src/mscorlib/src/System/Resources/IResourceGroveler.cs16
-rw-r--r--src/mscorlib/src/System/Resources/IResourceReader.cs30
-rw-r--r--src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs6
-rw-r--r--src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs57
-rw-r--r--src/mscorlib/src/System/Resources/MissingManifestResourceException.cs41
-rw-r--r--src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs55
-rw-r--r--src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs64
-rw-r--r--src/mscorlib/src/System/Resources/ResourceFallbackManager.cs172
-rw-r--r--src/mscorlib/src/System/Resources/ResourceManager.cs396
-rw-r--r--src/mscorlib/src/System/Resources/ResourceReader.cs671
-rw-r--r--src/mscorlib/src/System/Resources/ResourceSet.cs62
-rw-r--r--src/mscorlib/src/System/Resources/ResourceTypeCode.cs57
-rw-r--r--src/mscorlib/src/System/Resources/RuntimeResourceSet.cs122
-rw-r--r--src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs38
-rw-r--r--src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs28
-rw-r--r--src/mscorlib/src/System/Resources/__FastResourceComparer.cs36
-rw-r--r--src/mscorlib/src/System/Resources/__HResults.cs3
-rw-r--r--src/mscorlib/src/System/RtType.cs980
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs94
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs112
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs50
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs23
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs43
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs58
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/FriendAccessAllowedAttribute.cs (renamed from src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs)36
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs39
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs22
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs16
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs61
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs39
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs48
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs32
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs20
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs19
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs23
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs26
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs57
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs35
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs34
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs61
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs14
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs28
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs36
-rw-r--r--src/mscorlib/src/System/Runtime/GcSettings.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs36
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs188
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/COMException.cs60
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs21
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs23
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs220
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs50
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs100
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs104
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs230
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs224
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs13
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs77
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs18
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs9
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs15
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs38
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs458
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs38
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs64
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs60
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs45
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs40
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs67
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs515
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs5
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs210
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs55
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs48
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs20
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs24
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs126
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs3
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs24
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs48
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs41
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs249
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs65
-rw-r--r--src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs161
-rw-r--r--src/mscorlib/src/System/Runtime/MemoryFailPoint.cs180
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs7
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs67
-rw-r--r--src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs10
-rw-r--r--src/mscorlib/src/System/Runtime/RuntimeImports.cs35
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs121
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs75
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs22
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs39
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs30
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs240
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs59
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs44
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs41
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs145
-rw-r--r--src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs72
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs33
-rw-r--r--src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs45
-rw-r--r--src/mscorlib/src/System/RuntimeArgumentHandle.cs9
-rw-r--r--src/mscorlib/src/System/RuntimeHandles.cs380
-rw-r--r--src/mscorlib/src/System/SByte.cs218
-rw-r--r--src/mscorlib/src/System/Security/Attributes.cs199
-rw-r--r--src/mscorlib/src/System/Security/DynamicSecurityMethodAttribute.cs21
-rw-r--r--src/mscorlib/src/System/Security/SecurityException.cs110
-rw-r--r--src/mscorlib/src/System/Security/SecurityState.cs25
-rw-r--r--src/mscorlib/src/System/Security/Util/URLString.cs138
-rw-r--r--src/mscorlib/src/System/Security/VerificationException.cs32
-rw-r--r--src/mscorlib/src/System/SerializableAttribute.cs24
-rw-r--r--src/mscorlib/src/System/SharedStatics.cs34
-rw-r--r--src/mscorlib/src/System/Single.cs220
-rw-r--r--src/mscorlib/src/System/Span.cs587
-rw-r--r--src/mscorlib/src/System/StackOverflowException.cs41
-rw-r--r--src/mscorlib/src/System/String.Comparison.cs383
-rw-r--r--src/mscorlib/src/System/String.Manipulation.cs634
-rw-r--r--src/mscorlib/src/System/String.Searching.cs180
-rw-r--r--src/mscorlib/src/System/String.cs408
-rw-r--r--src/mscorlib/src/System/StringComparer.cs300
-rw-r--r--src/mscorlib/src/System/StringComparison.cs29
-rw-r--r--src/mscorlib/src/System/StringFreezingAttribute.cs25
-rw-r--r--src/mscorlib/src/System/StringSplitOptions.cs13
-rw-r--r--src/mscorlib/src/System/StubHelpers.cs289
-rw-r--r--src/mscorlib/src/System/SystemException.cs32
-rw-r--r--src/mscorlib/src/System/Text/ASCIIEncoding.cs757
-rw-r--r--src/mscorlib/src/System/Text/Decoder.cs338
-rw-r--r--src/mscorlib/src/System/Text/DecoderBestFitFallback.cs33
-rw-r--r--src/mscorlib/src/System/Text/DecoderExceptionFallback.cs28
-rw-r--r--src/mscorlib/src/System/Text/DecoderFallback.cs41
-rw-r--r--src/mscorlib/src/System/Text/DecoderNLS.cs87
-rw-r--r--src/mscorlib/src/System/Text/DecoderReplacementFallback.cs30
-rw-r--r--src/mscorlib/src/System/Text/Encoder.cs332
-rw-r--r--src/mscorlib/src/System/Text/EncoderBestFitFallback.cs39
-rw-r--r--src/mscorlib/src/System/Text/EncoderExceptionFallback.cs46
-rw-r--r--src/mscorlib/src/System/Text/EncoderFallback.cs30
-rw-r--r--src/mscorlib/src/System/Text/EncoderNLS.cs86
-rw-r--r--src/mscorlib/src/System/Text/EncoderReplacementFallback.cs44
-rw-r--r--src/mscorlib/src/System/Text/Encoding.cs428
-rw-r--r--src/mscorlib/src/System/Text/EncodingForwarder.cs329
-rw-r--r--src/mscorlib/src/System/Text/EncodingInfo.cs74
-rw-r--r--src/mscorlib/src/System/Text/EncodingNLS.cs125
-rw-r--r--src/mscorlib/src/System/Text/EncodingProvider.cs136
-rw-r--r--src/mscorlib/src/System/Text/Latin1Encoding.cs62
-rw-r--r--src/mscorlib/src/System/Text/Normalization.Unix.cs25
-rw-r--r--src/mscorlib/src/System/Text/Normalization.Windows.cs272
-rw-r--r--src/mscorlib/src/System/Text/Normalization.cs29
-rw-r--r--src/mscorlib/src/System/Text/StringBuilder.CoreCLR.cs48
-rw-r--r--src/mscorlib/src/System/Text/StringBuilder.cs2286
-rw-r--r--src/mscorlib/src/System/Text/StringBuilderCache.cs5
-rw-r--r--src/mscorlib/src/System/Text/UTF32Encoding.cs1003
-rw-r--r--src/mscorlib/src/System/Text/UTF7Encoding.cs372
-rw-r--r--src/mscorlib/src/System/Text/UTF8Encoding.cs2286
-rw-r--r--src/mscorlib/src/System/Text/UnicodeEncoding.cs1826
-rw-r--r--src/mscorlib/src/System/ThreadAttributes.cs28
-rw-r--r--src/mscorlib/src/System/ThreadStaticAttribute.cs28
-rw-r--r--src/mscorlib/src/System/Threading/AbandonedMutexException.cs85
-rw-r--r--src/mscorlib/src/System/Threading/ApartmentState.cs27
-rw-r--r--src/mscorlib/src/System/Threading/AsyncLocal.cs487
-rw-r--r--src/mscorlib/src/System/Threading/AutoResetEvent.cs24
-rw-r--r--src/mscorlib/src/System/Threading/CancellationToken.cs32
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs6
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenSource.cs48
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs319
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandleOverlapped.cs52
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs105
-rw-r--r--src/mscorlib/src/System/Threading/CountdownEvent.cs589
-rw-r--r--src/mscorlib/src/System/Threading/EventResetMode.cs26
-rw-r--r--src/mscorlib/src/System/Threading/EventWaitHandle.cs59
-rw-r--r--src/mscorlib/src/System/Threading/ExecutionContext.cs380
-rw-r--r--src/mscorlib/src/System/Threading/Interlocked.cs45
-rw-r--r--src/mscorlib/src/System/Threading/LazyInitializer.cs131
-rw-r--r--src/mscorlib/src/System/Threading/LockRecursionException.cs30
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEvent.cs24
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEventSlim.cs16
-rw-r--r--src/mscorlib/src/System/Threading/Monitor.cs35
-rw-r--r--src/mscorlib/src/System/Threading/Mutex.cs92
-rw-r--r--src/mscorlib/src/System/Threading/Overlapped.cs100
-rw-r--r--src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs23
-rw-r--r--src/mscorlib/src/System/Threading/ReaderWriterLockSlim.cs1311
-rw-r--r--src/mscorlib/src/System/Threading/Semaphore.cs32
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreFullException.cs27
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreSlim.cs37
-rw-r--r--src/mscorlib/src/System/Threading/SendOrPostCallback.cs16
-rw-r--r--src/mscorlib/src/System/Threading/SpinWait.cs59
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationContext.cs46
-rw-r--r--src/mscorlib/src/System/Threading/SynchronizationLockException.cs43
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs34
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs30
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs39
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs10
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs14
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs196
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Task.cs511
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs93
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs8
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs33
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs38
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs73
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs75
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs81
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs24
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/future.cs43
-rw-r--r--src/mscorlib/src/System/Threading/Thread.cs251
-rw-r--r--src/mscorlib/src/System/Threading/ThreadAbortException.cs39
-rw-r--r--src/mscorlib/src/System/Threading/ThreadInterruptedException.cs41
-rw-r--r--src/mscorlib/src/System/Threading/ThreadLocal.cs23
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPool.cs259
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPriority.cs31
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStart.cs23
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStartException.cs37
-rw-r--r--src/mscorlib/src/System/Threading/ThreadState.cs35
-rw-r--r--src/mscorlib/src/System/Threading/ThreadStateException.cs40
-rw-r--r--src/mscorlib/src/System/Threading/Timeout.cs19
-rw-r--r--src/mscorlib/src/System/Threading/Timer.cs159
-rw-r--r--src/mscorlib/src/System/Threading/Volatile.cs53
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandle.cs203
-rw-r--r--src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs36
-rw-r--r--src/mscorlib/src/System/ThrowHelper.cs311
-rw-r--r--src/mscorlib/src/System/TimeSpan.cs302
-rw-r--r--src/mscorlib/src/System/TimeZone.cs246
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs20
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs62
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs16
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Unix.cs68
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Win32.cs38
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.cs74
-rw-r--r--src/mscorlib/src/System/TimeZoneNotFoundException.cs28
-rw-r--r--src/mscorlib/src/System/TimeoutException.cs41
-rw-r--r--src/mscorlib/src/System/Tuple.cs28
-rw-r--r--src/mscorlib/src/System/TupleExtensions.cs930
-rw-r--r--src/mscorlib/src/System/Type.CoreCLR.cs206
-rw-r--r--src/mscorlib/src/System/Type.cs1764
-rw-r--r--src/mscorlib/src/System/TypeAccessException.cs34
-rw-r--r--src/mscorlib/src/System/TypeCode.cs48
-rw-r--r--src/mscorlib/src/System/TypeInitializationException.cs79
-rw-r--r--src/mscorlib/src/System/TypeLoadException.cs106
-rw-r--r--src/mscorlib/src/System/TypeNameParser.cs19
-rw-r--r--src/mscorlib/src/System/TypeUnloadedException.cs42
-rw-r--r--src/mscorlib/src/System/TypedReference.cs49
-rw-r--r--src/mscorlib/src/System/UInt16.cs180
-rw-r--r--src/mscorlib/src/System/UInt32.cs148
-rw-r--r--src/mscorlib/src/System/UInt64.cs156
-rw-r--r--src/mscorlib/src/System/UIntPtr.cs80
-rw-r--r--src/mscorlib/src/System/UnauthorizedAccessException.cs45
-rw-r--r--src/mscorlib/src/System/UnhandledExceptionEventArgs.cs29
-rw-r--r--src/mscorlib/src/System/UnhandledExceptionEventHandler.cs9
-rw-r--r--src/mscorlib/src/System/UnitySerializationHolder.cs357
-rw-r--r--src/mscorlib/src/System/ValueTuple.cs2324
-rw-r--r--src/mscorlib/src/System/ValueType.cs38
-rw-r--r--src/mscorlib/src/System/Variant.cs395
-rw-r--r--src/mscorlib/src/System/Version.cs448
-rw-r--r--src/mscorlib/src/System/Void.cs17
-rw-r--r--src/mscorlib/src/System/WeakReference.cs63
-rw-r--r--src/mscorlib/src/System/WeakReferenceOfT.cs25
-rw-r--r--src/mscorlib/src/System/XmlIgnoreMemberAttribute.cs21
-rw-r--r--src/mscorlib/src/System/__ComObject.cs36
-rw-r--r--src/mscorlib/src/System/__Filters.cs155
-rw-r--r--src/mscorlib/src/System/__HResults.cs153
-rw-r--r--src/mscorlib/src/mscorlib.Friends.cs8
839 files changed, 44653 insertions, 111397 deletions
diff --git a/src/mscorlib/src/System/LowLevelConsole.cs b/src/mscorlib/src/Internal/Console.cs
index 29e69185ac..a2a323fa13 100644
--- a/src/mscorlib/src/System/LowLevelConsole.cs
+++ b/src/mscorlib/src/Internal/Console.cs
@@ -2,19 +2,20 @@
// 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.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
-namespace System
+namespace Internal
{
//
// Simple limited console class for internal printf-style debugging in System.Private.CoreLib
// and low-level tests that want to call System.Private.CoreLib directly
//
- public static class LowLevelConsole
+ public static class Console
{
private static readonly SafeFileHandle _outputHandle =
new SafeFileHandle(Win32Native.GetStdHandle(Win32Native.STD_OUTPUT_HANDLE), false);
@@ -23,7 +24,7 @@ namespace System
{
byte[] bytes = Encoding.UTF8.GetBytes(s);
- fixed (byte * pBytes = bytes)
+ fixed (byte* pBytes = bytes)
{
int bytesWritten;
Win32Native.WriteFile(_outputHandle, pBytes, bytes.Length, out bytesWritten, IntPtr.Zero);
@@ -39,27 +40,5 @@ namespace System
{
Write(Environment.NewLine);
}
- }
-
- //
- // Internal wrapper with the regular name for convenience. Note that it cannot be public to avoid colliding
- // with the full Console type.
- //
- internal static class Console
- {
- public static void Write(string s)
- {
- LowLevelConsole.Write(s);
- }
-
- public static void WriteLine(string s)
- {
- LowLevelConsole.WriteLine(s);
- }
-
- public static void WriteLine()
- {
- LowLevelConsole.WriteLine();
- }
}
}
diff --git a/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs b/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs
index b22310eacb..b5a56b8633 100644
--- a/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs
+++ b/src/mscorlib/src/Internal/Runtime/Augments/EnvironmentAugments.cs
@@ -4,6 +4,8 @@
using System;
using System.Collections;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
namespace Internal.Runtime.Augments
{
@@ -16,7 +18,6 @@ namespace Internal.Runtime.Augments
public static void FailFast(string message, Exception error) => Environment.FailFast(message, error);
public static string[] GetCommandLineArgs() => Environment.GetCommandLineArgs();
public static bool HasShutdownStarted => Environment.HasShutdownStarted;
- public static string StackTrace => Environment.StackTrace;
public static int TickCount => Environment.TickCount;
public static string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable);
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) => Environment.GetEnvironmentVariable(variable, target);
@@ -24,5 +25,14 @@ namespace Internal.Runtime.Augments
public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target) => Environment.GetEnvironmentVariables(target);
public static void SetEnvironmentVariable(string variable, string value) => Environment.SetEnvironmentVariable(variable, value);
public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) => Environment.SetEnvironmentVariable(variable, value, target);
+
+ public static string StackTrace
+ {
+ [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
+ get
+ {
+ return new StackTrace(1 /* skip this one frame */, true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
+ }
+ }
}
}
diff --git a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
index 58eff98dec..605f974da0 100644
--- a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
+++ b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
@@ -15,7 +15,7 @@ namespace Internal.Runtime.Augments
{
public class RuntimeThread : CriticalFinalizerObject
{
- internal RuntimeThread() {}
+ internal RuntimeThread() { }
public static RuntimeThread Create(ThreadStart start) => new Thread(start);
public static RuntimeThread Create(ThreadStart start, int maxStackSize) => new Thread(start, maxStackSize);
diff --git a/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
new file mode 100644
index 0000000000..fe14560a3a
--- /dev/null
+++ b/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
@@ -0,0 +1,72 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Security;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortHandle")]
+ internal unsafe static extern ResultCode GetSortHandle(byte[] localeName, out SafeSortHandle sortHandle);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CloseSortHandle")]
+ internal unsafe static extern void CloseSortHandle(IntPtr handle);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")]
+ internal unsafe static extern int CompareString(SafeSortHandle sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")]
+ internal unsafe static extern int IndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_LastIndexOf")]
+ internal unsafe static extern int LastIndexOf(SafeSortHandle sortHandle, string target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOfOrdinalIgnoreCase")]
+ internal unsafe static extern int IndexOfOrdinalIgnoreCase(string target, int cwTargetLength, char* pSource, int cwSourceLength, bool findLast);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool StartsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool EndsWith(SafeSortHandle sortHandle, string target, int cwTargetLength, string source, int cwSourceLength, CompareOptions options);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortKey")]
+ internal unsafe static extern int GetSortKey(SafeSortHandle sortHandle, string str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareStringOrdinalIgnoreCase")]
+ 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 class SafeSortHandle : SafeHandle
+ {
+ private SafeSortHandle() :
+ base(IntPtr.Zero, true)
+ {
+ }
+
+ public override bool IsInvalid
+ {
+ get { return handle == IntPtr.Zero; }
+ }
+
+ protected override bool ReleaseHandle()
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ CloseSortHandle(handle);
+ SetHandle(IntPtr.Zero);
+ return true;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.ICU.cs b/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.ICU.cs
new file mode 100644
index 0000000000..c690884145
--- /dev/null
+++ b/src/mscorlib/src/Interop/Unix/System.Globalization.Native/Interop.ICU.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ [DllImport(Libraries.GlobalizationInterop, EntryPoint = "GlobalizationNative_LoadICU")]
+ internal static extern int LoadICU();
+ }
+}
diff --git a/src/mscorlib/src/Interop/Windows/Normaliz/Interop.Idna.cs b/src/mscorlib/src/Interop/Windows/Normaliz/Interop.Idna.cs
new file mode 100644
index 0000000000..cad457d915
--- /dev/null
+++ b/src/mscorlib/src/Interop/Windows/Normaliz/Interop.Idna.cs
@@ -0,0 +1,38 @@
+// 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 Normaliz
+ {
+ //
+ // Idn APIs
+ //
+
+ [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern int IdnToAscii(
+ uint dwFlags,
+ IntPtr lpUnicodeCharStr,
+ int cchUnicodeChar,
+ [System.Runtime.InteropServices.OutAttribute()]
+ IntPtr lpASCIICharStr,
+ int cchASCIIChar);
+
+ [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern int IdnToUnicode(
+ uint dwFlags,
+ IntPtr lpASCIICharStr,
+ int cchASCIIChar,
+ [System.Runtime.InteropServices.OutAttribute()]
+ IntPtr lpUnicodeCharStr,
+ int cchUnicodeChar);
+
+ internal const int IDN_ALLOW_UNASSIGNED = 0x1;
+ internal const int IDN_USE_STD3_ASCII_RULES = 0x2;
+ internal const int ERROR_INVALID_NAME = 123;
+ }
+}
diff --git a/src/mscorlib/src/Interop/Windows/Normaliz/Interop.Normalization.cs b/src/mscorlib/src/Interop/Windows/Normaliz/Interop.Normalization.cs
new file mode 100644
index 0000000000..3e49f1f64c
--- /dev/null
+++ b/src/mscorlib/src/Interop/Windows/Normaliz/Interop.Normalization.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 System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Normaliz
+ {
+ [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern bool IsNormalizedString(int normForm, string source, int length);
+
+ [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern int NormalizeString(
+ int normForm,
+ string source,
+ int sourceLength,
+ [System.Runtime.InteropServices.OutAttribute()]
+ char[] destination,
+ int destinationLength);
+ }
+}
diff --git a/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs b/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs
new file mode 100644
index 0000000000..2bb349d670
--- /dev/null
+++ b/src/mscorlib/src/Interop/Windows/kernel32/Interop.Globalization.cs
@@ -0,0 +1,131 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static unsafe partial class Kernel32
+ {
+ internal const int LOCALE_NAME_MAX_LENGTH = 85;
+ internal const uint LOCALE_ALLOW_NEUTRAL_NAMES = 0x08000000; // Flag to allow returning neutral names/lcids for name conversion
+ internal const uint LOCALE_SUPPLEMENTAL = 0x00000002;
+ internal const uint LOCALE_REPLACEMENT = 0x00000008;
+ internal const uint LOCALE_NEUTRALDATA = 0x00000010;
+ internal const uint LOCALE_SPECIFICDATA = 0x00000020;
+ internal const int COMPARE_STRING = 0x0001;
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static unsafe int LCIDToLocaleName(int locale, char *pLocaleName, int cchName, uint dwFlags);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static int LocaleNameToLCID(string lpName, uint dwFlags);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static unsafe int LCMapStringEx(
+ string lpLocaleName,
+ uint dwMapFlags,
+ char* lpSrcStr,
+ int cchSrc,
+ void* lpDestStr,
+ int cchDest,
+ void* lpVersionInformation,
+ void* lpReserved,
+ IntPtr sortHandle);
+
+ [DllImport("kernel32.dll", EntryPoint = "FindNLSStringEx")]
+ internal extern static unsafe int FindNLSStringEx(
+ char* lpLocaleName,
+ uint dwFindNLSStringFlags,
+ char* lpStringSource,
+ int cchSource,
+ char* lpStringValue,
+ int cchValue,
+ int* pcchFound,
+ void* lpVersionInformation,
+ void* lpReserved,
+ IntPtr sortHandle);
+
+ [DllImport("kernel32.dll", EntryPoint = "CompareStringEx")]
+ internal extern static unsafe int CompareStringEx(
+ char* lpLocaleName,
+ uint dwCmpFlags,
+ char* lpString1,
+ int cchCount1,
+ char* lpString2,
+ int cchCount2,
+ void* lpVersionInformation,
+ void* lpReserved,
+ IntPtr lParam);
+
+ [DllImport("kernel32.dll", EntryPoint = "CompareStringOrdinal")]
+ internal extern static unsafe int CompareStringOrdinal(
+ char* lpString1,
+ int cchCount1,
+ char* lpString2,
+ int cchCount2,
+ bool bIgnoreCase);
+
+ [DllImport("kernel32.dll", EntryPoint = "FindStringOrdinal")]
+ internal extern static unsafe int FindStringOrdinal(
+ uint dwFindStringOrdinalFlags,
+ char* lpStringSource,
+ int cchSource,
+ char* lpStringValue,
+ int cchValue,
+ int bIgnoreCase);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static unsafe bool IsNLSDefinedString(
+ int Function,
+ uint dwFlags,
+ IntPtr lpVersionInformation,
+ char* lpString,
+ int cchStr);
+
+ [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
+ internal static extern bool GetUserPreferredUILanguages(uint dwFlags, out uint pulNumLanguages, char [] pwszLanguagesBuffer, ref uint pcchLanguagesBuffer);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, IntPtr lpLCData, int cchData);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static bool EnumSystemLocalesEx(EnumLocalesProcEx lpLocaleEnumProcEx, uint dwFlags, IntPtr lParam, IntPtr reserved);
+
+ internal delegate BOOL EnumLocalesProcEx(IntPtr lpLocaleString, uint dwFlags, IntPtr lParam);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static bool EnumTimeFormatsEx(EnumTimeFormatsProcEx lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, IntPtr lParam);
+
+ internal delegate BOOL EnumTimeFormatsProcEx(IntPtr lpTimeFormatString, IntPtr lParam);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue);
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static bool EnumCalendarInfoExEx(EnumCalendarInfoProcExEx pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, IntPtr lParam);
+
+ internal delegate BOOL EnumCalendarInfoProcExEx(IntPtr lpCalendarInfoString, uint Calendar, IntPtr lpReserved, IntPtr lParam);
+
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct NlsVersionInfoEx
+ {
+ internal int dwNLSVersionInfoSize;
+ internal int dwNLSVersion;
+ internal int dwDefinedVersion;
+ internal int dwEffectiveId;
+ internal Guid guidCustomVersion;
+ }
+
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
+ internal extern static unsafe bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation);
+ }
+}
diff --git a/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs b/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
index 6c2c6e9630..93138e6e16 100644
--- a/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
+++ b/src/mscorlib/src/Microsoft/Win32/OAVariantLib.cs
@@ -12,8 +12,9 @@
**
**
===========================================================*/
-namespace Microsoft.Win32 {
-
+
+namespace Microsoft.Win32
+{
using System;
using System.Diagnostics.Contracts;
using System.Reflection;
@@ -31,8 +32,8 @@ namespace Microsoft.Win32 {
public const int NoUserOverride = 0x04;
public const int CalendarHijri = 0x08;
public const int LocalBool = 0x10;
-
- internal static readonly Type [] ClassTypes = {
+
+ internal static readonly Type[] ClassTypes = {
typeof(Empty),
typeof(void),
typeof(Boolean),
@@ -58,12 +59,12 @@ namespace Microsoft.Win32 {
typeof(DBNull),
};
- // Keep these numbers in sync w/ the above array.
- private const int CV_OBJECT=0x12;
-
+ // Keep these numbers in sync w/ the above array.
+ private const int CV_OBJECT = 0x12;
+
#endregion
-
+
#region Internal Methods
/**
@@ -79,43 +80,45 @@ namespace Microsoft.Win32 {
throw new ArgumentNullException(nameof(targetClass));
if (culture == null)
throw new ArgumentNullException(nameof(culture));
- Variant result = new Variant ();
- ChangeTypeEx(ref result, ref source,
+ Variant result = new Variant();
+ ChangeTypeEx(ref result, ref source,
#if FEATURE_USE_LCID
- culture.LCID,
+ culture.LCID,
#else
// @CORESYSTODO: what does CoreSystem expect for this argument?
0,
#endif
targetClass.TypeHandle.Value, GetCVTypeFromClass(targetClass), options);
return result;
- }
+ }
#endregion
#region Private Helpers
- private static int GetCVTypeFromClass(Type ctype)
+ private static int GetCVTypeFromClass(Type ctype)
{
Contract.Requires(ctype != null);
#if _DEBUG
BCLDebug.Assert(ClassTypes[CV_OBJECT] == typeof(Object), "OAVariantLib::ClassTypes[CV_OBJECT] == Object.class");
#endif
-
- int cvtype=-1;
- for (int i=0; i<ClassTypes.Length; i++) {
- if (ctype.Equals(ClassTypes[i])) {
- cvtype=i;
+
+ int cvtype = -1;
+ for (int i = 0; i < ClassTypes.Length; i++)
+ {
+ if (ctype.Equals(ClassTypes[i]))
+ {
+ cvtype = i;
break;
}
}
-
+
// OleAut Binder works better if unrecognized
// types were changed to Object. So don't throw here.
if (cvtype == -1)
cvtype = CV_OBJECT;
-
+
return cvtype;
}
diff --git a/src/mscorlib/src/Microsoft/Win32/Registry.cs b/src/mscorlib/src/Microsoft/Win32/Registry.cs
index bf4f73949a..aa2dd9b396 100644
--- a/src/mscorlib/src/Microsoft/Win32/Registry.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Registry.cs
@@ -2,133 +2,12 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-
-namespace Microsoft.Win32 {
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
-
- /**
- * Registry encapsulation. Contains members representing all top level system
- * keys.
- *
- * @security(checkClassLinking=on)
- */
- //This class contains only static members and does not need to be serializable.
- internal static class Registry {
- static Registry()
- {
- }
-
- /**
- * Current User Key.
- *
- * This key should be used as the root for all user specific settings.
- */
- public static readonly RegistryKey CurrentUser = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER);
-
- /**
- * Local Machine Key.
- *
- * This key should be used as the root for all machine specific settings.
- */
- public static readonly RegistryKey LocalMachine = RegistryKey.GetBaseKey(RegistryKey.HKEY_LOCAL_MACHINE);
-
- /**
- * Classes Root Key.
- *
- * This is the root key of class information.
- */
- public static readonly RegistryKey ClassesRoot = RegistryKey.GetBaseKey(RegistryKey.HKEY_CLASSES_ROOT);
-
- /**
- * Users Root Key.
- *
- * This is the root of users.
- */
- public static readonly RegistryKey Users = RegistryKey.GetBaseKey(RegistryKey.HKEY_USERS);
-
- /**
- * Performance Root Key.
- *
- * This is where dynamic performance data is stored on NT.
- */
- public static readonly RegistryKey PerformanceData = RegistryKey.GetBaseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
-
- /**
- * Current Config Root Key.
- *
- * This is where current configuration information is stored.
- */
- public static readonly RegistryKey CurrentConfig = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_CONFIG);
-
- //
- // Following function will parse a keyName and returns the basekey for it.
- // It will also store the subkey name in the out parameter.
- // If the keyName is not valid, we will throw ArgumentException.
- // The return value shouldn't be null.
- //
- private static RegistryKey GetBaseKeyFromKeyName(string keyName, out string subKeyName) {
- if( keyName == null) {
- throw new ArgumentNullException(nameof(keyName));
- }
-
- string basekeyName;
- int i = keyName.IndexOf('\\');
- if( i != -1) {
- basekeyName = keyName.Substring(0, i).ToUpper(System.Globalization.CultureInfo.InvariantCulture);
- }
- else {
- basekeyName = keyName.ToUpper(System.Globalization.CultureInfo.InvariantCulture);
- }
- RegistryKey basekey = null;
-
- switch(basekeyName) {
- case "HKEY_CURRENT_USER":
- basekey = Registry.CurrentUser;
- break;
- case "HKEY_LOCAL_MACHINE":
- basekey = Registry.LocalMachine;
- break;
- case "HKEY_CLASSES_ROOT":
- basekey = Registry.ClassesRoot;
- break;
- case "HKEY_USERS":
- basekey = Registry.Users;
- break;
- case "HKEY_PERFORMANCE_DATA":
- basekey = Registry.PerformanceData;
- break;
- case "HKEY_CURRENT_CONFIG":
- basekey = Registry.CurrentConfig;
- break;
- default:
- throw new ArgumentException(Environment.GetResourceString("Arg_RegInvalidKeyName", nameof(keyName)));
- }
- if( i == -1 || i == keyName.Length) {
- subKeyName = string.Empty;
- }
- else {
- subKeyName = keyName.Substring(i + 1, keyName.Length - i - 1);
- }
- return basekey;
- }
-
- public static object GetValue(string keyName, string valueName, object defaultValue ) {
- string subKeyName;
- RegistryKey basekey = GetBaseKeyFromKeyName(keyName, out subKeyName);
- BCLDebug.Assert(basekey != null, "basekey can't be null.");
- RegistryKey key = basekey.OpenSubKey(subKeyName);
- if(key == null) { // if the key doesn't exist, do nothing
- return null;
- }
- try {
- return key.GetValue(valueName, defaultValue);
- }
- finally {
- key.Close();
- }
- }
+namespace Microsoft.Win32
+{
+ internal static class Registry
+ {
+ public static readonly RegistryKey CurrentUser = RegistryKey.CurrentUser;
+ public static readonly RegistryKey LocalMachine = RegistryKey.LocalMachine;
}
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
index f82b276059..e39b95903e 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
@@ -2,28 +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.
-
-/*
- Note on transaction support:
- Eventually we will want to add support for NT's transactions to our
- RegistryKey API's (possibly Whidbey M3?). When we do this, here's
- the list of API's we need to make transaction-aware:
-
- RegCreateKeyEx
- RegDeleteKey
- RegDeleteValue
- RegEnumKeyEx
- RegEnumValue
- RegOpenKeyEx
- RegQueryInfoKey
- RegQueryValueEx
- RegSetValueEx
-
- We can ignore RegConnectRegistry (remote registry access doesn't yet have
- transaction support) and RegFlushKey. RegCloseKey doesn't require any
- additional work. .
- */
-
/*
Note on ACL support:
The key thing to note about ACL's is you set them on a kernel object like a
@@ -48,70 +26,41 @@
*/
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Buffers;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
namespace Microsoft.Win32
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Security;
- using System.Text;
- using System.Threading;
- using System.IO;
- using System.Runtime.Remoting;
- using System.Runtime.InteropServices;
- using Microsoft.Win32.SafeHandles;
- using System.Runtime.Versioning;
- using System.Globalization;
- using System.Diagnostics.Contracts;
- using System.Diagnostics.CodeAnalysis;
-
/**
* Registry encapsulation. To get an instance of a RegistryKey use the
* Registry class's static members then call OpenSubKey.
- *
- * @see Registry
- * @security(checkDllCalls=off)
- * @security(checkClassLinking=on)
*/
- internal sealed class RegistryKey : MarshalByRefObject, IDisposable
+ internal sealed class RegistryKey : MarshalByRefObject, IDisposable
{
+ // Use the public Registry.CurrentUser
+ internal static readonly RegistryKey CurrentUser =
+ GetBaseKey(new IntPtr(unchecked((int)0x80000001)), "HKEY_CURRENT_USER");
+
+ // Use the public Registry.LocalMachine
+ internal static readonly RegistryKey LocalMachine =
+ GetBaseKey(new IntPtr(unchecked((int)0x80000002)), "HKEY_LOCAL_MACHINE");
// We could use const here, if C# supported ELEMENT_TYPE_I fully.
- internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000));
- internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
- internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
- internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003));
- internal static readonly IntPtr HKEY_PERFORMANCE_DATA = new IntPtr(unchecked((int)0x80000004));
- internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005));
-
- // Dirty indicates that we have munged data that should be potentially
- // written to disk.
- //
- private const int STATE_DIRTY = 0x0001;
+ private static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001));
+ private static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002));
// SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened"
// or "closed".
//
- private const int STATE_SYSTEMKEY = 0x0002;
+ private const int STATE_SYSTEMKEY = 0x0002;
// Access
//
- private const int STATE_WRITEACCESS = 0x0004;
-
- // Indicates if this key is for HKEY_PERFORMANCE_DATA
- private const int STATE_PERF_DATA = 0x0008;
-
- // Names of keys. This array must be in the same order as the HKEY values listed above.
- //
- private static readonly String[] hkeyNames = new String[] {
- "HKEY_CLASSES_ROOT",
- "HKEY_CURRENT_USER",
- "HKEY_LOCAL_MACHINE",
- "HKEY_USERS",
- "HKEY_PERFORMANCE_DATA",
- "HKEY_CURRENT_CONFIG",
- };
+ private const int STATE_WRITEACCESS = 0x0004;
// MSDN defines the following limits for registry key names & values:
// Key Name: 255 characters
@@ -122,30 +71,7 @@ namespace Microsoft.Win32
private volatile SafeRegistryHandle hkey = null;
private volatile int state = 0;
- private volatile String keyName;
- private volatile bool remoteKey = false;
- private volatile RegistryKeyPermissionCheck checkMode;
- 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
- };
-
+ private volatile string keyName;
/**
* Creates a RegistryKey.
@@ -156,37 +82,32 @@ namespace Microsoft.Win32
* The remoteKey flag when set to true indicates that we are dealing with registry entries
* on a remote machine and requires the program making these calls to have full trust.
*/
- private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, bool remoteKey, bool isPerfData, RegistryView view) {
+ private RegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey)
+ {
this.hkey = hkey;
- this.keyName = "";
- this.remoteKey = remoteKey;
- this.regView = view;
- if (systemkey) {
- this.state |= STATE_SYSTEMKEY;
+ keyName = "";
+ if (systemkey)
+ {
+ state |= STATE_SYSTEMKEY;
}
- if (writable) {
- this.state |= STATE_WRITEACCESS;
+ if (writable)
+ {
+ state |= STATE_WRITEACCESS;
}
- if (isPerfData)
- this.state |= STATE_PERF_DATA;
- ValidateKeyView(view);
- }
-
- /**
- * Closes this key, flushes it to disk if the contents have been modified.
- */
- public void Close() {
- Dispose(true);
}
- private void Dispose(bool disposing) {
- if (hkey != null) {
-
- if (!IsSystemKey()) {
- try {
+ private void Dispose(bool disposing)
+ {
+ if (hkey != null)
+ {
+ if (!IsSystemKey())
+ {
+ try
+ {
hkey.Dispose();
}
- catch (IOException){
+ catch (IOException)
+ {
// we don't really care if the handle is invalid at this point
}
finally
@@ -194,20 +115,6 @@ namespace Microsoft.Win32
hkey = null;
}
}
- else if (disposing && IsPerfDataKey()) {
- // System keys should never be closed. However, we want to call RegCloseKey
- // on HKEY_PERFORMANCE_DATA when called from PerformanceCounter.CloseSharedResources
- // (i.e. when disposing is true) so that we release the PERFLIB cache and cause it
- // to be refreshed (by re-reading the registry) when accessed subsequently.
- // This is the only way we can see the just installed perf counter.
- // NOTE: since HKEY_PERFORMANCE_DATA is process wide, there is inherent race condition in closing
- // the key asynchronously. While Vista is smart enough to rebuild the PERFLIB resources
- // in this situation the down level OSes are not. We have a small window between
- // the dispose below and usage elsewhere (other threads). This is By Design.
- // This is less of an issue when OS > NT5 (i.e Vista & higher), we can close the perfkey
- // (to release & refresh PERFLIB resources) and the OS will rebuild PERFLIB as necessary.
- SafeRegistryHandle.RegCloseKey(RegistryKey.HKEY_PERFORMANCE_DATA);
- }
}
}
@@ -216,278 +123,199 @@ namespace Microsoft.Win32
Dispose(true);
}
- public void DeleteValue(String name, bool throwOnMissingValue) {
+ public void DeleteValue(string name, bool throwOnMissingValue)
+ {
EnsureWriteable();
- CheckPermission(RegistryInternalCheck.CheckValueWritePermission, name, false, RegistryKeyPermissionCheck.Default);
int errorCode = Win32Native.RegDeleteValue(hkey, name);
-
+
//
- // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
+ // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE
// This still means the name doesn't exist. We need to be consistent with previous OS.
//
- if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) {
- if (throwOnMissingValue) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyValueAbsent);
+ if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
+ {
+ if (throwOnMissingValue)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSubKeyValueAbsent);
}
+
// Otherwise, just return giving no indication to the user.
// (For compatibility)
}
+
// We really should throw an exception here if errorCode was bad,
// but we can't for compatibility reasons.
- BCLDebug.Correctness(errorCode == 0, "RegDeleteValue failed. Here's your error code: "+errorCode);
- }
-
- /**
- * Retrieves a new RegistryKey that represents the requested key. Valid
- * values are:
- *
- * HKEY_CLASSES_ROOT,
- * HKEY_CURRENT_USER,
- * HKEY_LOCAL_MACHINE,
- * HKEY_USERS,
- * HKEY_PERFORMANCE_DATA,
- * HKEY_CURRENT_CONFIG,
- * HKEY_DYN_DATA.
- *
- * @param hKey HKEY_* to open.
- *
- * @return the RegistryKey requested.
- */
- internal static RegistryKey GetBaseKey(IntPtr hKey) {
- return GetBaseKey(hKey, RegistryView.Default);
+ Debug.Assert(errorCode == 0, "RegDeleteValue failed. Here's your error code: " + errorCode);
}
- internal static RegistryKey GetBaseKey(IntPtr hKey, RegistryView view) {
-
- int index = ((int)hKey) & 0x0FFFFFFF;
- BCLDebug.Assert(index >= 0 && index < hkeyNames.Length, "index is out of range!");
- BCLDebug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!");
-
- bool isPerf = hKey == HKEY_PERFORMANCE_DATA;
- // only mark the SafeHandle as ownsHandle if the key is HKEY_PERFORMANCE_DATA.
- SafeRegistryHandle srh = new SafeRegistryHandle(hKey, isPerf);
+ private static RegistryKey GetBaseKey(IntPtr hKey, string keyName)
+ {
+ SafeRegistryHandle srh = new SafeRegistryHandle(hKey, ownsHandle: false);
- RegistryKey key = new RegistryKey(srh, true, true,false, isPerf, view);
- key.checkMode = RegistryKeyPermissionCheck.Default;
- key.keyName = hkeyNames[index];
+ RegistryKey key = new RegistryKey(srh, true, true);
+ key.keyName = keyName;
return key;
}
- /**
- * Retrieves a subkey. If readonly is <b>true</b>, then the subkey is opened with
- * read-only access.
- *
- * @param name Name or path of subkey to open.
- * @param readonly Set to <b>true</b> if you only need readonly access.
- *
- * @return the Subkey requested, or <b>null</b> if the operation failed.
- */
- public RegistryKey OpenSubKey(string name, bool writable ) {
+ /// <summary>
+ /// Retrieves a subkey or null if the operation failed.
+ /// </summary>
+ /// <param name="writable">True to open writable, otherwise opens the key read-only.</param>
+ public RegistryKey OpenSubKey(string name, bool writable)
+ {
ValidateKeyName(name);
EnsureNotDisposed();
- name = FixupName(name); // Fixup multiple slashes to a single slash
- CheckPermission(RegistryInternalCheck.CheckOpenSubKeyWithWritablePermission, name, writable, RegistryKeyPermissionCheck.Default);
SafeRegistryHandle result = null;
int ret = Win32Native.RegOpenKeyEx(hkey,
name,
0,
- GetRegistryKeyAccess(writable) | (int)regView,
+ writable ? Win32Native.KEY_READ | Win32Native.KEY_WRITE : Win32Native.KEY_READ,
out result);
- if (ret == 0 && !result.IsInvalid) {
- RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
- key.checkMode = GetSubKeyPermissonCheck(writable);
+ if (ret == 0 && !result.IsInvalid)
+ {
+ RegistryKey key = new RegistryKey(result, writable, false);
key.keyName = keyName + "\\" + name;
return key;
}
// Return null if we didn't find the key.
- if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) {
+ if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL)
+ {
// We need to throw SecurityException here for compatibility reasons,
// although UnauthorizedAccessException will make more sense.
ThrowHelper.ThrowSecurityException(ExceptionResource.Security_RegistryPermission);
}
-
- 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.
- *
- * @param name Name or path of subkey to open.
- *
- * @return the Subkey requested, or <b>null</b> if the operation failed.
- */
- public RegistryKey OpenSubKey(String name) {
- return OpenSubKey(name, false);
- }
-
- internal int InternalSubKeyCount() {
- EnsureNotDisposed();
-
- int subkeys = 0;
- int junk = 0;
- int ret = Win32Native.RegQueryInfoKey(hkey,
- null,
- null,
- IntPtr.Zero,
- ref subkeys, // subkeys
- null,
- null,
- ref junk, // values
- null,
- null,
- null,
- null);
-
- if (ret != 0)
- Win32Error(ret, null);
- return subkeys;
- }
-
- /**
- * Retrieves an array of strings containing all the subkey names.
- *
- * @return all subkey names.
- */
- public String[] GetSubKeyNames() {
- CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
- return InternalGetSubKeyNames();
- }
-
- internal unsafe String[] InternalGetSubKeyNames() {
+ /// <summary>
+ /// Retrieves an array of strings containing all the subkey names.
+ /// </summary>
+ public string[] GetSubKeyNames()
+ {
EnsureNotDisposed();
- int subkeys = InternalSubKeyCount();
- String[] names = new String[subkeys]; // Returns 0-length array if empty.
- if (subkeys > 0) {
- char[] name = new char[MaxKeyLength + 1];
-
- int namelen;
+ var names = new List<string>();
+ char[] name = ArrayPool<char>.Shared.Rent(MaxKeyLength + 1);
- fixed (char *namePtr = &name[0])
+ try
+ {
+ int result;
+ int nameLength = name.Length;
+
+ while ((result = Win32Native.RegEnumKeyEx(
+ hkey,
+ names.Count,
+ name,
+ ref nameLength,
+ null,
+ null,
+ null,
+ null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
- for (int i=0; i<subkeys; i++) {
- namelen = name.Length; // Don't remove this. The API's doesn't work if this is not properly initialised.
- int ret = Win32Native.RegEnumKeyEx(hkey,
- i,
- namePtr,
- ref namelen,
- null,
- null,
- null,
- null);
- if (ret != 0)
- Win32Error(ret, null);
- names[i] = new String(namePtr);
+ switch (result)
+ {
+ case Interop.Errors.ERROR_SUCCESS:
+ names.Add(new string(name, 0, nameLength));
+ nameLength = name.Length;
+ break;
+ default:
+ // Throw the error
+ Win32Error(result, null);
+ break;
}
}
}
+ finally
+ {
+ ArrayPool<char>.Shared.Return(name);
+ }
- return names;
+ return names.ToArray();
}
- internal int InternalValueCount() {
- EnsureNotDisposed();
- int values = 0;
- int junk = 0;
- int ret = Win32Native.RegQueryInfoKey(hkey,
- null,
- null,
- IntPtr.Zero,
- ref junk, // subkeys
- null,
- null,
- ref values, // values
- null,
- null,
- null,
- null);
- if (ret != 0)
- Win32Error(ret, null);
- return values;
- }
-
- /**
- * Retrieves an array of strings containing all the value names.
- *
- * @return all value names.
- */
- public unsafe String[] GetValueNames() {
- CheckPermission(RegistryInternalCheck.CheckKeyReadPermission, null, false, RegistryKeyPermissionCheck.Default);
+ /// <summary>
+ /// Retrieves an array of strings containing all the value names.
+ /// </summary>
+ public unsafe string[] GetValueNames()
+ {
EnsureNotDisposed();
+ var names = new List<string>();
- int values = InternalValueCount();
- String[] names = new String[values];
+ // Names in the registry aren't usually very long, although they can go to as large
+ // as 16383 characters (MaxValueLength).
+ //
+ // Every call to RegEnumValue will allocate another buffer to get the data from
+ // NtEnumerateValueKey before copying it back out to our passed in buffer. This can
+ // add up quickly- we'll try to keep the memory pressure low and grow the buffer
+ // only if needed.
- if (values > 0) {
- char[] name = new char[MaxValueLength + 1];
- int namelen;
+ char[] name = ArrayPool<char>.Shared.Rent(100);
- fixed (char *namePtr = &name[0])
+ try
+ {
+ int result;
+ int nameLength = name.Length;
+
+ while ((result = Win32Native.RegEnumValue(
+ hkey,
+ names.Count,
+ name,
+ ref nameLength,
+ IntPtr.Zero,
+ null,
+ null,
+ null)) != Interop.Errors.ERROR_NO_MORE_ITEMS)
{
- for (int i=0; i<values; i++) {
- namelen = name.Length;
-
- int ret = Win32Native.RegEnumValue(hkey,
- i,
- namePtr,
- ref namelen,
- IntPtr.Zero,
- null,
- null,
- null);
-
- if (ret != 0) {
- // ignore ERROR_MORE_DATA if we're querying HKEY_PERFORMANCE_DATA
- if (!(IsPerfDataKey() && ret == Win32Native.ERROR_MORE_DATA))
- Win32Error(ret, null);
- }
-
- names[i] = new String(namePtr);
+ switch (result)
+ {
+ // The size is only ever reported back correctly in the case
+ // of ERROR_SUCCESS. It will almost always be changed, however.
+ case Interop.Errors.ERROR_SUCCESS:
+ names.Add(new string(name, 0, nameLength));
+ break;
+ case Interop.Errors.ERROR_MORE_DATA:
+ if (IsPerfDataKey())
+ {
+ // Enumerating the values for Perf keys always returns
+ // ERROR_MORE_DATA, but has a valid name. Buffer does need
+ // to be big enough however. 8 characters is the largest
+ // known name. The size isn't returned, but the string is
+ // null terminated.
+ fixed (char* c = &name[0])
+ {
+ names.Add(new string(c));
+ }
+ }
+ else
+ {
+ char[] oldName = name;
+ int oldLength = oldName.Length;
+ name = null;
+ ArrayPool<char>.Shared.Return(oldName);
+ name = ArrayPool<char>.Shared.Rent(checked(oldLength * 2));
+ }
+ break;
+ default:
+ // Throw the error
+ Win32Error(result, null);
+ break;
}
+
+ // Always set the name length back to the buffer size
+ nameLength = name.Length;
}
}
+ finally
+ {
+ if (name != null)
+ ArrayPool<char>.Shared.Return(name);
+ }
- return names;
- }
-
- /**
- * Retrieves the specified value. <b>null</b> is returned if the value
- * doesn't exist.
- *
- * 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.
- *
- * @param name Name of value to retrieve.
- *
- * @return the data associated with the value.
- */
- public Object GetValue(String name) {
- CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
- return InternalGetValue(name, null, false, true);
+ return names.ToArray();
}
/**
@@ -505,426 +333,257 @@ namespace Microsoft.Win32
*
* @return the data associated with the value.
*/
- public Object GetValue(String name, Object defaultValue) {
- CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
- return InternalGetValue(name, defaultValue, false, true);
- }
-
- public Object GetValue(String name, Object defaultValue, RegistryValueOptions options) {
- if( options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options), nameof(options));
- }
- bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames);
- CheckPermission(RegistryInternalCheck.CheckValueReadPermission, name, false, RegistryKeyPermissionCheck.Default);
- return InternalGetValue(name, defaultValue, doNotExpand, true);
- }
-
- internal Object InternalGetValue(String name, Object defaultValue, bool doNotExpand, bool checkSecurity) {
- if (checkSecurity) {
- // Name can be null! It's the most common use of RegQueryValueEx
- EnsureNotDisposed();
- }
+ public object GetValue(string name, object defaultValue = null, bool doNotExpand = false)
+ {
+ EnsureNotDisposed();
- Object data = defaultValue;
+ object data = defaultValue;
int type = 0;
int datasize = 0;
int ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
- if (ret != 0) {
- if (IsPerfDataKey()) {
- int size = 65000;
- int sizeInput = size;
-
- int r;
- byte[] blob = new byte[size];
- while (Win32Native.ERROR_MORE_DATA == (r = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref sizeInput))) {
- if (size == Int32.MaxValue) {
- // ERROR_MORE_DATA was returned however we cannot increase the buffer size beyond Int32.MaxValue
- Win32Error(r, name);
- }
- else if (size > (Int32.MaxValue / 2)) {
- // at this point in the loop "size * 2" would cause an overflow
- size = Int32.MaxValue;
- }
- else {
- size *= 2;
- }
- sizeInput = size;
- blob = new byte[size];
- }
- if (r != 0)
- Win32Error(r, name);
- return blob;
- }
- else {
- // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
- // Some OS's returned ERROR_MORE_DATA even in success cases, so we
- // want to continue on through the function.
- if (ret != Win32Native.ERROR_MORE_DATA)
- return data;
- }
+ if (ret != 0)
+ {
+ // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data).
+ // Some OS's returned ERROR_MORE_DATA even in success cases, so we
+ // want to continue on through the function.
+ if (ret != Win32Native.ERROR_MORE_DATA)
+ return data;
}
- if (datasize < 0) {
+ if (datasize < 0)
+ {
// unexpected code path
- BCLDebug.Assert(false, "[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
+ Debug.Assert(false, "[InternalGetValue] RegQueryValue returned ERROR_SUCCESS but gave a negative datasize");
datasize = 0;
}
+ switch (type)
+ {
+ case Win32Native.REG_NONE:
+ case Win32Native.REG_DWORD_BIG_ENDIAN:
+ case Win32Native.REG_BINARY:
+ {
+ byte[] blob = new byte[datasize];
+ ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
+ data = blob;
+ }
+ break;
+ case Win32Native.REG_QWORD:
+ { // also REG_QWORD_LITTLE_ENDIAN
+ if (datasize > 8)
+ {
+ // prevent an AV in the edge case that datasize is larger than sizeof(long)
+ goto case Win32Native.REG_BINARY;
+ }
+ long blob = 0;
+ Debug.Assert(datasize == 8, "datasize==8");
+ // Here, datasize must be 8 when calling this
+ ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
- switch (type) {
- case Win32Native.REG_NONE:
- case Win32Native.REG_DWORD_BIG_ENDIAN:
- case Win32Native.REG_BINARY: {
- byte[] blob = new byte[datasize];
- ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
- data = blob;
- }
- break;
- case Win32Native.REG_QWORD:
- { // also REG_QWORD_LITTLE_ENDIAN
- if (datasize > 8) {
- // prevent an AV in the edge case that datasize is larger than sizeof(long)
- goto case Win32Native.REG_BINARY;
- }
- long blob = 0;
- BCLDebug.Assert(datasize==8, "datasize==8");
- // Here, datasize must be 8 when calling this
- ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
-
- data = blob;
- }
- break;
- case Win32Native.REG_DWORD:
- { // also REG_DWORD_LITTLE_ENDIAN
- if (datasize > 4) {
- // prevent an AV in the edge case that datasize is larger than sizeof(int)
- goto case Win32Native.REG_QWORD;
- }
- int blob = 0;
- BCLDebug.Assert(datasize==4, "datasize==4");
- // Here, datasize must be four when calling this
- ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
-
- data = blob;
- }
- break;
-
- case Win32Native.REG_SZ:
- {
- if (datasize % 2 == 1) {
- // handle the case where the registry contains an odd-byte length (corrupt data?)
- try {
- datasize = checked(datasize + 1);
- }
- catch (OverflowException e) {
- throw new IOException(Environment.GetResourceString("Arg_RegGetOverflowBug"), e);
- }
- }
- char[] blob = new char[datasize/2];
-
- ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
- if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) {
- data = new String(blob, 0, blob.Length - 1);
- }
- else {
- // in the very unlikely case the data is missing null termination,
- // pass in the whole char[] to prevent truncating a character
- data = new String(blob);
- }
- }
- break;
-
- case Win32Native.REG_EXPAND_SZ:
- {
- if (datasize % 2 == 1) {
- // handle the case where the registry contains an odd-byte length (corrupt data?)
- try {
- datasize = checked(datasize + 1);
- }
- catch (OverflowException e) {
- throw new IOException(Environment.GetResourceString("Arg_RegGetOverflowBug"), e);
- }
- }
- char[] blob = new char[datasize/2];
-
- ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
-
- if (blob.Length > 0 && blob[blob.Length - 1] == (char)0) {
- data = new String(blob, 0, blob.Length - 1);
- }
- else {
- // in the very unlikely case the data is missing null termination,
- // pass in the whole char[] to prevent truncating a character
- data = new String(blob);
- }
-
- if (!doNotExpand)
- data = Environment.ExpandEnvironmentVariables((String)data);
- }
- break;
- case Win32Native.REG_MULTI_SZ:
- {
- if (datasize % 2 == 1) {
- // handle the case where the registry contains an odd-byte length (corrupt data?)
- try {
- datasize = checked(datasize + 1);
- }
- catch (OverflowException e) {
- throw new IOException(Environment.GetResourceString("Arg_RegGetOverflowBug"), e);
- }
- }
- char[] blob = new char[datasize/2];
-
- ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
-
- // make sure the string is null terminated before processing the data
- if (blob.Length > 0 && blob[blob.Length - 1] != (char)0) {
- try {
- char[] newBlob = new char[checked(blob.Length + 1)];
- for (int i = 0; i < blob.Length; i++) {
- newBlob[i] = blob[i];
- }
- newBlob[newBlob.Length - 1] = (char)0;
- blob = newBlob;
- }
- catch (OverflowException e) {
- throw new IOException(Environment.GetResourceString("Arg_RegGetOverflowBug"), e);
- }
- blob[blob.Length - 1] = (char)0;
- }
-
-
- IList<String> strings = new List<String>();
- int cur = 0;
- int len = blob.Length;
-
- while (ret == 0 && cur < len) {
- int nextNull = cur;
- while (nextNull < len && blob[nextNull] != (char)0) {
- nextNull++;
- }
-
- if (nextNull < len) {
- BCLDebug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
- if (nextNull-cur > 0) {
- strings.Add(new String(blob, cur, nextNull-cur));
- }
- else {
- // we found an empty string. But if we're at the end of the data,
- // it's just the extra null terminator.
- if (nextNull != len-1)
- strings.Add(String.Empty);
- }
- }
- else {
- strings.Add(new String(blob, cur, len-cur));
- }
- cur = nextNull+1;
- }
-
- data = new String[strings.Count];
- strings.CopyTo((String[])data, 0);
- }
- break;
- case Win32Native.REG_LINK:
- default:
- break;
- }
-
- return data;
- }
-
- private bool IsSystemKey() {
- return (this.state & STATE_SYSTEMKEY) != 0;
- }
-
- private bool IsWritable() {
- return (this.state & STATE_WRITEACCESS) != 0;
- }
-
- private bool IsPerfDataKey() {
- return (this.state & STATE_PERF_DATA) != 0;
- }
-
- private void SetDirty() {
- this.state |= STATE_DIRTY;
- }
-
- /**
- * Sets the specified value.
- *
- * @param name Name of value to store data in.
- * @param value Data to store.
- */
- public void SetValue(String name, Object value) {
- SetValue(name, value, RegistryValueKind.Unknown);
- }
-
- public unsafe void SetValue(String name, Object value, RegistryValueKind valueKind) {
- if (value==null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
+ data = blob;
+ }
+ break;
+ case Win32Native.REG_DWORD:
+ { // also REG_DWORD_LITTLE_ENDIAN
+ if (datasize > 4)
+ {
+ // prevent an AV in the edge case that datasize is larger than sizeof(int)
+ goto case Win32Native.REG_QWORD;
+ }
+ int blob = 0;
+ Debug.Assert(datasize == 4, "datasize==4");
+ // Here, datasize must be four when calling this
+ ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, ref blob, ref datasize);
- if (name != null && name.Length > MaxValueLength) {
- throw new ArgumentException(Environment.GetResourceString("Arg_RegValStrLenBug"));
- }
+ data = blob;
+ }
+ break;
- if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind))
- throw new ArgumentException(Environment.GetResourceString("Arg_RegBadKeyKind"), nameof(valueKind));
+ case Win32Native.REG_SZ:
+ {
+ if (datasize % 2 == 1)
+ {
+ // handle the case where the registry contains an odd-byte length (corrupt data?)
+ try
+ {
+ datasize = checked(datasize + 1);
+ }
+ catch (OverflowException e)
+ {
+ throw new IOException(SR.Arg_RegGetOverflowBug, e);
+ }
+ }
+ char[] blob = new char[datasize / 2];
- EnsureWriteable();
+ ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
+ if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
+ {
+ data = new string(blob, 0, blob.Length - 1);
+ }
+ else
+ {
+ // in the very unlikely case the data is missing null termination,
+ // pass in the whole char[] to prevent truncating a character
+ data = new string(blob);
+ }
+ }
+ break;
- if (!remoteKey && ContainsRegistryValue(name)) { // Existing key
- CheckPermission(RegistryInternalCheck.CheckValueWritePermission, name, false, RegistryKeyPermissionCheck.Default);
- }
- else { // Creating a new value
- CheckPermission(RegistryInternalCheck.CheckValueCreatePermission, name, false, RegistryKeyPermissionCheck.Default);
- }
+ case Win32Native.REG_EXPAND_SZ:
+ {
+ if (datasize % 2 == 1)
+ {
+ // handle the case where the registry contains an odd-byte length (corrupt data?)
+ try
+ {
+ datasize = checked(datasize + 1);
+ }
+ catch (OverflowException e)
+ {
+ throw new IOException(SR.Arg_RegGetOverflowBug, e);
+ }
+ }
+ char[] blob = new char[datasize / 2];
- if (valueKind == RegistryValueKind.Unknown) {
- // this is to maintain compatibility with the old way of autodetecting the type.
- // SetValue(string, object) will come through this codepath.
- valueKind = CalculateValueKind(value);
- }
+ ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
- int ret = 0;
- try {
- switch (valueKind) {
- case RegistryValueKind.ExpandString:
- case RegistryValueKind.String:
+ if (blob.Length > 0 && blob[blob.Length - 1] == (char)0)
{
- String data = value.ToString();
- ret = Win32Native.RegSetValueEx(hkey,
- name,
- 0,
- valueKind,
- data,
- checked(data.Length * 2 + 2));
- break;
+ data = new string(blob, 0, blob.Length - 1);
+ }
+ else
+ {
+ // in the very unlikely case the data is missing null termination,
+ // pass in the whole char[] to prevent truncating a character
+ data = new string(blob);
}
- case RegistryValueKind.MultiString:
+ if (!doNotExpand)
+ data = Environment.ExpandEnvironmentVariables((string)data);
+ }
+ break;
+ case Win32Native.REG_MULTI_SZ:
+ {
+ if (datasize % 2 == 1)
{
- // Other thread might modify the input array after we calculate the buffer length.
- // Make a copy of the input array to be safe.
- string[] dataStrings = (string[])(((string[])value).Clone());
- int sizeInBytes = 0;
-
- // First determine the size of the array
- //
- for (int i=0; i<dataStrings.Length; i++) {
- if (dataStrings[i] == null) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetStrArrNull);
- }
- sizeInBytes = checked(sizeInBytes + (dataStrings[i].Length+1) * 2);
- }
- sizeInBytes = checked(sizeInBytes + 2);
-
- byte[] basePtr = new byte[sizeInBytes];
- fixed(byte* b = basePtr) {
- IntPtr currentPtr = new IntPtr( (void *) b);
-
- // Write out the strings...
- //
- for (int i=0; i<dataStrings.Length; i++) {
- // Assumes that the Strings are always null terminated.
- String.InternalCopy(dataStrings[i],currentPtr,(checked(dataStrings[i].Length*2)));
- currentPtr = new IntPtr((long)currentPtr + (checked(dataStrings[i].Length*2)));
- *(char*)(currentPtr.ToPointer()) = '\0';
- currentPtr = new IntPtr((long)currentPtr + 2);
- }
-
- *(char*)(currentPtr.ToPointer()) = '\0';
- currentPtr = new IntPtr((long)currentPtr + 2);
-
- ret = Win32Native.RegSetValueEx(hkey,
- name,
- 0,
- RegistryValueKind.MultiString,
- basePtr,
- sizeInBytes);
+ // handle the case where the registry contains an odd-byte length (corrupt data?)
+ try
+ {
+ datasize = checked(datasize + 1);
+ }
+ catch (OverflowException e)
+ {
+ throw new IOException(SR.Arg_RegGetOverflowBug, e);
}
- break;
}
+ char[] blob = new char[datasize / 2];
- case RegistryValueKind.None:
- case RegistryValueKind.Binary:
- byte[] dataBytes = (byte[]) value;
- ret = Win32Native.RegSetValueEx(hkey,
- name,
- 0,
- (valueKind == RegistryValueKind.None ? Win32Native.REG_NONE: RegistryValueKind.Binary),
- dataBytes,
- dataBytes.Length);
- break;
-
- case RegistryValueKind.DWord:
+ ret = Win32Native.RegQueryValueEx(hkey, name, null, ref type, blob, ref datasize);
+
+ // make sure the string is null terminated before processing the data
+ if (blob.Length > 0 && blob[blob.Length - 1] != (char)0)
{
- // We need to use Convert here because we could have a boxed type cannot be
- // unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail.
- int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture);
-
- ret = Win32Native.RegSetValueEx(hkey,
- name,
- 0,
- RegistryValueKind.DWord,
- ref data,
- 4);
- break;
+ try
+ {
+ char[] newBlob = new char[checked(blob.Length + 1)];
+ for (int i = 0; i < blob.Length; i++)
+ {
+ newBlob[i] = blob[i];
+ }
+ newBlob[newBlob.Length - 1] = (char)0;
+ blob = newBlob;
+ }
+ catch (OverflowException e)
+ {
+ throw new IOException(SR.Arg_RegGetOverflowBug, e);
+ }
+ blob[blob.Length - 1] = (char)0;
}
- case RegistryValueKind.QWord:
+ IList<string> strings = new List<string>();
+ int cur = 0;
+ int len = blob.Length;
+
+ while (ret == 0 && cur < len)
{
- long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture);
-
- ret = Win32Native.RegSetValueEx(hkey,
- name,
- 0,
- RegistryValueKind.QWord,
- ref data,
- 8);
- break;
+ int nextNull = cur;
+ while (nextNull < len && blob[nextNull] != (char)0)
+ {
+ nextNull++;
+ }
+
+ if (nextNull < len)
+ {
+ Debug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0");
+ if (nextNull - cur > 0)
+ {
+ strings.Add(new string(blob, cur, nextNull - cur));
+ }
+ else
+ {
+ // we found an empty string. But if we're at the end of the data,
+ // it's just the extra null terminator.
+ if (nextNull != len - 1)
+ strings.Add(string.Empty);
+ }
+ }
+ else
+ {
+ strings.Add(new string(blob, cur, len - cur));
+ }
+ cur = nextNull + 1;
}
- }
- }
- catch (OverflowException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
- }
- catch (InvalidOperationException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
- }
- catch (FormatException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
- }
- catch (InvalidCastException) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegSetMismatchedKind);
- }
- if (ret == 0) {
- SetDirty();
+ data = new string[strings.Count];
+ strings.CopyTo((string[])data, 0);
+ }
+ break;
+ case Win32Native.REG_LINK:
+ default:
+ break;
}
- else
- Win32Error(ret, null);
+ return data;
+ }
+
+ private bool IsSystemKey()
+ {
+ return (state & STATE_SYSTEMKEY) != 0;
}
- private RegistryValueKind CalculateValueKind(Object value) {
- // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days.
- // Even though we could add detection for an int64 in here, we want to maintain compatibility with the
- // old behavior.
- if (value is Int32)
- return RegistryValueKind.DWord;
- else if (value is Array) {
- if (value is byte[])
- return RegistryValueKind.Binary;
- else if (value is String[])
- return RegistryValueKind.MultiString;
- else
- throw new ArgumentException(Environment.GetResourceString("Arg_RegSetBadArrType", value.GetType().Name));
+ private bool IsWritable()
+ {
+ return (state & STATE_WRITEACCESS) != 0;
+ }
+
+ private bool IsPerfDataKey()
+ {
+ return false;
+ }
+
+ public unsafe void SetStringValue(string name, string value)
+ {
+ if (value == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
+
+ if (name != null && name.Length > MaxValueLength)
+ {
+ throw new ArgumentException(SR.Arg_RegValStrLenBug);
}
- else
- return RegistryValueKind.String;
+
+ EnsureWriteable();
+
+ int result = Win32Native.RegSetValueEx(hkey,
+ name,
+ 0,
+ RegistryValueKind.String,
+ value,
+ checked(value.Length * 2 + 2));
+
+ if (result != 0)
+ Win32Error(result, null);
}
/**
@@ -932,7 +591,8 @@ namespace Microsoft.Win32
*
* @return a string representing the key.
*/
- public override String ToString() {
+ public override string ToString()
+ {
EnsureNotDisposed();
return keyName;
}
@@ -944,164 +604,51 @@ namespace Microsoft.Win32
* error, and depending on the error, insert a string into the message
* gotten from the ResourceManager.
*/
- internal void Win32Error(int errorCode, String str) {
- switch (errorCode) {
+ internal void Win32Error(int errorCode, string str)
+ {
+ switch (errorCode)
+ {
case Win32Native.ERROR_ACCESS_DENIED:
if (str != null)
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_RegistryKeyGeneric_Key", str));
+ throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_RegistryKeyGeneric_Key, str));
else
throw new UnauthorizedAccessException();
-
- case Win32Native.ERROR_INVALID_HANDLE:
- /**
- * For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException.
- * However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the
- * SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues
- * in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception
- * on reentrant calls because of this error code path in RegistryKey
- *
- * Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this,
- * however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on
- * this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of
- * having serialized access).
- */
- if (!IsPerfDataKey()) {
- this.hkey.SetHandleAsInvalid();
- this.hkey = null;
- }
- goto default;
-
case Win32Native.ERROR_FILE_NOT_FOUND:
- throw new IOException(Environment.GetResourceString("Arg_RegKeyNotFound"), errorCode);
+ throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
throw new IOException(Win32Native.GetMessage(errorCode), errorCode);
}
}
- internal static String FixupName(String name)
- {
- BCLDebug.Assert(name!=null,"[FixupName]name!=null");
- if (name.IndexOf('\\') == -1)
- return name;
-
- StringBuilder sb = new StringBuilder(name);
- FixupPath(sb);
- int temp = sb.Length - 1;
- if (temp >= 0 && sb[temp] == '\\') // Remove trailing slash
- sb.Length = temp;
- return sb.ToString();
- }
-
-
- private static void FixupPath(StringBuilder path)
+ private void EnsureNotDisposed()
{
- Contract.Requires(path != null);
- int length = path.Length;
- bool fixup = false;
- char markerChar = (char)0xFFFF;
-
- int i = 1;
- while (i < length - 1)
- {
- if (path[i] == '\\')
- {
- i++;
- while (i < length)
- {
- if (path[i] == '\\')
- {
- path[i] = markerChar;
- i++;
- fixup = true;
- }
- else
- break;
- }
-
- }
- i++;
- }
-
- if (fixup)
+ if (hkey == null)
{
- i = 0;
- int j = 0;
- while (i < length)
- {
- if(path[i] == markerChar)
- {
- i++;
- continue;
- }
- path[j] = path[i];
- i++;
- j++;
- }
- path.Length += j - i;
- }
-
- }
-
- private void CheckPermission(RegistryInternalCheck check, string item, bool subKeyWritable, RegistryKeyPermissionCheck subKeyCheck)
- {
- // TODO: Cleanup
- }
-
- 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) {
ThrowHelper.ThrowObjectDisposedException(keyName, ExceptionResource.ObjectDisposed_RegKeyClosed);
}
}
- private void EnsureWriteable() {
+ private void EnsureWriteable()
+ {
EnsureNotDisposed();
- if (!IsWritable()) {
+ if (!IsWritable())
+ {
ThrowHelper.ThrowUnauthorizedAccessException(ExceptionResource.UnauthorizedAccess_RegistryNoWrite);
}
}
- static int GetRegistryKeyAccess(bool isWritable) {
- int winAccess;
- if (!isWritable) {
- winAccess = Win32Native.KEY_READ;
- }
- else {
- winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE;
- }
-
- return winAccess;
- }
-
- private RegistryKeyPermissionCheck GetSubKeyPermissonCheck(bool subkeyWritable) {
- if( checkMode == RegistryKeyPermissionCheck.Default) {
- return checkMode;
- }
-
- if(subkeyWritable) {
- return RegistryKeyPermissionCheck.ReadWriteSubTree;
- }
- else {
- return RegistryKeyPermissionCheck.ReadSubTree;
- }
- }
-
- static private void ValidateKeyName(string name) {
- Contract.Ensures(name != null);
- if (name == null) {
+ static private void ValidateKeyName(string name)
+ {
+ if (name == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.name);
}
int nextSlash = name.IndexOf("\\", StringComparison.OrdinalIgnoreCase);
int current = 0;
- while (nextSlash != -1) {
+ while (nextSlash != -1)
+ {
if ((nextSlash - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
@@ -1111,32 +658,11 @@ namespace Microsoft.Win32
if ((name.Length - current) > MaxKeyLength)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RegKeyStrLenBug);
-
- }
-
- static private void ValidateKeyView(RegistryView view) {
- if (view != RegistryView.Default && view != RegistryView.Registry32 && view != RegistryView.Registry64) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidRegistryViewCheck, ExceptionArgument.view);
- }
}
// Win32 constants for error handling
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
- private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
+ private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
}
-
- [Flags]
- internal enum RegistryValueOptions {
- None = 0,
- DoNotExpandEnvironmentNames = 1
- }
-
- // the name for this API is meant to mimic FileMode, which has similar values
-
- internal enum RegistryKeyPermissionCheck {
- Default = 0,
- ReadSubTree = 1,
- ReadWriteSubTree = 2
- }
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs b/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
index 5e22275332..90c880b278 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryValueKind.cs
@@ -2,17 +2,21 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+namespace Microsoft.Win32
+{
+ internal enum RegistryValueKind
+ {
+ String = Win32Native.REG_SZ,
+ ExpandString = Win32Native.REG_EXPAND_SZ,
+ Binary = Win32Native.REG_BINARY,
+ DWord = Win32Native.REG_DWORD,
+ MultiString = Win32Native.REG_MULTI_SZ,
+ QWord = Win32Native.REG_QWORD,
+ Unknown = 0,
-namespace Microsoft.Win32 {
- internal enum RegistryValueKind {
- String = Win32Native.REG_SZ,
- ExpandString = Win32Native.REG_EXPAND_SZ,
- Binary = Win32Native.REG_BINARY,
- DWord = Win32Native.REG_DWORD,
- MultiString = Win32Native.REG_MULTI_SZ,
- QWord = Win32Native.REG_QWORD,
- Unknown = 0, // REG_NONE is defined as zero but BCL
- None = unchecked((int)0xFFFFFFFF), // mistakingly overrode this value.
- } // Now instead of using Win32Native.REG_NONE we use "-1" and play games internally.
+ // REG_NONE is defined as zero but BCL, mistakingly overrode this value.
+ // Now instead of using Win32Native.REG_NONE we use "-1" and play games internally.
+ None = unchecked((int)0xFFFFFFFF),
+ }
}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryView.cs b/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
deleted file mode 100644
index 302a603e0c..0000000000
--- a/src/mscorlib/src/Microsoft/Win32/RegistryView.cs
+++ /dev/null
@@ -1,19 +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.
-
-//
-//
-//
-// Implements Microsoft.Win32.RegistryView
-//
-// ======================================================================================
-namespace Microsoft.Win32 {
- using System;
-
- internal enum RegistryView {
- Default = 0, // 0x0000 operate on the default registry view
- Registry64 = Win32Native.KEY_WOW64_64KEY, // 0x0100 operate on the 64-bit registry view
- Registry32 = Win32Native.KEY_WOW64_32KEY, // 0x0200 operate on the 32-bit registry view
- };
-}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
index 89ea22b855..d7d833d35d 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeFindHandle.cs
@@ -18,10 +18,11 @@ using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using Microsoft.Win32;
-namespace Microsoft.Win32.SafeHandles {
+namespace Microsoft.Win32.SafeHandles
+{
internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid
{
- internal SafeFindHandle() : base(true) {}
+ internal SafeFindHandle() : base(true) { }
override protected bool ReleaseHandle()
{
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
index 603558c51a..256f611463 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
@@ -2,11 +2,13 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-namespace Microsoft.Win32 {
- using Microsoft.Win32.SafeHandles;
+using Microsoft.Win32.SafeHandles;
- sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid {
- internal SafeLibraryHandle() : base(true) {}
+namespace Microsoft.Win32
+{
+ sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
+ {
+ internal SafeLibraryHandle() : base(true) { }
override protected bool ReleaseHandle()
{
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
index a1e5bc4263..1215000ec5 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeRegistryHandle.cs
@@ -2,28 +2,23 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
-//
-//
-// Implements Microsoft.Win32.SafeHandles.SafeRegistryHandle
-//
-// ======================================================================================
-namespace Microsoft.Win32.SafeHandles {
- using System;
- using System.Security;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
+using System;
+using System.Security;
+using System.Runtime.InteropServices;
- internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid {
- internal SafeRegistryHandle() : base(true) {}
+namespace Microsoft.Win32.SafeHandles
+{
+ internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid
+ {
+ internal SafeRegistryHandle() : base(true) { }
- public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) {
+ public SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle)
+ {
SetHandle(preexistingHandle);
}
- override protected bool ReleaseHandle() {
+ override protected bool ReleaseHandle()
+ {
return (RegCloseKey(handle) == Win32Native.ERROR_SUCCESS);
}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
index 0ebcd5c09e..1141e6d027 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeWaitHandle.cs
@@ -21,8 +21,8 @@ using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Threading;
-namespace Microsoft.Win32.SafeHandles {
-
+namespace Microsoft.Win32.SafeHandles
+{
public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid
{
// Called by P/Invoke marshaler
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
index 62418131f3..8a7f591dfc 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
+++ b/src/mscorlib/src/Microsoft/Win32/SafeHandles/Win32SafeHandles.cs
@@ -13,17 +13,17 @@
//
//
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+
namespace Microsoft.Win32.SafeHandles
{
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
-
// Class of safe handle which uses 0 or -1 as an invalid handle.
public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle
{
- protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
+ protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
}
@@ -33,7 +33,8 @@ namespace Microsoft.Win32.SafeHandles
throw new NotImplementedException();
}
- public override bool IsInvalid {
+ public override bool IsInvalid
+ {
get { return handle.IsNull() || handle == new IntPtr(-1); }
}
}
@@ -41,7 +42,7 @@ namespace Microsoft.Win32.SafeHandles
// Class of safe handle which uses only -1 as an invalid handle.
public abstract class SafeHandleMinusOneIsInvalid : SafeHandle
{
- protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle)
+ protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle)
{
}
@@ -51,31 +52,8 @@ namespace Microsoft.Win32.SafeHandles
throw new NotImplementedException();
}
- public override bool IsInvalid {
- get { return handle == new IntPtr(-1); }
- }
- }
-
- // Class of critical handle which uses 0 or -1 as an invalid handle.
- public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
- {
- protected CriticalHandleZeroOrMinusOneIsInvalid() : base(IntPtr.Zero)
- {
- }
-
- public override bool IsInvalid {
- get { return handle.IsNull() || handle == new IntPtr(-1); }
- }
- }
-
- // Class of critical handle which uses only -1 as an invalid handle.
- public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
- {
- protected CriticalHandleMinusOneIsInvalid() : base(new IntPtr(-1))
+ public override bool IsInvalid
{
- }
-
- public override bool IsInvalid {
get { return handle == new IntPtr(-1); }
}
}
diff --git a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
index 6e37b9c878..1b835d5dd1 100644
--- a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
+++ b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
@@ -2,7 +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.
-namespace Microsoft.Win32 {
+namespace Microsoft.Win32
+{
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
@@ -16,12 +17,12 @@ namespace Microsoft.Win32 {
using System.Diagnostics.Tracing;
[SuppressUnmanagedCodeSecurityAttribute()]
- internal static class UnsafeNativeMethods {
-
- [DllImport(Win32Native.KERNEL32, EntryPoint="GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
+ internal static class UnsafeNativeMethods
+ {
+ [DllImport(Win32Native.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(Win32Native.KERNEL32, EntryPoint = "GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation);
//
@@ -35,7 +36,7 @@ namespace Microsoft.Win32 {
// PULONGLONG pululEnumerator
// );
//
- [DllImport(Win32Native.KERNEL32, EntryPoint="GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
+ [DllImport(Win32Native.KERNEL32, EntryPoint = "GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetFileMUIPath(
int flags,
@@ -50,13 +51,13 @@ namespace Microsoft.Win32 {
ref Int64 enumerator);
- [DllImport(Win32Native.USER32, EntryPoint="LoadStringW", SetLastError=true, CharSet=CharSet.Unicode, ExactSpelling=true, CallingConvention=CallingConvention.StdCall)]
+ [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)]
+ [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);
@@ -245,14 +246,13 @@ namespace Microsoft.Win32 {
void* OutBuffer,
int OutBufferSize,
ref int ReturnLength);
-
}
#if FEATURE_COMINTEROP
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
[MarshalAs(UnmanagedType.HString)] string activatableClassId,
[In] ref Guid iid,
- [Out,MarshalAs(UnmanagedType.IInspectable)] out Object factory);
+ [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 b081b16ca1..8543bc8a99 100644
--- a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
@@ -87,7 +87,8 @@
* in your DllImportAttribute.
*/
-namespace Microsoft.Win32 {
+namespace Microsoft.Win32
+{
using System;
using System.Security;
using System.Text;
@@ -103,7 +104,7 @@ namespace Microsoft.Win32 {
using BOOL = System.Int32;
using DWORD = System.UInt32;
using ULONG = System.UInt32;
-
+
/**
* Win32 encapsulation for MSCORLIB.
*/
@@ -111,49 +112,49 @@ namespace Microsoft.Win32 {
// global declaration on the class.
[SuppressUnmanagedCodeSecurityAttribute()]
- internal static class Win32Native {
-
- internal const int KEY_QUERY_VALUE = 0x0001;
- internal const int KEY_SET_VALUE = 0x0002;
- internal const int KEY_CREATE_SUB_KEY = 0x0004;
+ internal static class Win32Native
+ {
+ internal const int KEY_QUERY_VALUE = 0x0001;
+ internal const int KEY_SET_VALUE = 0x0002;
+ internal const int KEY_CREATE_SUB_KEY = 0x0004;
internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008;
- internal const int KEY_NOTIFY = 0x0010;
- internal const int KEY_CREATE_LINK = 0x0020;
- internal const int KEY_READ =((STANDARD_RIGHTS_READ |
- KEY_QUERY_VALUE |
- KEY_ENUMERATE_SUB_KEYS |
- KEY_NOTIFY)
- &
+ internal const int KEY_NOTIFY = 0x0010;
+ internal const int KEY_CREATE_LINK = 0x0020;
+ internal const int KEY_READ = ((STANDARD_RIGHTS_READ |
+ KEY_QUERY_VALUE |
+ KEY_ENUMERATE_SUB_KEYS |
+ KEY_NOTIFY)
+ &
(~SYNCHRONIZE));
-
- internal const int KEY_WRITE =((STANDARD_RIGHTS_WRITE |
- KEY_SET_VALUE |
- KEY_CREATE_SUB_KEY)
- &
+
+ internal const int KEY_WRITE = ((STANDARD_RIGHTS_WRITE |
+ KEY_SET_VALUE |
+ KEY_CREATE_SUB_KEY)
+ &
(~SYNCHRONIZE));
- internal const int KEY_WOW64_64KEY = 0x0100; //
- internal const int KEY_WOW64_32KEY = 0x0200; //
- internal const int REG_OPTION_NON_VOLATILE= 0x0000; // (default) keys are persisted beyond reboot/unload
- internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile
+ internal const int KEY_WOW64_64KEY = 0x0100; //
+ internal const int KEY_WOW64_32KEY = 0x0200; //
+ internal const int REG_OPTION_NON_VOLATILE = 0x0000; // (default) keys are persisted beyond reboot/unload
+ internal const int REG_OPTION_VOLATILE = 0x0001; // All keys created by the function are volatile
internal const int REG_OPTION_CREATE_LINK = 0x0002; // They key is a symbolic link
internal const int REG_OPTION_BACKUP_RESTORE = 0x0004; // Use SE_BACKUP_NAME process special privileges
- internal const int REG_NONE = 0; // No value type
- internal const int REG_SZ = 1; // Unicode nul terminated string
- internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string
+ internal const int REG_NONE = 0; // No value type
+ internal const int REG_SZ = 1; // Unicode nul terminated string
+ internal const int REG_EXPAND_SZ = 2; // Unicode nul terminated string
// (with environment variable references)
- internal const int REG_BINARY = 3; // Free form binary
- internal const int REG_DWORD = 4; // 32-bit number
- internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD)
- internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number
- internal const int REG_LINK = 6; // Symbolic Link (unicode)
- internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings
- internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map
- internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description
- 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;
+ internal const int REG_BINARY = 3; // Free form binary
+ internal const int REG_DWORD = 4; // 32-bit number
+ internal const int REG_DWORD_LITTLE_ENDIAN = 4; // 32-bit number (same as REG_DWORD)
+ internal const int REG_DWORD_BIG_ENDIAN = 5; // 32-bit number
+ internal const int REG_LINK = 6; // Symbolic Link (unicode)
+ internal const int REG_MULTI_SZ = 7; // Multiple Unicode strings
+ internal const int REG_RESOURCE_LIST = 8; // Resource list in the resource map
+ internal const int REG_FULL_RESOURCE_DESCRIPTOR = 9; // Resource list in the hardware description
+ 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;
@@ -174,7 +175,8 @@ namespace Microsoft.Win32 {
internal const int LOAD_STRING_MAX_LENGTH = 500;
[StructLayout(LayoutKind.Sequential)]
- internal struct SystemTime {
+ internal struct SystemTime
+ {
[MarshalAs(UnmanagedType.U2)]
public short Year;
[MarshalAs(UnmanagedType.U2)]
@@ -194,7 +196,8 @@ namespace Microsoft.Win32 {
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct TimeZoneInformation {
+ internal struct TimeZoneInformation
+ {
[MarshalAs(UnmanagedType.I4)]
public Int32 Bias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
@@ -208,7 +211,8 @@ namespace Microsoft.Win32 {
[MarshalAs(UnmanagedType.I4)]
public Int32 DaylightBias;
- public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi) {
+ public TimeZoneInformation(Win32Native.DynamicTimeZoneInformation dtzi)
+ {
Bias = dtzi.Bias;
StandardName = dtzi.StandardName;
StandardDate = dtzi.StandardDate;
@@ -221,7 +225,8 @@ namespace Microsoft.Win32 {
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
- internal struct DynamicTimeZoneInformation {
+ internal struct DynamicTimeZoneInformation
+ {
[MarshalAs(UnmanagedType.I4)]
public Int32 Bias;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
@@ -242,7 +247,8 @@ namespace Microsoft.Win32 {
[StructLayout(LayoutKind.Sequential)]
- internal struct RegistryTimeZoneInformation {
+ internal struct RegistryTimeZoneInformation
+ {
[MarshalAs(UnmanagedType.I4)]
public Int32 Bias;
[MarshalAs(UnmanagedType.I4)]
@@ -252,7 +258,8 @@ namespace Microsoft.Win32 {
public SystemTime StandardDate;
public SystemTime DaylightDate;
- public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi) {
+ public RegistryTimeZoneInformation(Win32Native.TimeZoneInformation tzi)
+ {
Bias = tzi.Bias;
StandardDate = tzi.StandardDate;
StandardBias = tzi.StandardBias;
@@ -260,7 +267,8 @@ namespace Microsoft.Win32 {
DaylightBias = tzi.DaylightBias;
}
- public RegistryTimeZoneInformation(Byte[] bytes) {
+ public RegistryTimeZoneInformation(Byte[] bytes)
+ {
//
// typedef struct _REG_TZI_FORMAT {
// [00-03] LONG Bias;
@@ -286,8 +294,9 @@ namespace Microsoft.Win32 {
// [42-43] WORD wMilliseconds;
// } REG_TZI_FORMAT;
//
- if (bytes == null || bytes.Length != 44) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidREG_TZI_FORMAT"), nameof(bytes));
+ if (bytes == null || bytes.Length != 44)
+ {
+ throw new ArgumentException(SR.Argument_InvalidREG_TZI_FORMAT, nameof(bytes));
}
Bias = BitConverter.ToInt32(bytes, 0);
StandardBias = BitConverter.ToInt32(bytes, 4);
@@ -317,12 +326,12 @@ namespace Microsoft.Win32 {
// Win32 ACL-related constants:
- internal const int READ_CONTROL = 0x00020000;
- internal const int SYNCHRONIZE = 0x00100000;
+ internal const int READ_CONTROL = 0x00020000;
+ internal const int SYNCHRONIZE = 0x00100000;
+
+ internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
+ internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
- internal const int STANDARD_RIGHTS_READ = READ_CONTROL;
- internal const int STANDARD_RIGHTS_WRITE = READ_CONTROL;
-
// STANDARD_RIGHTS_REQUIRED (0x000F0000L)
// SEMAPHORE_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED|SYNCHRONIZE|0x3)
@@ -332,18 +341,20 @@ namespace Microsoft.Win32 {
// Note that you may need to specify the SYNCHRONIZE bit as well
// to be able to open a synchronization primitive.
internal const int SEMAPHORE_MODIFY_STATE = 0x00000002;
- internal const int EVENT_MODIFY_STATE = 0x00000002;
- internal const int MUTEX_MODIFY_STATE = 0x00000001;
- internal const int MUTEX_ALL_ACCESS = 0x001F0001;
+ internal const int EVENT_MODIFY_STATE = 0x00000002;
+ internal const int MUTEX_MODIFY_STATE = 0x00000001;
+ internal const int MUTEX_ALL_ACCESS = 0x001F0001;
- internal const int LMEM_FIXED = 0x0000;
+ internal const int LMEM_FIXED = 0x0000;
internal const int LMEM_ZEROINIT = 0x0040;
- internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT);
+ internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT);
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
- internal class OSVERSIONINFO {
- internal OSVERSIONINFO() {
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
+ internal class OSVERSIONINFO
+ {
+ internal OSVERSIONINFO()
+ {
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
@@ -353,14 +364,15 @@ namespace Microsoft.Win32 {
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal String CSDVersion = null;
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
- internal class OSVERSIONINFOEX {
-
- public OSVERSIONINFOEX() {
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
+ internal class OSVERSIONINFOEX
+ {
+ public OSVERSIONINFOEX()
+ {
OSVersionInfoSize = (int)Marshal.SizeOf(this);
}
@@ -370,26 +382,28 @@ namespace Microsoft.Win32 {
internal int MinorVersion = 0;
internal int BuildNumber = 0;
internal int PlatformId = 0;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)]
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string CSDVersion = null;
internal ushort ServicePackMajor = 0;
internal ushort ServicePackMinor = 0;
internal short SuiteMask = 0;
internal byte ProductType = 0;
- internal byte Reserved = 0;
+ internal byte Reserved = 0;
}
[StructLayout(LayoutKind.Sequential)]
- internal class SECURITY_ATTRIBUTES {
+ internal class SECURITY_ATTRIBUTES
+ {
internal int nLength = 0;
// don't remove null, or this field will disappear in bcl.small
- internal unsafe byte * pSecurityDescriptor = null;
+ internal unsafe byte* pSecurityDescriptor = null;
internal int bInheritHandle = 0;
}
[Serializable]
[StructLayout(LayoutKind.Sequential)]
- internal struct WIN32_FILE_ATTRIBUTE_DATA {
+ internal struct WIN32_FILE_ATTRIBUTE_DATA
+ {
internal int fileAttributes;
internal uint ftCreationTimeLow;
internal uint ftCreationTimeHigh;
@@ -400,22 +414,24 @@ namespace Microsoft.Win32 {
internal int fileSizeHigh;
internal int fileSizeLow;
- internal void PopulateFrom(WIN32_FIND_DATA findData) {
+ internal void PopulateFrom(WIN32_FIND_DATA findData)
+ {
// Copy the information to data
- fileAttributes = findData.dwFileAttributes;
- ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime;
- ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime;
- ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime;
- ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime;
- ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime;
- ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime;
- fileSizeHigh = findData.nFileSizeHigh;
- fileSizeLow = findData.nFileSizeLow;
+ fileAttributes = findData.dwFileAttributes;
+ ftCreationTimeLow = findData.ftCreationTime_dwLowDateTime;
+ ftCreationTimeHigh = findData.ftCreationTime_dwHighDateTime;
+ ftLastAccessTimeLow = findData.ftLastAccessTime_dwLowDateTime;
+ ftLastAccessTimeHigh = findData.ftLastAccessTime_dwHighDateTime;
+ ftLastWriteTimeLow = findData.ftLastWriteTime_dwLowDateTime;
+ ftLastWriteTimeHigh = findData.ftLastWriteTime_dwHighDateTime;
+ fileSizeHigh = findData.nFileSizeHigh;
+ fileSizeLow = findData.nFileSizeLow;
}
}
[StructLayout(LayoutKind.Sequential)]
- internal struct MEMORYSTATUSEX {
+ internal struct MEMORYSTATUSEX
+ {
// The length field must be set to the size of this data structure.
internal int length;
internal int memoryLoad;
@@ -429,7 +445,8 @@ namespace Microsoft.Win32 {
}
[StructLayout(LayoutKind.Sequential)]
- internal unsafe struct MEMORY_BASIC_INFORMATION {
+ internal unsafe struct MEMORY_BASIC_INFORMATION
+ {
internal void* BaseAddress;
internal void* AllocationBase;
internal uint AllocationProtect;
@@ -441,10 +458,10 @@ namespace Microsoft.Win32 {
#if !FEATURE_PAL
internal const String KERNEL32 = "kernel32.dll";
- internal const String USER32 = "user32.dll";
- internal const String OLE32 = "ole32.dll";
+ internal const String USER32 = "user32.dll";
+ internal const String OLE32 = "ole32.dll";
internal const String OLEAUT32 = "oleaut32.dll";
- internal const String NTDLL = "ntdll.dll";
+ internal const String NTDLL = "ntdll.dll";
#else //FEATURE_PAL
internal const String KERNEL32 = "libcoreclr";
internal const String USER32 = "libcoreclr";
@@ -453,40 +470,43 @@ namespace Microsoft.Win32 {
internal const String NTDLL = "libcoreclr";
#endif //FEATURE_PAL
internal const String ADVAPI32 = "advapi32.dll";
- internal const String SHELL32 = "shell32.dll";
- internal const String SHIM = "mscoree.dll";
- internal const String CRYPT32 = "crypt32.dll";
- internal const String SECUR32 = "secur32.dll";
+ internal const String SHELL32 = "shell32.dll";
+ internal const String SHIM = "mscoree.dll";
+ internal const String CRYPT32 = "crypt32.dll";
+ internal const String SECUR32 = "secur32.dll";
internal const String MSCORWKS = "coreclr.dll";
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
- [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=true)]
+ [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) {
+ 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) {
+ if (result != 0)
+ {
// result is the # of characters copied to the StringBuilder.
return StringBuilderCache.GetStringAndRelease(sb);
}
- else {
+ else
+ {
StringBuilderCache.Release(sb);
- return Environment.GetResourceString("UnknownError_Num", errorCode);
+ return SR.Format(SR.UnknownError_Num, errorCode);
}
}
- [DllImport(KERNEL32, EntryPoint="LocalAlloc")]
+ [DllImport(KERNEL32, EntryPoint = "LocalAlloc")]
internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes);
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(KERNEL32, SetLastError = true)]
internal static extern IntPtr LocalFree(IntPtr handle);
// MSDN says the length is a SIZE_T.
@@ -499,25 +519,25 @@ namespace Microsoft.Win32 {
return GlobalMemoryStatusExNative(ref buffer);
}
- [DllImport(KERNEL32, SetLastError=true, EntryPoint="GlobalMemoryStatusEx")]
+ [DllImport(KERNEL32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")]
private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer);
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(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)]
- unsafe internal static extern void * VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode);
+ [DllImport(KERNEL32, SetLastError = true)]
+ unsafe internal static extern void* VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode);
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(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(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(KERNEL32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")]
internal static extern int lstrlenW(IntPtr ptr);
[DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
@@ -538,31 +558,31 @@ namespace Microsoft.Win32 {
#endif
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(KERNEL32, SetLastError = true)]
internal static extern bool SetEvent(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(KERNEL32, SetLastError = true)]
internal static extern bool ResetEvent(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateEvent(SECURITY_ATTRIBUTES lpSecurityAttributes, bool isManualReset, bool initialState, String name);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenEvent(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateMutex(SECURITY_ATTRIBUTES lpSecurityAttributes, bool initialOwner, String name);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenMutex(/* DWORD */ int desiredAccess, bool inheritHandle, String name);
-
- [DllImport(KERNEL32, SetLastError=true)]
+
+ [DllImport(KERNEL32, SetLastError = true)]
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(KERNEL32, SetLastError = true)]
internal static extern bool CloseHandle(IntPtr handle);
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(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)]
@@ -576,13 +596,13 @@ namespace Microsoft.Win32 {
internal static extern SafeWaitHandle OpenSemaphore(/* DWORD */ int 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
+ 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 struct NlsVersionInfoEx
{
internal int dwNLSVersionInfoSize;
internal int dwNLSVersion;
@@ -591,7 +611,7 @@ namespace Microsoft.Win32 {
internal Guid guidCustomVersion;
}
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
+ [DllImport(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
@@ -601,7 +621,7 @@ namespace Microsoft.Win32 {
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
- [DllImport(KERNEL32, SetLastError=true)]
+ [DllImport(KERNEL32, SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one!
// From wincon.h
@@ -621,32 +641,32 @@ namespace Microsoft.Win32 {
internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 0x2;
private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
- private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
+ private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
internal const uint FILE_MAP_WRITE = 0x0002;
internal const uint FILE_MAP_READ = 0x0004;
// Constants from WinNT.h
- internal const int FILE_ATTRIBUTE_READONLY = 0x00000001;
- internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
+ internal const int FILE_ATTRIBUTE_READONLY = 0x00000001;
+ internal const int FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
internal const int FILE_ATTRIBUTE_REPARSE_POINT = 0x00000400;
internal const int IO_REPARSE_TAG_MOUNT_POINT = unchecked((int)0xA0000003);
internal const int PAGE_READWRITE = 0x04;
- internal const int MEM_COMMIT = 0x1000;
- internal const int MEM_RESERVE = 0x2000;
- internal const int MEM_RELEASE = 0x8000;
- internal const int MEM_FREE = 0x10000;
+ internal const int MEM_COMMIT = 0x1000;
+ internal const int MEM_RESERVE = 0x2000;
+ internal const int MEM_RELEASE = 0x8000;
+ internal const int MEM_FREE = 0x10000;
// Error codes from WinError.h
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_INVALID_FUNCTION = 0x1;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
- internal const int ERROR_ACCESS_DENIED = 0x5;
+ internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DATA = 0xd;
@@ -699,10 +719,10 @@ namespace Microsoft.Win32 {
internal const uint STATUS_INSUFFICIENT_RESOURCES = 0xC000009A;
internal const uint STATUS_ACCESS_DENIED = 0xC0000022;
- internal const int INVALID_FILE_SIZE = -1;
+ internal const int INVALID_FILE_SIZE = -1;
// From WinStatus.h
- internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int) 0xC000006E);
+ 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
@@ -714,12 +734,13 @@ namespace Microsoft.Win32 {
// Win32 Structs in N/Direct style
[Serializable]
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[BestFitMapping(false)]
- internal class WIN32_FIND_DATA {
- internal int dwFileAttributes = 0;
+ internal class WIN32_FIND_DATA
+ {
+ internal int dwFileAttributes = 0;
// ftCreationTime was a by-value FILETIME structure
- internal uint ftCreationTime_dwLowDateTime = 0 ;
+ internal uint ftCreationTime_dwLowDateTime = 0;
internal uint ftCreationTime_dwHighDateTime = 0;
// ftLastAccessTime was a by-value FILETIME structure
internal uint ftLastAccessTime_dwLowDateTime = 0;
@@ -727,24 +748,24 @@ namespace Microsoft.Win32 {
// ftLastWriteTime was a by-value FILETIME structure
internal uint ftLastWriteTime_dwLowDateTime = 0;
internal uint ftLastWriteTime_dwHighDateTime = 0;
- internal int nFileSizeHigh = 0;
- internal int nFileSizeLow = 0;
+ internal int nFileSizeHigh = 0;
+ internal int nFileSizeLow = 0;
// If the file attributes' reparse point flag is set, then
// dwReserved0 is the file tag (aka reparse tag) for the
// reparse point. Use this to figure out whether something is
// a volume mount point or a symbolic link.
- internal int dwReserved0 = 0;
- internal int dwReserved1 = 0;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst=260)]
- internal String cFileName = null;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst=14)]
- internal String cAlternateFileName = null;
+ internal int dwReserved0 = 0;
+ internal int dwReserved1 = 0;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
+ internal String cFileName = null;
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
+ internal String cAlternateFileName = null;
}
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(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(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool FindNextFile(
SafeFindHandle hndFindFile,
[In, Out, MarshalAs(UnmanagedType.LPStruct)]
@@ -756,13 +777,13 @@ namespace Microsoft.Win32 {
[DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
internal static extern uint GetCurrentDirectoryW(uint nBufferLength, char[] lpBuffer);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
- [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool SetCurrentDirectory(String path);
- [DllImport(KERNEL32, SetLastError=false, EntryPoint="SetErrorMode", ExactSpelling=true)]
+ [DllImport(KERNEL32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)]
private static extern int SetErrorMode_VistaAndOlder(int newMode);
// RTM versions of Win7 and Windows Server 2008 R2
@@ -779,24 +800,21 @@ namespace Microsoft.Win32 {
[DllImport(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(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(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)]
- internal static unsafe extern char * GetEnvironmentStrings();
+ [DllImport(KERNEL32, CharSet = CharSet.Unicode)]
+ internal static unsafe extern char* GetEnvironmentStrings();
- [DllImport(KERNEL32, CharSet=CharSet.Unicode)]
- internal static unsafe extern bool FreeEnvironmentStrings(char * pStrings);
+ [DllImport(KERNEL32, CharSet = CharSet.Unicode)]
+ internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings);
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true)]
+ [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern uint GetCurrentProcessId();
- [DllImport(KERNEL32, CharSet=CharSet.Auto, BestFitMapping=false)]
- internal extern static int GetComputerName([Out]StringBuilder nameBuffer, ref int bufferSize);
-
[DllImport(OLE32)]
internal extern static int CoCreateGuid(out Guid guid);
@@ -810,148 +828,150 @@ namespace Microsoft.Win32 {
internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb);
#if FEATURE_WIN32_REGISTRY
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegDeleteValue(SafeRegistryHandle hKey, String lpValueName);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal unsafe static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex,
- char *lpName, ref int lpcbName, int[] lpReserved,
+ char[] lpName, ref int lpcbName, int[] lpReserved,
[Out]StringBuilder lpClass, int[] lpcbClass,
long[] lpftLastWriteTime);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal unsafe static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex,
- char *lpValueName, ref int lpcbValueName,
+ char[] lpValueName, ref int lpcbValueName,
IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData,
int[] lpcbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, String lpSubKey,
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [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)]
+
+ [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);
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, ref int lpData,
ref int lpcbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, ref long lpData,
ref int lpcbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
- int[] lpReserved, ref int lpType, [Out] char[] lpData,
+ int[] lpReserved, ref int lpType, [Out] char[] lpData,
ref int lpcbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, byte[] lpData, int cbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, ref int lpData, int cbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, ref long lpData, int cbData);
-
- [DllImport(ADVAPI32, CharSet=CharSet.Auto, BestFitMapping=false)]
+
+ [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegSetValueEx(SafeRegistryHandle hKey, String lpValueName,
int Reserved, RegistryValueKind dwType, String lpData, int cbData);
#endif // FEATURE_WIN32_REGISTRY
-
- [DllImport(KERNEL32, CharSet=CharSet.Auto, SetLastError=true, BestFitMapping=false)]
+
+ [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize);
[DllImport(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;
+ 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()
+ 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 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)]
+ [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)]
[return: MarshalAs(UnmanagedType.Bool)]
internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
-#if FEATURE_PAL
- [DllImport(KERNEL32, EntryPoint = "PAL_Random")]
- internal extern static bool Random(bool bStrong,
- [Out, MarshalAs(UnmanagedType.LPArray)] byte[] buffer, int length);
-#else
- private const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002;
-#endif
+ internal const byte VER_GREATER_EQUAL = 0x3;
+ internal const uint VER_MAJORVERSION = 0x0000002;
+ internal const uint VER_MINORVERSION = 0x0000001;
+ internal const uint VER_SERVICEPACKMAJOR = 0x0000020;
+ internal const uint VER_SERVICEPACKMINOR = 0x0000010;
+ [DllImport("kernel32.dll")]
+ internal static extern bool VerifyVersionInfoW([In, Out] OSVERSIONINFOEX lpVersionInfo, uint dwTypeMask, ulong dwlConditionMask);
+ [DllImport("kernel32.dll")]
+ internal static extern ulong VerSetConditionMask(ulong dwlConditionMask, uint dwTypeBitMask, byte dwConditionMask);
}
}
diff --git a/src/mscorlib/src/System.Private.CoreLib.txt b/src/mscorlib/src/System.Private.CoreLib.txt
deleted file mode 100644
index b4e9e297d9..0000000000
--- a/src/mscorlib/src/System.Private.CoreLib.txt
+++ /dev/null
@@ -1,2235 +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.
-
-; These are the managed resources for mscorlib.dll.
-; See those first three bytes in the file? This is in UTF-8. Leave the
-; Unicode byte order mark (U+FEFF) written in UTF-8 at the start of this file.
-
-; For resource info, see the ResourceManager documentation and the ResGen tool,
-; which is a managed app using ResourceWriter.
-; ResGen now supports limited preprocessing of txt files, you can use
-; #if SYMBOL and #if !SYMBOL to control what sets of resources are included in
-; the resulting resources.
-
-; The naming scheme is: [Namespace.] ExceptionName _ Reason
-; We'll suppress "System." where possible.
-; Examples:
-; Argument_Null
-; Reflection.TargetInvokation_someReason
-
-; Usage Notes:
-; * Keep exceptions in alphabetical order by package
-; * A single space may exist on either side of the equal sign.
-; * Follow the naming conventions.
-; * Any lines starting with a '#' or ';' are ignored
-; * Equal signs aren't legal characters for keys, but may occur in values.
-; * Correctly punctuate all sentences. Most resources should end in a period.
-; Remember, your mother will probably read some of these messages.
-; * You may use " (quote), \n and \t. Use \\ for a single '\' character.
-; * String inserts work. i.e., BadNumber_File = Wrong number in file "{0}".
-
-; Real words, used by code like Environment.StackTrace
-#if INCLUDE_RUNTIME
-Word_At = at
-StackTrace_InFileLineNumber = in {0}:line {1}
-UnknownError_Num = Unknown error "{0}".
-AllocatedFrom = Allocated from:
-
-; Note this one is special, used as a divider between stack traces!
-Exception_EndOfInnerExceptionStack = --- End of inner exception stack trace ---
-Exception_WasThrown = Exception of type '{0}' was thrown.
-
-; The following are used in the implementation of ExceptionDispatchInfo
-Exception_EndStackTraceFromPreviousThrow = --- End of stack trace from previous location where exception was thrown ---
-
-Arg_ParamName_Name = Parameter name: {0}
-ArgumentOutOfRange_ActualValue = Actual value was {0}.
-
-NoDebugResources = [{0}]\r\nArguments: {1}\r\nDebugging resource strings are unavailable. Often the key and arguments provide sufficient information to diagnose the problem. See http://go.microsoft.com/fwlink/?linkid=106663&Version={2}&File={3}&Key={4}
-#endif // INCLUDE_RUNTIME
-
-#if INCLUDE_DEBUG
-
-; For code contracts
-AssumptionFailed = Assumption failed.
-AssumptionFailed_Cnd = Assumption failed: {0}
-AssertionFailed = Assertion failed.
-AssertionFailed_Cnd = Assertion failed: {0}
-PreconditionFailed = Precondition failed.
-PreconditionFailed_Cnd = Precondition failed: {0}
-PostconditionFailed = Postcondition failed.
-PostconditionFailed_Cnd = Postcondition failed: {0}
-PostconditionOnExceptionFailed = Postcondition failed after throwing an exception.
-PostconditionOnExceptionFailed_Cnd = Postcondition failed after throwing an exception: {0}
-InvariantFailed = Invariant failed.
-InvariantFailed_Cnd = Invariant failed: {0}
-MustUseCCRewrite = An assembly (probably "{1}") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.{0} and the CONTRACTS_FULL symbol is defined. Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild. CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. \r\nAfter the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane. Ensure that "Perform Runtime Contract Checking" is enabled, which will define CONTRACTS_FULL.
-
-; Identity Reference Library
-#if FEATURE_IDENTITY_REFERENCE
-IdentityReference_IdentityNotMapped = Some or all identity references could not be translated.
-IdentityReference_MustBeIdentityReference = The targetType parameter must be of IdentityReference type.
-IdentityReference_AccountNameTooLong = Account name is too long.
-IdentityReference_DomainNameTooLong = Domain name is too long.
-IdentityReference_InvalidNumberOfSubauthorities = The number of sub-authorities must not exceed {0}.
-IdentityReference_IdentifierAuthorityTooLarge = The size of the identifier authority must not exceed 6 bytes.
-IdentityReference_InvalidSidRevision = SIDs with revision other than '1' are not supported.
-IdentityReference_CannotCreateLogonIdsSid = Well-known SIDs of type LogonIdsSid cannot be created.
-IdentityReference_DomainSidRequired = The domainSid parameter must be specified for creating well-known SID of type {0}.
-IdentityReference_NotAWindowsDomain = The domainSid parameter is not a valid Windows domain SID.
-#endif // FEATURE_IDENTITY_REFERENCE
-
-; AccessException
-Acc_CreateGeneric = Cannot create a type for which Type.ContainsGenericParameters is true.
-Acc_CreateAbst = Cannot create an abstract class.
-Acc_CreateInterface = Cannot create an instance of an interface.
-Acc_NotClassInit = Type initializer was not callable.
-Acc_CreateGenericEx = Cannot create an instance of {0} because Type.ContainsGenericParameters is true.
-Acc_CreateArgIterator = Cannot dynamically create an instance of ArgIterator.
-Acc_CreateAbstEx = Cannot create an instance of {0} because it is an abstract class.
-Acc_CreateInterfaceEx = Cannot create an instance of {0} because it is an interface.
-Acc_CreateVoid = Cannot dynamically create an instance of System.Void.
-Acc_ReadOnly = Cannot set a constant field.
-Acc_RvaStatic = SkipVerification permission is needed to modify an image-based (RVA) static field.
-Access_Void = Cannot create an instance of void.
-
-; ArgumentException
-Arg_TypedReference_Null = The TypedReference must be initialized.
-Argument_AddingDuplicate__ = Item has already been added. Key in dictionary: '{0}' Key being added: '{1}'
-Argument_AddingDuplicate = An item with the same key has already been added.
-Argument_AddingDuplicateWithKey = An item with the same key has already been added. Key: {0}
-Argument_MethodDeclaringTypeGenericLcg = Method '{0}' has a generic declaring type '{1}'. Explicitly provide the declaring type to GetTokenFor.
-Argument_MethodDeclaringTypeGeneric = Cannot resolve method {0} because the declaring type of the method handle {1} is generic. Explicitly provide the declaring type to GetMethodFromHandle.
-Argument_FieldDeclaringTypeGeneric = Cannot resolve field {0} because the declaring type of the field handle {1} is generic. Explicitly provide the declaring type to GetFieldFromHandle.
-Argument_ApplicationTrustShouldHaveIdentity = An ApplicationTrust must have an application identity before it can be persisted.
-Argument_ConversionOverflow = Conversion buffer overflow.
-Argument_CodepageNotSupported = {0} is not a supported code page.
-Argument_CultureNotSupported = Culture is not supported.
-Argument_CultureInvalidIdentifier = {0} is an invalid culture identifier.
-Argument_OneOfCulturesNotSupported = Culture name {0} or {1} is not supported.
-Argument_CultureIetfNotSupported = Culture IETF Name {0} is not a recognized IETF name.
-Argument_CultureIsNeutral = Culture ID {0} (0x{0:X4}) is a neutral culture; a region cannot be created from it.
-Argument_InvalidNeutralRegionName = The region name {0} should not correspond to neutral culture; a specific culture name is required.
-Argument_InvalidGenericInstArray = Generic arguments must be provided for each generic parameter and each generic argument must be a RuntimeType.
-Argument_GenericArgsCount = The number of generic arguments provided doesn't equal the arity of the generic type definition.
-Argument_CultureInvalidFormat = Culture '{0}' is a neutral culture. It cannot be used in formatting and parsing and therefore cannot be set as the thread's current culture.
-Argument_CompareOptionOrdinal = CompareOption.Ordinal cannot be used with other options.
-Argument_CustomCultureCannotBePassedByNumber = Customized cultures cannot be passed by LCID, only by name.
-Argument_EncodingConversionOverflowChars = The output char buffer is too small to contain the decoded characters, encoding '{0}' fallback '{1}'.
-Argument_EncodingConversionOverflowBytes = The output byte buffer is too small to contain the encoded data, encoding '{0}' fallback '{1}'.
-Argument_EncoderFallbackNotEmpty = Must complete Convert() operation or call Encoder.Reset() before calling GetBytes() or GetByteCount(). Encoder '{0}' fallback '{1}'.
-Argument_EmptyFileName = Empty file name is not legal.
-Argument_EmptyPath = Empty path name is not legal.
-Argument_EmptyName = Empty name is not legal.
-Argument_ImplementIComparable = At least one object must implement IComparable.
-Argument_InvalidType = The type of arguments passed into generic comparer methods is invalid.
-Argument_InvalidTypeForCA=Cannot build type parameter for custom attribute with a type that does not support the AssemblyQualifiedName property. The type instance supplied was of type '{0}'.
-Argument_IllegalEnvVarName = Environment variable name cannot contain equal character.
-Argument_IllegalAppId = Application identity does not have same number of components as manifest paths.
-Argument_IllegalAppBase = The application base specified is not valid.
-Argument_UnableToParseManifest = Unexpected error while parsing the specified manifest.
-Argument_IllegalAppIdMismatch = Application identity does not match identities in manifests.
-Argument_InvalidAppId = Invalid identity: no deployment or application identity specified.
-Argument_InvalidGenericArg = The generic type parameter was not valid
-Argument_InvalidArrayLength = Length of the array must be {0}.
-Argument_InvalidArrayType = Target array type is not compatible with the type of items in the collection.
-Argument_InvalidAppendMode = Append access can be requested only in write-only mode.
-Argument_InvalidEnumValue = The value '{0}' is not valid for this usage of the type {1}.
-Argument_EnumIsNotIntOrShort = The underlying type of enum argument must be Int32 or Int16.
-Argument_InvalidEnum = The Enum type should contain one and only one instance field.
-Argument_InvalidKeyStore = '{0}' is not a valid KeyStore name.
-Argument_InvalidFileMode&AccessCombo = Combining FileMode: {0} with FileAccess: {1} is invalid.
-Argument_InvalidFileMode&RightsCombo = Combining FileMode: {0} with FileSystemRights: {1} is invalid.
-Argument_InvalidFileModeTruncate&RightsCombo = Combining FileMode: {0} with FileSystemRights: {1} is invalid. FileMode.Truncate is valid only when used with FileSystemRights.Write.
-Argument_InvalidFlag = Value of flags is invalid.
-Argument_InvalidAnyFlag = No flags can be set.
-Argument_InvalidHandle = The handle is invalid.
-Argument_InvalidRegistryKeyPermissionCheck = The specified RegistryKeyPermissionCheck value is invalid.
-Argument_InvalidRegistryOptionsCheck = The specified RegistryOptions value is invalid.
-Argument_InvalidRegistryViewCheck = The specified RegistryView value is invalid.
-Argument_InvalidSubPath = The directory specified, '{0}', is not a subdirectory of '{1}'.
-Argument_NoRegionInvariantCulture = There is no region associated with the Invariant Culture (Culture ID: 0x7F).
-Argument_ResultCalendarRange = The result is out of the supported range for this calendar. The result should be between {0} (Gregorian date) and {1} (Gregorian date), inclusive.
-Argument_ResultIslamicCalendarRange = The date is out of the supported range for the Islamic calendar. The date should be greater than July 18th, 622 AD (Gregorian date).
-Argument_NeverValidGenericArgument = The type '{0}' may not be used as a type argument.
-Argument_NotEnoughGenArguments = The type or method has {1} generic parameter(s), but {0} generic argument(s) were provided. A generic argument must be provided for each generic parameter.
-Argument_NullFullTrustAssembly = A null StrongName was found in the full trust assembly list.
-Argument_GenConstraintViolation = GenericArguments[{0}], '{1}', on '{2}' violates the constraint of type '{3}'.
-Argument_InvalidToken = Token {0:x} is not valid in the scope of module {1}.
-Argument_InvalidTypeToken = Token {0:x} is not a valid Type token.
-Argument_ResolveType = Token {0:x} is not a valid Type token in the scope of module {1}.
-Argument_ResolveMethod = Token {0:x} is not a valid MethodBase token in the scope of module {1}.
-Argument_ResolveField = Token {0:x} is not a valid FieldInfo token in the scope of module {1}.
-Argument_ResolveMember = Token {0:x} is not a valid MemberInfo token in the scope of module {1}.
-Argument_ResolveString = Token {0:x} is not a valid string token in the scope of module {1}.
-Argument_ResolveModuleType = Token {0} resolves to the special module type representing this module.
-Argument_ResolveMethodHandle = Type handle '{0}' and method handle with declaring type '{1}' are incompatible. Get RuntimeMethodHandle and declaring RuntimeTypeHandle off the same MethodBase.
-Argument_ResolveFieldHandle = Type handle '{0}' and field handle with declaring type '{1}' are incompatible. Get RuntimeFieldHandle and declaring RuntimeTypeHandle off the same FieldInfo.
-Argument_ResourceScopeWrongDirection = Resource type in the ResourceScope enum is going from a more restrictive resource type to a more general one. From: "{0}" To: "{1}"
-Argument_BadResourceScopeTypeBits = Unknown value for the ResourceScope: {0} Too many resource type bits may be set.
-Argument_BadResourceScopeVisibilityBits = Unknown value for the ResourceScope: {0} Too many resource visibility bits may be set.
-Argument_WaitHandleNameTooLong = The name can be no more than {0} characters in length.
-Argument_EnumTypeDoesNotMatch = The argument type, '{0}', is not the same as the enum type '{1}'.
-InvalidOperation_MethodBuilderBaked = The signature of the MethodBuilder can no longer be modified because an operation on the MethodBuilder caused the methodDef token to be created. For example, a call to SetCustomAttribute requires the methodDef token to emit the CustomAttribute token.
-InvalidOperation_GenericParametersAlreadySet = The generic parameters are already defined on this MethodBuilder.
-Arg_AccessException = Cannot access member.
-Arg_AppDomainUnloadedException = Attempted to access an unloaded AppDomain.
-Arg_ApplicationException = Error in the application.
-Arg_ArgumentOutOfRangeException = Specified argument was out of the range of valid values.
-Arg_ArithmeticException = Overflow or underflow in the arithmetic operation.
-Arg_ArrayLengthsDiffer = Array lengths must be the same.
-Arg_ArrayPlusOffTooSmall = Destination array is not long enough to copy all the items in the collection. Check array index and length.
-Arg_ArrayTypeMismatchException = Attempted to access an element as a type incompatible with the array.
-Arg_BadDecimal = Read an invalid decimal value from the buffer.
-Arg_BadImageFormatException = Format of the executable (.exe) or library (.dll) is invalid.
-Argument_BadImageFormatExceptionResolve = A BadImageFormatException has been thrown while parsing the signature. This is likely due to lack of a generic context. Ensure genericTypeArguments and genericMethodArguments are provided and contain enough context.
-Arg_BufferTooSmall = Not enough space available in the buffer.
-Arg_CATypeResolutionFailed = Failed to resolve type from string "{0}" which was embedded in custom attribute blob.
-Arg_CannotHaveNegativeValue = String cannot contain a minus sign if the base is not 10.
-Arg_CannotUnloadAppDomainException = Attempt to unload the AppDomain failed.
-Arg_CannotMixComparisonInfrastructure = The usage of IKeyComparer and IHashCodeProvider/IComparer interfaces cannot be mixed; use one or the other.
-Arg_ContextMarshalException = Attempted to marshal an object across a context boundary.
-Arg_DataMisalignedException = A datatype misalignment was detected in a load or store instruction.
-Arg_DevicesNotSupported = FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of "\\\\.\\" in the path.
-Arg_DuplicateWaitObjectException = Duplicate objects in argument.
-Arg_EntryPointNotFoundException = Entry point was not found.
-Arg_DllNotFoundException = Dll was not found.
-Arg_ExecutionEngineException = Internal error in the runtime.
-Arg_FieldAccessException = Attempted to access a field that is not accessible by the caller.
-Arg_FileIsDirectory_Name = The target file "{0}" is a directory, not a file.
-Arg_FormatException = One of the identified items was in an invalid format.
-Arg_IndexOutOfRangeException = Index was outside the bounds of the array.
-Arg_InsufficientExecutionStackException = Insufficient stack to continue executing the program safely. This can happen from having too many functions on the call stack or function on the stack using too much stack space.
-Arg_InvalidCastException = Specified cast is not valid.
-Arg_InvalidOperationException = Operation is not valid due to the current state of the object.
-Arg_CorruptedCustomCultureFile = The file of the custom culture {0} is corrupt. Try to unregister this culture.
-Arg_InvokeMember = InvokeMember can be used only for COM objects.
-Arg_InvalidNeutralResourcesLanguage_Asm_Culture = The NeutralResourcesLanguageAttribute on the assembly "{0}" specifies an invalid culture name: "{1}".
-Arg_InvalidNeutralResourcesLanguage_FallbackLoc = The NeutralResourcesLanguageAttribute specifies an invalid or unrecognized ultimate resource fallback location: "{0}".
-Arg_InvalidSatelliteContract_Asm_Ver = Satellite contract version attribute on the assembly '{0}' specifies an invalid version: {1}.
-Arg_MethodAccessException = Attempt to access the method failed.
-Arg_MethodAccessException_WithMethodName = Attempt to access the method "{0}" on type "{1}" failed.
-Arg_MethodAccessException_WithCaller = Attempt by security transparent method '{0}' to access security critical method '{1}' failed.
-Arg_MissingFieldException = Attempted to access a non-existing field.
-Arg_MissingMemberException = Attempted to access a missing member.
-Arg_MissingMethodException = Attempted to access a missing method.
-Arg_MulticastNotSupportedException = Attempted to add multiple callbacks to a delegate that does not support multicast.
-Arg_NotFiniteNumberException = Number encountered was not a finite quantity.
-Arg_NotSupportedException = Specified method is not supported.
-Arg_UnboundGenParam = Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.
-Arg_UnboundGenField = Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
-Arg_NotGenericParameter = Method may only be called on a Type for which Type.IsGenericParameter is true.
-Arg_GenericParameter = Method must be called on a Type for which Type.IsGenericParameter is false.
-Arg_NotGenericTypeDefinition = {0} is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.
-Arg_NotGenericMethodDefinition = {0} is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.
-Arg_BadLiteralFormat = Encountered an invalid type for a default value.
-Arg_MissingActivationArguments = The AppDomainSetup must specify the activation arguments for this call.
-Argument_BadParameterTypeForCAB = Cannot emit a CustomAttribute with argument of type {0}.
-Argument_InvalidMemberForNamedArgument = The member must be either a field or a property.
-Argument_InvalidTypeName = The name of the type is invalid.
-
-; Note - don't change the NullReferenceException default message. This was
-; negotiated carefully with the VB team to avoid saying "null" or "nothing".
-Arg_NullReferenceException = Object reference not set to an instance of an object.
-
-Arg_AccessViolationException = Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
-Arg_OverflowException = Arithmetic operation resulted in an overflow.
-Arg_PathGlobalRoot = Paths that begin with \\\\?\\GlobalRoot are internal to the kernel and should not be opened by managed applications.
-Arg_PathIllegal = The path is not of a legal form.
-Arg_PathIllegalUNC = The UNC path should be of the form \\\\server\\share.
-Arg_RankException = Attempted to operate on an array with the incorrect number of dimensions.
-Arg_RankMultiDimNotSupported = Only single dimensional arrays are supported for the requested action.
-Arg_NonZeroLowerBound = The lower bound of target array must be zero.
-Arg_RegSubKeyValueAbsent = No value exists with that name.
-Arg_ResourceFileUnsupportedVersion = The ResourceReader class does not know how to read this version of .resources files. Expected version: {0} This file: {1}
-Arg_ResourceNameNotExist = The specified resource name "{0}" does not exist in the resource file.
-Arg_SecurityException = Security error.
-Arg_SerializationException = Serialization error.
-Arg_StackOverflowException = Operation caused a stack overflow.
-Arg_SurrogatesNotAllowedAsSingleChar = Unicode surrogate characters must be written out as pairs together in the same call, not individually. Consider passing in a character array instead.
-Arg_SynchronizationLockException = Object synchronization method was called from an unsynchronized block of code.
-Arg_RWLockRestoreException = ReaderWriterLock.RestoreLock was called without releasing all locks acquired since the call to ReleaseLock.
-Arg_SystemException = System error.
-Arg_TimeoutException = The operation has timed out.
-Arg_UnauthorizedAccessException = Attempted to perform an unauthorized operation.
-Arg_ArgumentException = Value does not fall within the expected range.
-Arg_DirectoryNotFoundException = Attempted to access a path that is not on the disk.
-Arg_DriveNotFoundException = Attempted to access a drive that is not available.
-Arg_EndOfStreamException = Attempted to read past the end of the stream.
-Arg_HexStyleNotSupported = The number style AllowHexSpecifier is not supported on floating point data types.
-Arg_IOException = I/O error occurred.
-Arg_InvalidHexStyle = With the AllowHexSpecifier bit set in the enum bit field, the only other valid bits that can be combined into the enum value must be a subset of those in HexNumber.
-Arg_KeyNotFound = The given key was not present in the dictionary.
-Argument_InvalidNumberStyles = An undefined NumberStyles value is being used.
-Argument_InvalidDateTimeStyles = An undefined DateTimeStyles value is being used.
-Argument_InvalidTimeSpanStyles = An undefined TimeSpanStyles value is being used.
-Argument_DateTimeOffsetInvalidDateTimeStyles = The DateTimeStyles value 'NoCurrentDateDefault' is not allowed when parsing DateTimeOffset.
-Argument_NativeResourceAlreadyDefined = Native resource has already been defined.
-Argument_BadObjRef = Invalid ObjRef provided to '{0}'.
-Argument_InvalidCultureName = Culture name '{0}' is not supported.
-Argument_NameTooLong = The name '{0}' is too long to be a Culture or Region name, which is limited to {1} characters.
-Argument_NameContainsInvalidCharacters = The name '{0}' contains characters that are not valid for a Culture or Region.
-Argument_InvalidRegionName = Region name '{0}' is not supported.
-Argument_CannotCreateTypedReference = Cannot use function evaluation to create a TypedReference object.
-Arg_ArrayZeroError = Array must not be of length zero.
-Arg_BogusIComparer = Unable to sort because the IComparer.Compare() method returns inconsistent results. Either a value does not compare equal to itself, or one value repeatedly compared to another value yields different results. IComparer: '{0}'.
-Arg_CreatInstAccess = Cannot specify both CreateInstance and another access type.
-Arg_CryptographyException = Error occurred during a cryptographic operation.
-Arg_DateTimeRange = Combination of arguments to the DateTime constructor is out of the legal range.
-Arg_DecBitCtor = Decimal byte array constructor requires an array of length four containing valid decimal bytes.
-Arg_DlgtTargMeth = Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
-Arg_DlgtTypeMis = Delegates must be of the same type.
-Arg_DlgtNullInst = Delegate to an instance method cannot have null 'this'.
-Arg_DllInitFailure = One machine may not have remote administration enabled, or both machines may not be running the remote registry service.
-Arg_EmptyArray = Array may not be empty.
-Arg_EmptyOrNullArray = Array may not be empty or null.
-Arg_EmptyCollection = Collection must not be empty.
-Arg_EmptyOrNullString = String may not be empty or null.
-Argument_ItemNotExist = The specified item does not exist in this KeyedCollection.
-Argument_EncodingNotSupported = '{0}' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
-Argument_FallbackBufferNotEmpty = Cannot change fallback when buffer is not empty. Previous Convert() call left data in the fallback buffer.
-Argument_InvalidCodePageConversionIndex = Unable to translate Unicode character \\u{0:X4} at index {1} to specified code page.
-Argument_InvalidCodePageBytesIndex = Unable to translate bytes {0} at index {1} from specified code page to Unicode.
-Argument_RecursiveFallback = Recursive fallback not allowed for character \\u{0:X4}.
-Argument_RecursiveFallbackBytes = Recursive fallback not allowed for bytes {0}.
-Arg_EnumAndObjectMustBeSameType = Object must be the same type as the enum. The type passed in was '{0}'; the enum type was '{1}'.
-Arg_EnumIllegalVal = Illegal enum value: {0}.
-Arg_EnumNotSingleFlag = Must set exactly one flag.
-Arg_EnumAtLeastOneFlag = Must set at least one flag.
-Arg_EnumUnderlyingTypeAndObjectMustBeSameType = Enum underlying type and the object must be same type or object must be a String. Type passed in was '{0}'; the enum underlying type was '{1}'.
-Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType = Enum underlying type and the object must be same type or object. Type passed in was '{0}'; the enum underlying type was '{1}'.
-Arg_EnumMustHaveUnderlyingValueField = All enums must have an underlying value__ field.
-Arg_COMAccess = Must specify property Set or Get or method call for a COM Object.
-Arg_COMPropSetPut = Only one of the following binding flags can be set: BindingFlags.SetProperty, BindingFlags.PutDispProperty, BindingFlags.PutRefDispProperty.
-Arg_FldSetGet = Cannot specify both Get and Set on a field.
-Arg_PropSetGet = Cannot specify both Get and Set on a property.
-Arg_CannotBeNaN = TimeSpan does not accept floating point Not-a-Number values.
-Arg_FldGetPropSet = Cannot specify both GetField and SetProperty.
-Arg_FldSetPropGet = Cannot specify both SetField and GetProperty.
-Arg_FldSetInvoke = Cannot specify Set on a Field and Invoke on a method.
-Arg_FldGetArgErr = No arguments can be provided to Get a field value.
-Arg_FldSetArgErr = Only the field value can be specified to set a field value.
-Arg_GetMethNotFnd = Property Get method was not found.
-Arg_GuidArrayCtor = Byte array for GUID must be exactly {0} bytes long.
-Arg_HandleNotAsync = Handle does not support asynchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened synchronously (that is, it was not opened for overlapped I/O).
-Arg_HandleNotSync = Handle does not support synchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened asynchronously (that is, it was opened explicitly for overlapped I/O).
-Arg_HTCapacityOverflow = Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.
-Arg_IndexMustBeInt = All indexes must be of type Int32.
-Arg_InvalidConsoleColor = The ConsoleColor enum value was not defined on that enum. Please use a defined color from the enum.
-Arg_InvalidFileAttrs = Invalid File or Directory attributes value.
-Arg_InvalidHandle = Invalid handle.
-Arg_InvalidTypeInSignature = The signature Type array contains some invalid type (i.e. null, void)
-Arg_InvalidTypeInRetType = The return Type contains some invalid type (i.e. null, ByRef)
-Arg_EHClauseNotFilter = This ExceptionHandlingClause is not a filter.
-Arg_EHClauseNotClause = This ExceptionHandlingClause is not a clause.
-Arg_ReflectionOnlyCA = It is illegal to reflect on the custom attributes of a Type loaded via ReflectionOnlyGetType (see Assembly.ReflectionOnly) -- use CustomAttributeData instead.
-Arg_ReflectionOnlyInvoke = It is illegal to invoke a method on a Type loaded via ReflectionOnlyGetType.
-Arg_ReflectionOnlyField = It is illegal to get or set the value on a field on a Type loaded via ReflectionOnlyGetType.
-Arg_MemberInfoNullModule = The Module object containing the member cannot be null.
-Arg_ParameterInfoNullMember = The MemberInfo object defining the parameter cannot be null.
-Arg_ParameterInfoNullModule = The Module object containing the parameter cannot be null.
-Arg_AssemblyNullModule = The manifest module of the assembly cannot be null.
-Arg_LongerThanSrcArray = Source array was not long enough. Check the source index, length, and the array's lower bounds.
-Arg_LongerThanDestArray = Destination array was not long enough. Check the destination index, length, and the array's lower bounds.
-Arg_LowerBoundsMustMatch = The arrays' lower bounds must be identical.
-Arg_MustBeBoolean = Object must be of type Boolean.
-Arg_MustBeByte = Object must be of type Byte.
-Arg_MustBeChar = Object must be of type Char.
-Arg_MustBeDateTime = Object must be of type DateTime.
-Arg_MustBeDateTimeOffset = Object must be of type DateTimeOffset.
-Arg_MustBeDecimal = Object must be of type Decimal.
-Arg_MustBeDelegate = Type must derive from Delegate.
-Arg_MustBeDouble = Object must be of type Double.
-Arg_MustBeDriveLetterOrRootDir = Object must be a root directory ("C:\\") or a drive letter ("C").
-Arg_MustBeEnum = Type provided must be an Enum.
-Arg_MustBeEnumBaseTypeOrEnum = The value passed in must be an enum base or an underlying type for an enum, such as an Int32.
-Arg_MustBeGuid = Object must be of type GUID.
-Arg_MustBeIdentityReferenceType = Type must be an IdentityReference, such as NTAccount or SecurityIdentifier.
-Arg_MustBeInterface = Type passed must be an interface.
-Arg_MustBeInt16 = Object must be of type Int16.
-Arg_MustBeInt32 = Object must be of type Int32.
-Arg_MustBeInt64 = Object must be of type Int64.
-Arg_MustBePrimArray = Object must be an array of primitives.
-Arg_MustBePointer = Type must be a Pointer.
-Arg_MustBeStatic = Method must be a static method.
-Arg_MustBeString = Object must be of type String.
-Arg_MustBeStringPtrNotAtom = The pointer passed in as a String must not be in the bottom 64K of the process's address space.
-Arg_MustBeSByte = Object must be of type SByte.
-Arg_MustBeSingle = Object must be of type Single.
-Arg_MustBeTimeSpan = Object must be of type TimeSpan.
-Arg_MustBeType = Type must be a type provided by the runtime.
-Arg_MustBeUInt16 = Object must be of type UInt16.
-Arg_MustBeUInt32 = Object must be of type UInt32.
-Arg_MustBeUInt64 = Object must be of type UInt64.
-Arg_MustBeVersion = Object must be of type Version.
-Arg_MustBeTrue = Argument must be true.
-Arg_MustAllBeRuntimeType = At least one type argument is not a runtime type.
-Arg_NamedParamNull = Named parameter value must not be null.
-Arg_NamedParamTooBig = Named parameter array cannot be bigger than argument array.
-Arg_Need1DArray = Array was not a one-dimensional array.
-Arg_Need2DArray = Array was not a two-dimensional array.
-Arg_Need3DArray = Array was not a three-dimensional array.
-Arg_NeedAtLeast1Rank = Must provide at least one rank.
-Arg_NoDefCTor = No parameterless constructor defined for this object.
-Arg_BitArrayTypeUnsupported = Only supported array types for CopyTo on BitArrays are Boolean[], Int32[] and Byte[].
-Arg_DivideByZero = Attempted to divide by zero.
-Arg_NoAccessSpec = Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty).
-Arg_NoStaticVirtual = Method cannot be both static and virtual.
-Arg_NotFoundIFace = Interface not found.
-Arg_ObjObjEx = Object of type '{0}' cannot be converted to type '{1}'.
-Arg_ObjObj = Object type cannot be converted to target type.
-Arg_FieldDeclTarget = Field '{0}' defined on type '{1}' is not a field on the target object which is of type '{2}'.
-Arg_OleAutDateInvalid = Not a legal OleAut date.
-Arg_OleAutDateScale = OleAut date did not convert to a DateTime correctly.
-Arg_PlatformNotSupported = Operation is not supported on this platform.
-Arg_PlatformSecureString = SecureString is only supported on Windows 2000 SP3 and higher platforms.
-Arg_ParmCnt = Parameter count mismatch.
-Arg_ParmArraySize = Must specify one or more parameters.
-Arg_Path2IsRooted = Second path fragment must not be a drive or UNC name.
-Arg_PathIsVolume = Path must not be a drive.
-Arg_PrimWiden = Cannot widen from source type to target type either because the source type is a not a primitive type or the conversion cannot be accomplished.
-Arg_NullIndex = Arrays indexes must be set to an object instance.
-Arg_VarMissNull = Missing parameter does not have a default value.
-Arg_PropSetInvoke = Cannot specify Set on a property and Invoke on a method.
-Arg_PropNotFound = Could not find the specified property.
-Arg_RankIndices = Indices length does not match the array rank.
-Arg_RanksAndBounds = Number of lengths and lowerBounds must match.
-Arg_RegSubKeyAbsent = Cannot delete a subkey tree because the subkey does not exist.
-Arg_RemoveArgNotFound = Cannot remove the specified item because it was not found in the specified Collection.
-Arg_RegKeyDelHive = Cannot delete a registry hive's subtree.
-Arg_RegKeyNoRemoteConnect = No remote connection to '{0}' while trying to read the registry.
-Arg_RegKeyOutOfRange = Registry HKEY was out of the legal range.
-Arg_RegKeyNotFound = The specified registry key does not exist.
-Arg_RegKeyStrLenBug = Registry key names should not be greater than 255 characters.
-Arg_RegValStrLenBug = Registry value names should not be greater than 16,383 characters.
-Arg_RegBadKeyKind = The specified RegistryValueKind is an invalid value.
-Arg_RegGetOverflowBug = RegistryKey.GetValue does not allow a String that has a length greater than Int32.MaxValue.
-Arg_RegSetMismatchedKind = The type of the value object did not match the specified RegistryValueKind or the object could not be properly converted.
-Arg_RegSetBadArrType = RegistryKey.SetValue does not support arrays of type '{0}'. Only Byte[] and String[] are supported.
-Arg_RegSetStrArrNull = RegistryKey.SetValue does not allow a String[] that contains a null String reference.
-Arg_RegInvalidKeyName = Registry key name must start with a valid base key name.
-Arg_ResMgrNotResSet = Type parameter must refer to a subclass of ResourceSet.
-Arg_SetMethNotFnd = Property set method not found.
-Arg_TypeRefPrimitve = TypedReferences cannot be redefined as primitives.
-Arg_UnknownTypeCode = Unknown TypeCode value.
-Arg_VersionString = Version string portion was too short or too long.
-Arg_NoITypeInfo = Specified TypeInfo was invalid because it did not support the ITypeInfo interface.
-Arg_NoITypeLib = Specified TypeLib was invalid because it did not support the ITypeLib interface.
-Arg_NoImporterCallback = Specified type library importer callback was invalid because it did not support the ITypeLibImporterNotifySink interface.
-Arg_ImporterLoadFailure = The type library importer encountered an error during type verification. Try importing without class members.
-Arg_InvalidBase = Invalid Base.
-Arg_EnumValueNotFound = Requested value '{0}' was not found.
-Arg_EnumLitValueNotFound = Literal value was not found.
-Arg_MustContainEnumInfo = Must specify valid information for parsing in the string.
-Arg_InvalidSearchPattern = Search pattern cannot contain ".." to move up directories and can be contained only internally in file/directory names, as in "a..b".
-Arg_NegativeArgCount = Argument count must not be negative.
-Arg_InvalidAccessEntry = Specified access entry is invalid because it is unrestricted. The global flags should be specified instead.
-Arg_InvalidFileName = Specified file name was invalid.
-Arg_InvalidFileExtension = Specified file extension was not a valid extension.
-Arg_COMException = Error HRESULT E_FAIL has been returned from a call to a COM component.
-Arg_ExternalException = External component has thrown an exception.
-Arg_InvalidComObjectException = Attempt has been made to use a COM object that does not have a backing class factory.
-Arg_InvalidOleVariantTypeException = Specified OLE variant was invalid.
-Arg_MarshalDirectiveException = Marshaling directives are invalid.
-Arg_MarshalAsAnyRestriction = AsAny cannot be used on return types, ByRef parameters, ArrayWithOffset, or parameters passed from unmanaged to managed.
-Arg_NDirectBadObject = No PInvoke conversion exists for value passed to Object-typed parameter.
-Arg_SafeArrayTypeMismatchException = Specified array was not of the expected type.
-Arg_VTableCallsNotSupportedException = Attempted to make an early bound call on a COM dispatch-only interface.
-Arg_SafeArrayRankMismatchException = Specified array was not of the expected rank.
-Arg_AmbiguousMatchException = Ambiguous match found.
-Arg_CustomAttributeFormatException = Binary format of the specified custom attribute was invalid.
-Arg_InvalidFilterCriteriaException = Specified filter criteria was invalid.
-Arg_TypeLoadNullStr = A null or zero length string does not represent a valid Type.
-Arg_TargetInvocationException = Exception has been thrown by the target of an invocation.
-Arg_TargetParameterCountException = Number of parameters specified does not match the expected number.
-Arg_TypeAccessException = Attempt to access the type failed.
-Arg_TypeLoadException = Failure has occurred while loading a type.
-Arg_TypeUnloadedException = Type had been unloaded.
-Arg_ThreadStateException = Thread was in an invalid state for the operation being executed.
-Arg_ThreadStartException = Thread failed to start.
-Arg_WrongAsyncResult = IAsyncResult object did not come from the corresponding async method on this type.
-Arg_WrongType = The value "{0}" is not of type "{1}" and cannot be used in this generic collection.
-Argument_InvalidArgumentForComparison = Type of argument is not compatible with the generic comparer.
-Argument_ALSInvalidCapacity = Specified capacity must not be less than the current capacity.
-Argument_ALSInvalidSlot = Specified slot number was invalid.
-Argument_IdnIllegalName = Decoded string is not a valid IDN name.
-Argument_IdnBadBidi = Left to right characters may not be mixed with right to left characters in IDN labels.
-Argument_IdnBadLabelSize = IDN labels must be between 1 and 63 characters long.
-Argument_IdnBadNameSize = IDN names must be between 1 and {0} characters long.
-Argument_IdnBadPunycode = Invalid IDN encoded string.
-Argument_IdnBadStd3 = Label contains character '{0}' not allowed with UseStd3AsciiRules
-Arg_InvalidANSIString = The ANSI string passed in could not be converted from the default ANSI code page to Unicode.
-Arg_InvalidUTF8String = The UTF8 string passed in could not be converted to Unicode.
-Argument_InvalidCharSequence = Invalid Unicode code point found at index {0}.
-Argument_InvalidCharSequenceNoIndex = String contains invalid Unicode code points.
-Argument_InvalidCalendar = Not a valid calendar for the given culture.
-Argument_InvalidNormalizationForm = Invalid or unsupported normalization form.
-Argument_InvalidPathChars = Illegal characters in path.
-Argument_InvalidOffLen = Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
-Argument_InvalidSeekOrigin = Invalid seek origin.
-Argument_SeekOverflow = The specified seek offset '{0}' would result in a negative Stream position.
-Argument_InvalidUnity = Invalid Unity type.
-Argument_LongEnvVarName = Environment variable name cannot contain 1024 or more characters.
-Argument_LongEnvVarValue = Environment variable name or value is too long.
-Argument_StringFirstCharIsZero = The first char in the string is the null character.
-Argument_OnlyMscorlib = Only mscorlib's assembly is valid.
-Argument_PathEmpty = Path cannot be the empty string or all whitespace.
-Argument_PathFormatNotSupported = The given path's format is not supported.
-Argument_PathUriFormatNotSupported = URI formats are not supported.
-Argument_TypeNameTooLong = Type name was too long. The fully qualified type name must be less than 1,024 characters.
-Argument_StreamNotReadable = Stream was not readable.
-Argument_StreamNotWritable = Stream was not writable.
-Argument_InvalidNumberOfMembers = MemberData contains an invalid number of members.
-Argument_InvalidValue = Value was invalid.
-Argument_InvalidKey = Key was invalid.
-Argument_MinMaxValue = '{0}' cannot be greater than {1}.
-Argument_InvalidGroupSize = Every element in the value array should be between one and nine, except for the last element, which can be zero.
-Argument_MustHaveAttributeBaseClass = Type passed in must be derived from System.Attribute or System.Attribute itself.
-Argument_NoUninitializedStrings = Uninitialized Strings cannot be created.
-Argument_UnequalMembers = Supplied MemberInfo does not match the expected type.
-Argument_BadFormatSpecifier = Format specifier was invalid.
-Argument_InvalidHighSurrogate = Found a high surrogate char without a following low surrogate at index: {0}. The input may not be in this encoding, or may not contain valid Unicode (UTF-16) characters.
-Argument_InvalidLowSurrogate = Found a low surrogate char without a preceding high surrogate at index: {0}. The input may not be in this encoding, or may not contain valid Unicode (UTF-16) characters.
-Argument_UnmatchingSymScope = Non-matching symbol scope.
-Argument_NotInExceptionBlock = Not currently in an exception block.
-Argument_BadExceptionCodeGen = Incorrect code generation for exception block.
-Argument_NotExceptionType = Does not extend Exception.
-Argument_DuplicateResourceName = Duplicate resource name within an assembly.
-Argument_BadPersistableModuleInTransientAssembly = Cannot have a persistable module in a transient assembly.
-Argument_InvalidPermissionState = Invalid permission state.
-Argument_UnrestrictedIdentityPermission = Identity permissions cannot be unrestricted.
-Argument_WrongType = Operation on type '{0}' attempted with target of incorrect type.
-Argument_IllegalZone = Illegal security permission zone specified.
-Argument_HasToBeArrayClass = Must be an array type.
-Argument_InvalidDirectory = Invalid directory, '{0}'.
-Argument_DataLengthDifferent = Parameters 'members' and 'data' must have the same length.
-Argument_SigIsFinalized = Completed signature cannot be modified.
-Argument_ArraysInvalid = Array or pointer types are not valid.
-Argument_GenericsInvalid = Generic types are not valid.
-Argument_LargeInteger = Integer or token was too large to be encoded.
-Argument_BadSigFormat = Incorrect signature format.
-Argument_UnmatchedMethodForLocal = Local passed in does not belong to this ILGenerator.
-Argument_DuplicateName = Tried to add NamedPermissionSet with non-unique name.
-Argument_InvalidXMLElement = Invalid XML. Missing required tag <{0}> for type '{1}'.
-Argument_InvalidXMLMissingAttr = Invalid XML. Missing required attribute '{0}'.
-Argument_CannotGetTypeTokenForByRef = Cannot get TypeToken for a ByRef type.
-Argument_NotASimpleNativeType = The UnmanagedType passed to DefineUnmanagedMarshal is not a simple type. None of the following values may be used: UnmanagedType.ByValTStr, UnmanagedType.SafeArray, UnmanagedType.ByValArray, UnmanagedType.LPArray, UnmanagedType.CustomMarshaler.
-Argument_NotACustomMarshaler = Not a custom marshal.
-Argument_NoUnmanagedElementCount = Unmanaged marshal does not have ElementCount.
-Argument_NoNestedMarshal = Only LPArray or SafeArray has nested unmanaged marshal.
-Argument_InvalidXML = Invalid Xml.
-Argument_NoUnderlyingCCW = The object has no underlying COM data associated with it.
-Argument_BadFieldType = Bad field type in defining field.
-Argument_InvalidXMLBadVersion = Invalid Xml - can only parse elements of version one.
-Argument_NotAPermissionElement = 'elem' was not a permission element.
-Argument_NPMSInvalidName = Name can be neither null nor empty.
-Argument_InvalidElementTag = Invalid element tag '{0}'.
-Argument_InvalidElementText = Invalid element text '{0}'.
-Argument_InvalidElementName = Invalid element name '{0}'.
-Argument_InvalidElementValue = Invalid element value '{0}'.
-Argument_AttributeNamesMustBeUnique = Attribute names must be unique.
-Argument_InvalidHexFormat = Improperly formatted hex string.
-Argument_InvalidSite = Invalid site.
-Argument_InterfaceMap = 'this' type cannot be an interface itself.
-Argument_ArrayGetInterfaceMap = Interface maps for generic interfaces on arrays cannot be retrieved.
-Argument_InvalidName = Invalid name.
-Argument_InvalidDirectoryOnUrl = Invalid directory on URL.
-Argument_InvalidUrl = Invalid URL.
-Argument_InvalidKindOfTypeForCA = This type cannot be represented as a custom attribute.
-Argument_MustSupplyContainer = When supplying a FieldInfo for fixing up a nested type, a valid ID for that containing object must also be supplied.
-Argument_MustSupplyParent = When supplying the ID of a containing object, the FieldInfo that identifies the current field within that object must also be supplied.
-Argument_NoClass = Element does not specify a class.
-Argument_WrongElementType = '{0}' element required.
-Argument_UnableToGeneratePermissionSet = Unable to generate permission set; input XML may be malformed.
-Argument_NoEra = No Era was supplied.
-Argument_AssemblyAlreadyFullTrust = Assembly was already fully trusted.
-Argument_AssemblyNotFullTrust = Assembly was not fully trusted.
-Argument_AssemblyWinMD = Assembly must not be a Windows Runtime assembly.
-Argument_MemberAndArray = Cannot supply both a MemberInfo and an Array to indicate the parent of a value type.
-Argument_ObjNotComObject = The object's type must be __ComObject or derived from __ComObject.
-Argument_ObjIsWinRTObject = The object's type must not be a Windows Runtime type.
-Argument_TypeNotComObject = The type must be __ComObject or be derived from __ComObject.
-Argument_TypeIsWinRTType = The type must not be a Windows Runtime type.
-Argument_CantCallSecObjFunc = Cannot evaluate a security function.
-Argument_StructMustNotBeValueClass = The structure must not be a value class.
-Argument_NoSpecificCulture = Please select a specific culture, such as zh-CN, zh-HK, zh-TW, zh-MO, zh-SG.
-Argument_InvalidResourceCultureName = The given culture name '{0}' cannot be used to locate a resource file. Resource filenames must consist of only letters, numbers, hyphens or underscores.
-Argument_InvalidParamInfo = Invalid type for ParameterInfo member in Attribute class.
-Argument_EmptyDecString = Decimal separator cannot be the empty string.
-Argument_OffsetOfFieldNotFound = Field passed in is not a marshaled member of the type '{0}'.
-Argument_EmptyStrongName = StrongName cannot have an empty string for the assembly name.
-Argument_NotSerializable = Argument passed in is not serializable.
-Argument_EmptyApplicationName = ApplicationId cannot have an empty string for the name.
-Argument_NoDomainManager = The domain manager specified by the host could not be instantiated.
-Argument_NoMain = Main entry point not defined.
-Argument_InvalidDateTimeKind = Invalid DateTimeKind value.
-Argument_ConflictingDateTimeStyles = The DateTimeStyles values AssumeLocal and AssumeUniversal cannot be used together.
-Argument_ConflictingDateTimeRoundtripStyles = The DateTimeStyles value RoundtripKind cannot be used with the values AssumeLocal, AssumeUniversal or AdjustToUniversal.
-Argument_InvalidDigitSubstitution = The DigitSubstitution property must be of a valid member of the DigitShapes enumeration. Valid entries include Context, NativeNational or None.
-Argument_InvalidNativeDigitCount = The NativeDigits array must contain exactly ten members.
-Argument_InvalidNativeDigitValue = Each member of the NativeDigits array must be a single text element (one or more UTF16 code points) with a Unicode Nd (Number, Decimal Digit) property indicating it is a digit.
-ArgumentException_InvalidAceBinaryForm = The binary form of an ACE object is invalid.
-ArgumentException_InvalidAclBinaryForm = The binary form of an ACL object is invalid.
-ArgumentException_InvalidSDSddlForm = The SDDL form of a security descriptor object is invalid.
-Argument_InvalidSafeHandle = The SafeHandle is invalid.
-Argument_CannotPrepareAbstract = Abstract methods cannot be prepared.
-Argument_ArrayTooLarge = The input array length must not exceed Int32.MaxValue / {0}. Otherwise BitArray.Length would exceed Int32.MaxValue.
-Argument_RelativeUrlMembershipCondition = UrlMembershipCondition requires an absolute URL.
-Argument_EmptyWaithandleArray = Waithandle array may not be empty.
-Argument_InvalidSafeBufferOffLen = Offset and length were greater than the size of the SafeBuffer.
-Argument_NotEnoughBytesToRead = There are not enough bytes remaining in the accessor to read at this position.
-Argument_NotEnoughBytesToWrite = There are not enough bytes remaining in the accessor to write at this position.
-Argument_OffsetAndLengthOutOfBounds = Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
-Argument_OffsetAndCapacityOutOfBounds = Offset and capacity were greater than the size of the view.
-Argument_UnmanagedMemAccessorWrapAround = The UnmanagedMemoryAccessor capacity and offset would wrap around the high end of the address space.
-Argument_UnrecognizedLoaderOptimization = Unrecognized LOADER_OPTIMIZATION property value. Supported values may include "SingleDomain", "MultiDomain", "MultiDomainHost", and "NotSpecified".
-ArgumentException_NotAllCustomSortingFuncsDefined = Implementations of all the NLS functions must be provided.
-ArgumentException_MinSortingVersion = The runtime does not support a version of "{0}" less than {1}.
-Argument_PreAllocatedAlreadyAllocated = 'preAllocated' is already in use.
-Argument_NativeOverlappedWrongBoundHandle = 'overlapped' was not allocated by this ThreadPoolBoundHandle instance.
-Argument_NativeOverlappedAlreadyFree = 'overlapped' has already been freed.
-Argument_AlreadyBoundOrSyncHandle = 'handle' has already been bound to the thread pool, or was not opened for asynchronous I/O.
-Argument_InvalidTypeWithPointersNotSupported = Cannot use type '{0}'. Only value types without pointers or references are supported.
-Argument_DestinationTooShort = Destination is too short.
-
-;
-; =====================================================
-; Reflection Emit resource strings
-Arugment_EmitMixedContext1 = Type '{0}' was loaded in the ReflectionOnly context but the AssemblyBuilder was not created as AssemblyBuilderAccess.ReflectionOnly.
-Arugment_EmitMixedContext2 = Type '{0}' was not loaded in the ReflectionOnly context but the AssemblyBuilder was created as AssemblyBuilderAccess.ReflectionOnly.
-Argument_BadSizeForData = Data size must be > 0 and < 0x3f0000
-Argument_InvalidLabel = Invalid Label.
-Argument_RedefinedLabel = Label multiply defined.
-Argument_UnclosedExceptionBlock = The IL Generator cannot be used while there are unclosed exceptions.
-Argument_MissingDefaultConstructor = was missing default constructor.
-Argument_TooManyFinallyClause = Exception blocks may have at most one finally clause.
-Argument_NotInTheSameModuleBuilder = The argument passed in was not from the same ModuleBuilder.
-Argument_BadCurrentLocalVariable = Bad current local variable for setting symbol information.
-Argument_DuplicateModuleName = Duplicate dynamic module name within an assembly.
-Argument_DuplicateTypeName = Duplicate type name within an assembly.
-Argument_InvalidAssemblyName = Assembly names may not begin with whitespace or contain the characters '/', or '\\' or ':'.
-Argument_InvalidGenericInstantiation = The given generic instantiation was invalid.
-Argument_DuplicatedFileName = Duplicate file names.
-Argument_GlobalFunctionHasToBeStatic = Global members must be static.
-Argument_BadPInvokeOnInterface = PInvoke methods cannot exist on interfaces.
-Argument_BadPInvokeMethod = PInvoke methods must be static and native and cannot be abstract.
-Argument_MethodRedefined = Method has been already defined.
-Argument_BadTypeAttrAbstractNFinal = Bad type attributes. A type cannot be both abstract and final.
-Argument_BadTypeAttrNestedVisibilityOnNonNestedType = Bad type attributes. Nested visibility flag set on a non-nested type.
-Argument_BadTypeAttrNonNestedVisibilityNestedType = Bad type attributes. Non-nested visibility flag set on a nested type.
-Argument_BadTypeAttrInvalidLayout = Bad type attributes. Invalid layout attribute specified.
-Argument_BadTypeAttrReservedBitsSet = Bad type attributes. Reserved bits set on the type.
-Argument_BadFieldSig = Field signatures do not have return types.
-Argument_ShouldOnlySetVisibilityFlags = Should only set visibility flags when creating EnumBuilder.
-Argument_BadNestedTypeFlags = Visibility of interfaces must be one of the following: NestedAssembly, NestedFamANDAssem, NestedFamily, NestedFamORAssem, NestedPrivate or NestedPublic.
-Argument_ShouldNotSpecifyExceptionType = Should not specify exception type for catch clause for filter block.
-Argument_BadLabel = Bad label in ILGenerator.
-Argument_BadLabelContent = Bad label content in ILGenerator.
-Argument_EmitWriteLineType = EmitWriteLine does not support this field or local type.
-Argument_ConstantNull = Null is not a valid constant value for this type.
-Argument_ConstantDoesntMatch = Constant does not match the defined type.
-Argument_ConstantNotSupported = {0} is not a supported constant type.
-Argument_BadConstructor = Cannot have private or static constructor.
-Argument_BadConstructorCallConv = Constructor must have standard calling convention.
-Argument_BadPropertyForConstructorBuilder = Property must be on the same type of the given ConstructorInfo.
-Argument_NotAWritableProperty = Not a writable property.
-Argument_BadFieldForConstructorBuilder = Field must be on the same type of the given ConstructorInfo.
-Argument_BadAttributeOnInterfaceMethod = Interface method must be abstract and virtual.
-ArgumentException_BadMethodImplBody = MethodOverride's body must be from this type.
-Argument_BadParameterCountsForConstructor = Parameter count does not match passed in argument value count.
-Argument_BadParameterTypeForConstructor = Passed in argument value at index {0} does not match the parameter type.
-Argument_BadTypeInCustomAttribute = An invalid type was used as a custom attribute constructor argument, field or property.
-Argument_DateTimeBadBinaryData = The binary data must result in a DateTime with ticks between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
-Argument_VerStringTooLong = The unmanaged Version information is too large to persist.
-Argument_UnknownUnmanagedCallConv = Unknown unmanaged calling convention for function signature.
-Argument_BadConstantValue = Bad default value.
-Argument_IllegalName = Illegal name.
-Argument_cvtres_NotFound = Cannot find cvtres.exe
-Argument_BadCAForUnmngRSC = Bad '{0}' while generating unmanaged resource information.
-Argument_MustBeInterfaceMethod = The MemberInfo must be an interface method.
-Argument_CORDBBadVarArgCallConv = Cannot evaluate a VarArgs function.
-Argument_CORDBBadMethod = Cannot find the method on the object instance.
-Argument_InvalidOpCodeOnDynamicMethod = Ldtoken, Ldftn and Ldvirtftn OpCodes cannot target DynamicMethods.
-Argument_InvalidTypeForDynamicMethod = Invalid type owner for DynamicMethod.
-Argument_NeedGenericMethodDefinition = Method must represent a generic method definition on a generic type definition.
-Argument_MethodNeedGenericDeclaringType = The specified method cannot be dynamic or global and must be declared on a generic type definition.
-Argument_ConstructorNeedGenericDeclaringType = The specified constructor must be declared on a generic type definition.
-Argument_FieldNeedGenericDeclaringType = The specified field must be declared on a generic type definition.
-Argument_InvalidMethodDeclaringType = The specified method must be declared on the generic type definition of the specified type.
-Argument_InvalidConstructorDeclaringType = The specified constructor must be declared on the generic type definition of the specified type.
-Argument_InvalidFieldDeclaringType = The specified field must be declared on the generic type definition of the specified type.
-Argument_NeedNonGenericType = The specified Type must not be a generic type definition.
-Argument_MustBeTypeBuilder = 'type' must contain a TypeBuilder as a generic argument.
-Argument_CannotSetParentToInterface = Cannot set parent to an interface.
-Argument_MismatchedArrays = Two arrays, {0} and {1}, must be of the same size.
-Argument_NeedNonGenericObject = The specified object must not be an instance of a generic type.
-Argument_NeedStructWithNoRefs = The specified Type must be a struct containing no references.
-Argument_NotMethodCallOpcode = The specified opcode cannot be passed to EmitCall.
-
-; =====================================================
-;
-Argument_ModuleAlreadyLoaded = The specified module has already been loaded.
-Argument_MustHaveLayoutOrBeBlittable = The specified structure must be blittable or have layout information.
-Argument_NotSimpleFileName = The filename must not include a path specification.
-Argument_TypeMustBeVisibleFromCom = The specified type must be visible from COM.
-Argument_TypeMustBeComCreatable = The type must be creatable from COM.
-Argument_TypeMustNotBeComImport = The type must not be imported from COM.
-Argument_PolicyFileDoesNotExist = The requested policy file does not exist.
-Argument_NonNullObjAndCtx = Either obj or ctx must be null.
-Argument_NoModuleFileExtension = Module file name '{0}' must have file extension.
-Argument_TypeDoesNotContainMethod = Type does not contain the given method.
-Argument_StringZeroLength = String cannot be of zero length.
-Argument_MustBeString = String is too long or has invalid contents.
-Argument_AbsolutePathRequired = Absolute path information is required.
-Argument_ManifestFileDoesNotExist = The specified manifest file does not exist.
-Argument_MustBeRuntimeType = Type must be a runtime Type object.
-Argument_TypeNotValid = The Type object is not valid.
-Argument_MustBeRuntimeMethodInfo = MethodInfo must be a runtime MethodInfo object.
-Argument_MustBeRuntimeFieldInfo = FieldInfo must be a runtime FieldInfo object.
-Argument_InvalidFieldInfo = The FieldInfo object is not valid.
-Argument_InvalidConstructorInfo = The ConstructorInfo object is not valid.
-Argument_MustBeRuntimeAssembly = Assembly must be a runtime Assembly object.
-Argument_MustBeRuntimeModule = Module must be a runtime Module object.
-Argument_MustBeRuntimeParameterInfo = ParameterInfo must be a runtime ParameterInfo object.
-Argument_InvalidParameterInfo = The ParameterInfo object is not valid.
-Argument_MustBeRuntimeReflectionObject = The object must be a runtime Reflection object.
-Argument_InvalidMarshalByRefObject = The MarshalByRefObject is not valid.
-Argument_TypedReferenceInvalidField = Field in TypedReferences cannot be static or init only.
-Argument_HandleLeak = Cannot pass a GCHandle across AppDomains.
-Argument_ArgumentZero = Argument cannot be zero.
-Argument_ImproperType = Improper types in collection.
-Argument_NotAMembershipCondition = The type does not implement IMembershipCondition
-Argument_NotAPermissionType = The type does not implement IPermission
-Argument_NotACodeGroupType = The type does not inherit from CodeGroup
-Argument_NotATP = Type must be a TransparentProxy
-Argument_AlreadyACCW = The object already has a CCW associated with it.
-Argument_OffsetLocalMismatch = The UTC Offset of the local dateTime parameter does not match the offset argument.
-Argument_OffsetUtcMismatch = The UTC Offset for Utc DateTime instances must be 0.
-Argument_UTCOutOfRange = The UTC time represented when the offset is applied must be between year 0 and 10,000.
-Argument_OffsetOutOfRange = Offset must be within plus or minus 14 hours.
-Argument_OffsetPrecision = Offset must be specified in whole minutes.
-Argument_FlagNotSupported = One or more flags are not supported.
-Argument_MustBeFalse = Argument must be initialized to false
-Argument_ToExclusiveLessThanFromExclusive = fromInclusive must be less than or equal to toExclusive.
-Argument_FrameworkNameTooShort=FrameworkName cannot have less than two components or more than three components.
-Argument_FrameworkNameInvalid=FrameworkName is invalid.
-Argument_FrameworkNameMissingVersion=FrameworkName version component is missing.
-#if FEATURE_COMINTEROP
-Argument_TypeNotActivatableViaWindowsRuntime = Type '{0}' does not have an activation factory because it is not activatable by Windows Runtime.
-Argument_WinRTSystemRuntimeType = Cannot marshal type '{0}' to Windows Runtime. Only 'System.RuntimeType' is supported.
-Argument_Unexpected_TypeSource = Unexpected TypeKind when marshaling Windows.Foundation.TypeName.
-#endif // FEATURE_COMINTEROP
-
-; ArgumentNullException
-ArgumentNull_Array = Array cannot be null.
-ArgumentNull_ArrayValue = Found a null value within an array.
-ArgumentNull_ArrayElement = At least one element in the specified array was null.
-ArgumentNull_Assembly = Assembly cannot be null.
-ArgumentNull_AssemblyName = AssemblyName cannot be null.
-ArgumentNull_AssemblyNameName = AssemblyName.Name cannot be null or an empty string.
-ArgumentNull_Buffer = Buffer cannot be null.
-ArgumentNull_Collection = Collection cannot be null.
-ArgumentNull_CultureInfo = CultureInfo cannot be null.
-ArgumentNull_Dictionary = Dictionary cannot be null.
-ArgumentNull_FileName = File name cannot be null.
-ArgumentNull_Key = Key cannot be null.
-ArgumentNull_Graph = Object Graph cannot be null.
-ArgumentNull_Path = Path cannot be null.
-ArgumentNull_Stream = Stream cannot be null.
-ArgumentNull_String = String reference not set to an instance of a String.
-ArgumentNull_Type = Type cannot be null.
-ArgumentNull_Obj = Object cannot be null.
-ArgumentNull_GUID = GUID cannot be null.
-ArgumentNull_NullMember = Member at position {0} was null.
-ArgumentNull_Generic = Value cannot be null.
-ArgumentNull_WithParamName = Parameter '{0}' cannot be null.
-ArgumentNull_Child = Cannot have a null child.
-ArgumentNull_SafeHandle = SafeHandle cannot be null.
-ArgumentNull_CriticalHandle = CriticalHandle cannot be null.
-ArgumentNull_TypedRefType = Type in TypedReference cannot be null.
-ArgumentNull_ApplicationTrust = The application trust cannot be null.
-ArgumentNull_TypeRequiredByResourceScope = The type parameter cannot be null when scoping the resource's visibility to Private or Assembly.
-ArgumentNull_Waithandles = The waitHandles parameter cannot be null.
-
-; ArgumentOutOfRangeException
-ArgumentOutOfRange_AddressSpace = The number of bytes cannot exceed the virtual address space on a 32 bit machine.
-ArgumentOutOfRange_ArrayLB = Number was less than the array's lower bound in the first dimension.
-ArgumentOutOfRange_ArrayLBAndLength = Higher indices will exceed Int32.MaxValue because of large lower bound and/or length.
-ArgumentOutOfRange_ArrayLength = The length of the array must be between {0} and {1}, inclusive.
-ArgumentOutOfRange_ArrayLengthMultiple = The length of the array must be a multiple of {0}.
-ArgumentOutOfRange_ArrayListInsert = Insertion index was out of range. Must be non-negative and less than or equal to size.
-ArgumentOutOfRange_ArrayTooSmall = Destination array is not long enough to copy all the required data. Check array length and offset.
-ArgumentOutOfRange_BeepFrequency = Console.Beep's frequency must be between {0} and {1}.
-ArgumentOutOfRange_BiggerThanCollection = Larger than collection size.
-ArgumentOutOfRange_Bounds_Lower_Upper = Argument must be between {0} and {1}.
-ArgumentOutOfRange_Count = Count must be positive and count must refer to a location within the string/array/collection.
-ArgumentOutOfRange_CalendarRange = Specified time is not supported in this calendar. It should be between {0} (Gregorian date) and {1} (Gregorian date), inclusive.
-ArgumentOutOfRange_ConsoleBufferBoundaries = The value must be greater than or equal to zero and less than the console's buffer size in that dimension.
-ArgumentOutOfRange_ConsoleBufferLessThanWindowSize = The console buffer size must not be less than the current size and position of the console window, nor greater than or equal to Int16.MaxValue.
-ArgumentOutOfRange_ConsoleWindowBufferSize = The new console window size would force the console buffer size to be too large.
-ArgumentOutOfRange_ConsoleTitleTooLong = The console title is too long.
-ArgumentOutOfRange_ConsoleWindowPos = The window position must be set such that the current window size fits within the console's buffer, and the numbers must not be negative.
-ArgumentOutOfRange_ConsoleWindowSize_Size = The value must be less than the console's current maximum window size of {0} in that dimension. Note that this value depends on screen resolution and the console font.
-ArgumentOutOfRange_ConsoleKey = Console key values must be between 0 and 255.
-ArgumentOutOfRange_CursorSize = The cursor size is invalid. It must be a percentage between 1 and 100.
-ArgumentOutOfRange_BadYearMonthDay = Year, Month, and Day parameters describe an un-representable DateTime.
-ArgumentOutOfRange_BadHourMinuteSecond = Hour, Minute, and Second parameters describe an un-representable DateTime.
-ArgumentOutOfRange_DateArithmetic = The added or subtracted value results in an un-representable DateTime.
-ArgumentOutOfRange_DateTimeBadMonths = Months value must be between +/-120000.
-ArgumentOutOfRange_DateTimeBadYears = Years value must be between +/-10000.
-ArgumentOutOfRange_DateTimeBadTicks = Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
-ArgumentOutOfRange_Day = Day must be between 1 and {0} for month {1}.
-ArgumentOutOfRange_DecimalRound = Decimal can only round to between 0 and 28 digits of precision.
-ArgumentOutOfRange_DecimalScale = Decimal's scale value must be between 0 and 28, inclusive.
-ArgumentOutOfRange_Era = Time value was out of era range.
-ArgumentOutOfRange_Enum = Enum value was out of legal range.
-ArgumentOutOfRange_FileLengthTooBig = Specified file length was too large for the file system.
-ArgumentOutOfRange_FileTimeInvalid = Not a valid Win32 FileTime.
-ArgumentOutOfRange_GetByteCountOverflow = Too many characters. The resulting number of bytes is larger than what can be returned as an int.
-ArgumentOutOfRange_GetCharCountOverflow = Too many bytes. The resulting number of chars is larger than what can be returned as an int.
-ArgumentOutOfRange_HashtableLoadFactor = Load factor needs to be between 0.1 and 1.0.
-ArgumentOutOfRange_HugeArrayNotSupported = Arrays larger than 2GB are not supported.
-ArgumentOutOfRange_InvalidHighSurrogate = A valid high surrogate character is between 0xd800 and 0xdbff, inclusive.
-ArgumentOutOfRange_InvalidLowSurrogate = A valid low surrogate character is between 0xdc00 and 0xdfff, inclusive.
-ArgumentOutOfRange_InvalidEraValue = Era value was not valid.
-ArgumentOutOfRange_InvalidUserDefinedAceType = User-defined ACEs must not have a well-known ACE type.
-ArgumentOutOfRange_InvalidUTF32 = A valid UTF32 value is between 0x000000 and 0x10ffff, inclusive, and should not include surrogate codepoint values (0x00d800 ~ 0x00dfff).
-ArgumentOutOfRange_Index = Index was out of range. Must be non-negative and less than the size of the collection.
-ArgumentOutOfRange_IndexString = Index was out of range. Must be non-negative and less than the length of the string.
-ArgumentOutOfRange_StreamLength = Stream length must be non-negative and less than 2^31 - 1 - origin.
-ArgumentOutOfRange_LessEqualToIntegerMaxVal = Argument must be less than or equal to 2^31 - 1 milliseconds.
-ArgumentOutOfRange_Month = Month must be between one and twelve.
-ArgumentOutOfRange_MustBeNonNegInt32 = Value must be non-negative and less than or equal to Int32.MaxValue.
-ArgumentOutOfRange_NeedNonNegNum = Non-negative number required.
-ArgumentOutOfRange_NeedNonNegOrNegative1 = Number must be either non-negative and less than or equal to Int32.MaxValue or -1.
-ArgumentOutOfRange_NeedPosNum = Positive number required.
-ArgumentOutOfRange_NegativeCapacity = Capacity must be positive.
-ArgumentOutOfRange_NegativeCount = Count cannot be less than zero.
-ArgumentOutOfRange_NegativeLength = Length cannot be less than zero.
-ArgumentOutOfRange_NegFileSize = Length must be non-negative.
-ArgumentOutOfRange_ObjectID = objectID cannot be less than or equal to zero.
-ArgumentOutOfRange_SmallCapacity = capacity was less than the current size.
-ArgumentOutOfRange_QueueGrowFactor = Queue grow factor must be between {0} and {1}.
-ArgumentOutOfRange_RoundingDigits = Rounding digits must be between 0 and 15, inclusive.
-ArgumentOutOfRange_StartIndex = StartIndex cannot be less than zero.
-ArgumentOutOfRange_MustBePositive = '{0}' must be greater than zero.
-ArgumentOutOfRange_MustBeNonNegNum = '{0}' must be non-negative.
-ArgumentOutOfRange_LengthGreaterThanCapacity = The length cannot be greater than the capacity.
-ArgumentOutOfRange_ListInsert = Index must be within the bounds of the List.
-ArgumentOutOfRange_StartIndexLessThanLength = startIndex must be less than length of string.
-ArgumentOutOfRange_StartIndexLargerThanLength = startIndex cannot be larger than length of string.
-ArgumentOutOfRange_EndIndexStartIndex = endIndex cannot be greater than startIndex.
-ArgumentOutOfRange_IndexCount = Index and count must refer to a location within the string.
-ArgumentOutOfRange_IndexCountBuffer = Index and count must refer to a location within the buffer.
-ArgumentOutOfRange_IndexLength = Index and length must refer to a location within the string.
-ArgumentOutOfRange_InvalidThreshold = The specified threshold for creating dictionary is out of range.
-ArgumentOutOfRange_Capacity = Capacity exceeds maximum capacity.
-ArgumentOutOfRange_Length = The specified length exceeds maximum capacity of SecureString.
-ArgumentOutOfRange_LengthTooLarge = The specified length exceeds the maximum value of {0}.
-ArgumentOutOfRange_SmallMaxCapacity = MaxCapacity must be one or greater.
-ArgumentOutOfRange_GenericPositive = Value must be positive.
-ArgumentOutOfRange_Range = Valid values are between {0} and {1}, inclusive.
-ArgumentOutOfRange_AddValue = Value to add was out of range.
-ArgumentOutOfRange_OffsetLength = Offset and length must refer to a position in the string.
-ArgumentOutOfRange_OffsetOut = Either offset did not refer to a position in the string, or there is an insufficient length of destination character array.
-ArgumentOutOfRange_PartialWCHAR = Pointer startIndex and length do not refer to a valid string.
-ArgumentOutOfRange_ParamSequence = The specified parameter index is not in range.
-ArgumentOutOfRange_Version = Version's parameters must be greater than or equal to zero.
-ArgumentOutOfRange_TimeoutTooLarge = Time-out interval must be less than 2^32-2.
-ArgumentOutOfRange_UIntPtrMax-1 = The length of the buffer must be less than the maximum UIntPtr value for your platform.
-ArgumentOutOfRange_UnmanagedMemStreamLength = UnmanagedMemoryStream length must be non-negative and less than 2^63 - 1 - baseAddress.
-ArgumentOutOfRange_UnmanagedMemStreamWrapAround = The UnmanagedMemoryStream capacity would wrap around the high end of the address space.
-ArgumentOutOfRange_PeriodTooLarge = Period must be less than 2^32-2.
-ArgumentOutOfRange_Year = Year must be between 1 and 9999.
-ArgumentOutOfRange_BinaryReaderFillBuffer = The number of bytes requested does not fit into BinaryReader's internal buffer.
-ArgumentOutOfRange_PositionLessThanCapacityRequired = The position may not be greater or equal to the capacity of the accessor.
-
-; ArithmeticException
-Arithmetic_NaN = Function does not accept floating point Not-a-Number values.
-
-; ArrayTypeMismatchException
-ArrayTypeMismatch_CantAssignType = Source array type cannot be assigned to destination array type.
-ArrayTypeMismatch_ConstrainedCopy = Array.ConstrainedCopy will only work on array types that are provably compatible, without any form of boxing, unboxing, widening, or casting of each array element. Change the array types (i.e., copy a Derived[] to a Base[]), or use a mitigation strategy in the CER for Array.Copy's less powerful reliability contract, such as cloning the array or throwing away the potentially corrupt destination array.
-
-; BadImageFormatException
-BadImageFormat_ResType&SerBlobMismatch = The type serialized in the .resources file was not the same type that the .resources file said it contained. Expected '{0}' but read '{1}'.
-BadImageFormat_ResourcesIndexTooLong = Corrupt .resources file. String for name index '{0}' extends past the end of the file.
-BadImageFormat_ResourcesNameTooLong = Corrupt .resources file. Resource name extends past the end of the file.
-BadImageFormat_ResourcesNameInvalidOffset = Corrupt .resources file. Invalid offset '{0}' into name section.
-BadImageFormat_ResourcesHeaderCorrupted = Corrupt .resources file. Unable to read resources from this file because of invalid header information. Try regenerating the .resources file.
-BadImageFormat_ResourceNameCorrupted = Corrupt .resources file. A resource name extends past the end of the stream.
-BadImageFormat_ResourceNameCorrupted_NameIndex = Corrupt .resources file. The resource name for name index {0} extends past the end of the stream.
-BadImageFormat_ResourceDataLengthInvalid = Corrupt .resources file. The specified data length '{0}' is not a valid position in the stream.
-BadImageFormat_TypeMismatch = Corrupt .resources file. The specified type doesn't match the available data in the stream.
-BadImageFormat_InvalidType = Corrupt .resources file. The specified type doesn't exist.
-BadImageFormat_ResourcesIndexInvalid = Corrupt .resources file. The resource index '{0}' is outside the valid range.
-BadImageFormat_StreamPositionInvalid = Corrupt .resources file. The specified position '{0}' is not a valid position in the stream.
-BadImageFormat_ResourcesDataInvalidOffset = Corrupt .resources file. Invalid offset '{0}' into data section.
-BadImageFormat_NegativeStringLength = Corrupt .resources file. String length must be non-negative.
-BadImageFormat_ParameterSignatureMismatch = The parameters and the signature of the method don't match.
-
-; Cryptography
-; These strings still appear in bcl.small but should go away eventually
-Cryptography_CSSM_Error = Error 0x{0} from the operating system security framework: '{1}'.
-Cryptography_CSSM_Error_Unknown = Error 0x{0} from the operating system security framework.
-Cryptography_InvalidDSASignatureSize = Length of the DSA signature was not 40 bytes.
-Cryptography_InvalidHandle = {0} is an invalid handle.
-Cryptography_InvalidOID = Object identifier (OID) is unknown.
-Cryptography_OAEPDecoding = Error occurred while decoding OAEP padding.
-Cryptography_PasswordDerivedBytes_InvalidIV = The Initialization vector should have the same length as the algorithm block size in bytes.
-Cryptography_SSE_InvalidDataSize = Length of the data to encrypt is invalid.
-Cryptography_X509_ExportFailed = The certificate export operation failed.
-Cryptography_X509_InvalidContentType = Invalid content type.
-Cryptography_CryptoStream_FlushFinalBlockTwice = FlushFinalBlock() method was called twice on a CryptoStream. It can only be called once.
-Cryptography_HashKeySet = Hash key cannot be changed after the first write to the stream.
-Cryptography_HashNotYetFinalized = Hash must be finalized before the hash value is retrieved.
-Cryptography_InsufficientBuffer = Input buffer contains insufficient data.
-Cryptography_InvalidBlockSize = Specified block size is not valid for this algorithm.
-Cryptography_InvalidCipherMode = Specified cipher mode is not valid for this algorithm.
-Cryptography_InvalidIVSize = Specified initialization vector (IV) does not match the block size for this algorithm.
-Cryptography_InvalidKeySize = Specified key is not a valid size for this algorithm.
-Cryptography_PasswordDerivedBytes_FewBytesSalt = Salt is not at least eight bytes.
-Cryptography_PKCS7_InvalidPadding = Padding is invalid and cannot be removed.
-Cryptography_UnknownHashAlgorithm='{0}' is not a known hash algorithm.
-
-; EventSource
-EventSource_ToString = EventSource({0}, {1})
-EventSource_EventSourceGuidInUse = An instance of EventSource with Guid {0} already exists.
-EventSource_KeywordNeedPowerOfTwo = Value {0} for keyword {1} needs to be a power of 2.
-EventSource_UndefinedKeyword = Use of undefined keyword value {0} for event {1}.
-EventSource_UnsupportedEventTypeInManifest = Unsupported type {0} in event source.
-EventSource_ListenerNotFound = Listener not found.
-EventSource_ListenerCreatedInsideCallback = Creating an EventListener inside a EventListener callback.
-EventSource_AttributeOnNonVoid = Event attribute placed on method {0} which does not return 'void'.
-EventSource_NeedPositiveId = Event IDs must be positive integers.
-EventSource_ReservedOpcode = Opcode values less than 11 are reserved for system use.
-EventSource_ReservedKeywords = Keywords values larger than 0x0000100000000000 are reserved for system use
-EventSource_PayloadTooBig=The payload for a single event is too large.
-EventSource_NoFreeBuffers=No Free Buffers available from the operating system (e.g. event rate too fast).
-EventSource_NullInput=Null passed as a event argument.
-EventSource_TooManyArgs=Too many arguments.
-EventSource_SessionIdError=Bit position in AllKeywords ({0}) must equal the command argument named "EtwSessionKeyword" ({1}).
-EventSource_EnumKindMismatch = The type of {0} is not expected in {1}.
-EventSource_MismatchIdToWriteEvent = Event {0} is givien event ID {1} but {2} was passed to WriteEvent.
-EventSource_EventIdReused = Event {0} has ID {1} which is already in use.
-EventSource_EventNameReused = Event name {0} used more than once. If you wish to overload a method, the overloaded method should have a NonEvent attribute.
-EventSource_UndefinedChannel = Use of undefined channel value {0} for event {1}.
-EventSource_UndefinedOpcode = Use of undefined opcode value {0} for event {1}.
-ArgumentOutOfRange_MaxArgExceeded = The total number of parameters must not exceed {0}.
-ArgumentOutOfRange_MaxStringsExceeded = The number of String parameters must not exceed {0}.
-ArgumentOutOfRange_NeedValidId = The ID parameter must be in the range {0} through {1}.
-EventSource_NeedGuid = The Guid of an EventSource must be non zero.
-EventSource_NeedName = The name of an EventSource must not be null.
-EventSource_EtwAlreadyRegistered = The provider has already been registered with the operating system.
-EventSource_ListenerWriteFailure = An error occurred when writing to a listener.
-EventSource_TypeMustDeriveFromEventSource = Event source types must derive from EventSource.
-EventSource_TypeMustBeSealedOrAbstract = Event source types must be sealed or abstract.
-EventSource_TaskOpcodePairReused = Event {0} (with ID {1}) has the same task/opcode pair as event {2} (with ID {3}).
-EventSource_EventMustHaveTaskIfNonDefaultOpcode = Event {0} (with ID {1}) has a non-default opcode but not a task.
-EventSource_EventNameDoesNotEqualTaskPlusOpcode = Event {0} (with ID {1}) has a name that is not the concatenation of its task name and opcode.
-EventSource_PeriodIllegalInProviderName = Period character ('.') is illegal in an ETW provider name ({0}).
-EventSource_IllegalOpcodeValue = Opcode {0} has a value of {1} which is outside the legal range (11-238).
-EventSource_OpcodeCollision = Opcodes {0} and {1} are defined with the same value ({2}).
-EventSource_IllegalTaskValue = Task {0} has a value of {1} which is outside the legal range (1-65535).
-EventSource_TaskCollision = Tasks {0} and {1} are defined with the same value ({2}).
-EventSource_IllegalKeywordsValue = Keyword {0} has a value of {1} which is outside the legal range (0-0x0000080000000000).
-EventSource_KeywordCollision = Keywords {0} and {1} are defined with the same value ({2}).
-EventSource_EventChannelOutOfRange = Channel {0} has a value of {1} which is outside the legal range (16-254).
-EventSource_ChannelTypeDoesNotMatchEventChannelValue = Channel {0} does not match event channel value {1}.
-EventSource_MaxChannelExceeded = Attempt to define more than the maximum limit of 8 channels for a provider.
-EventSource_DuplicateStringKey = Multiple definitions for string "{0}".
-EventSource_EventWithAdminChannelMustHaveMessage = Event {0} specifies an Admin channel {1}. It must specify a Message property.
-EventSource_UnsupportedMessageProperty = Event {0} specifies an illegal or unsupported formatting message ("{1}").
-EventSource_AbstractMustNotDeclareKTOC = Abstract event source must not declare {0} nested type.
-EventSource_AbstractMustNotDeclareEventMethods = Abstract event source must not declare event methods ({0} with ID {1}).
-EventSource_EventMustNotBeExplicitImplementation = Event method {0} (with ID {1}) is an explicit interface method implementation. Re-write method as implicit implementation.
-EventSource_EventParametersMismatch = Event {0} was called with {1} argument(s), but it is defined with {2} parameter(s).
-EventSource_InvalidCommand = Invalid command value.
-EventSource_InvalidEventFormat = Can't specify both etw event format flags.
-EventSource_AddScalarOutOfRange = Getting out of bounds during scalar addition.
-EventSource_PinArrayOutOfRange = Pins are out of range.
-EventSource_DataDescriptorsOutOfRange = Data descriptors are out of range.
-EventSource_NotSupportedArrayOfNil = Arrays of Nil are not supported.
-EventSource_NotSupportedArrayOfBinary = Arrays of Binary are not supported.
-EventSource_NotSupportedArrayOfNullTerminatedString = Arrays of null-terminated string are not supported.
-EventSource_TooManyFields = Too many fields in structure.
-EventSource_RecursiveTypeDefinition = Recursive type definition is not supported.
-EventSource_NotSupportedEnumType = Enum type {0} underlying type {1} is not supported for serialization.
-EventSource_NonCompliantTypeError = The API supports only anonymous types or types decorated with the EventDataAttribute. Non-compliant type: {0} dataType.
-EventSource_NotSupportedNestedArraysEnums = Nested arrays/enumerables are not supported.
-EventSource_IncorrentlyAuthoredTypeInfo = Incorrectly-authored TypeInfo - a type should be serialized as one field or as one group
-EventSource_NotSupportedCustomSerializedData = Enumerables of custom-serialized data are not supported
-EventSource_StopsFollowStarts = An event with stop suffix must follow a corresponding event with a start suffix.
-EventSource_NoRelatedActivityId = EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId.
-EventSource_VarArgsParameterMismatch = The parameters to the Event method do not match the parameters to the WriteEvent method. This may cause the event to be displayed incorrectly.
-
-; ExecutionEngineException
-ExecutionEngine_InvalidAttribute = Attribute cannot have multiple definitions.
-ExecutionEngine_MissingSecurityDescriptor = Unable to retrieve security descriptor for this frame.
-
-;;ExecutionContext
-ExecutionContext_UndoFailed = Undo operation on a component context threw an exception
-ExecutionContext_ExceptionInAsyncLocalNotification = An exception was not handled in an AsyncLocal<T> notification callback.
-
-
-; FieldAccessException
-FieldAccess_InitOnly = InitOnly (aka ReadOnly) fields can only be initialized in the type/instance constructor.
-
-; FormatException
-Format_AttributeUsage = Duplicate AttributeUsageAttribute found on attribute type {0}.
-Format_Bad7BitInt32 = Too many bytes in what should have been a 7 bit encoded Int32.
-Format_BadBase = Invalid digits for the specified base.
-Format_BadBase64Char = The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.
-Format_BadBase64CharArrayLength = Invalid length for a Base-64 char array or string.
-Format_BadBoolean = String was not recognized as a valid Boolean.
-Format_BadDateTime = String was not recognized as a valid DateTime.
-Format_BadDateTimeCalendar = The DateTime represented by the string is not supported in calendar {0}.
-Format_BadDayOfWeek = String was not recognized as a valid DateTime because the day of week was incorrect.
-Format_DateOutOfRange = The DateTime represented by the string is out of range.
-Format_BadDatePattern = Could not determine the order of year, month, and date from '{0}'.
-Format_BadFormatSpecifier = Format specifier was invalid.
-Format_BadTimeSpan = String was not recognized as a valid TimeSpan.
-Format_BadQuote = Cannot find a matching quote character for the character '{0}'.
-Format_EmptyInputString = Input string was either empty or contained only whitespace.
-Format_ExtraJunkAtEnd = Additional non-parsable characters are at the end of the string.
-Format_GuidBrace = Expected {0xdddddddd, etc}.
-Format_GuidComma = Could not find a comma, or the length between the previous token and the comma was zero (i.e., '0x,'etc.).
-Format_GuidBraceAfterLastNumber = Could not find a brace, or the length between the previous token and the brace was zero (i.e., '0x,'etc.).
-Format_GuidDashes = Dashes are in the wrong position for GUID parsing.
-Format_GuidEndBrace = Could not find the ending brace.
-Format_GuidHexPrefix = Expected hex 0x in '{0}'.
-Format_GuidInvLen = Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
-Format_GuidInvalidChar = Guid string should only contain hexadecimal characters.
-Format_GuidUnrecognized = Unrecognized Guid format.
-Format_InvalidEnumFormatSpecification = Format String can be only "G", "g", "X", "x", "F", "f", "D" or "d".
-Format_InvalidGuidFormatSpecification = Format String can be only "D", "d", "N", "n", "P", "p", "B", "b", "X" or "x".
-Format_InvalidString = Input string was not in a correct format.
-Format_IndexOutOfRange = Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
-Format_UnknowDateTimeWord = The string was not recognized as a valid DateTime. There is an unknown word starting at index {0}.
-Format_NeedSingleChar = String must be exactly one character long.
-Format_NoParsibleDigits = Could not find any recognizable digits.
-Format_RepeatDateTimePattern = DateTime pattern '{0}' appears more than once with different values.
-Format_StringZeroLength = String cannot have zero length.
-Format_TwoTimeZoneSpecifiers = The String being parsed cannot contain two TimeZone specifiers.
-Format_UTCOutOfRange= The UTC representation of the date falls outside the year range 1-9999.
-Format_OffsetOutOfRange=The time zone offset must be within plus or minus 14 hours.
-Format_MissingIncompleteDate=There must be at least a partial date with a year present in the input.
-
-; IndexOutOfRangeException
-IndexOutOfRange_ArrayRankIndex = Array does not have that many dimensions.
-IndexOutOfRange_IORaceCondition = Probable I/O race condition detected while copying memory. The I/O package is not thread safe by default. In multithreaded applications, a stream must be accessed in a thread-safe way, such as a thread-safe wrapper returned by TextReader's or TextWriter's Synchronized methods. This also applies to classes like StreamWriter and StreamReader.
-IndexOutOfRange_UMSPosition = Unmanaged memory stream position was beyond the capacity of the stream.
-
-; InsufficientMemoryException
-InsufficientMemory_MemFailPoint = Insufficient available memory to meet the expected demands of an operation at this time. Please try again later.
-InsufficientMemory_MemFailPoint_TooBig = Insufficient memory to meet the expected demands of an operation, and this system is likely to never satisfy this request. If this is a 32 bit system, consider booting in 3 GB mode.
-InsufficientMemory_MemFailPoint_VAFrag = Insufficient available memory to meet the expected demands of an operation at this time, possibly due to virtual address space fragmentation. Please try again later.
-
-
-; InvalidCastException
-InvalidCast_DBNull = Object cannot be cast to DBNull.
-InvalidCast_DownCastArrayElement = At least one element in the source array could not be cast down to the destination array type.
-InvalidCast_Empty = Object cannot be cast to Empty.
-InvalidCast_FromDBNull = Object cannot be cast from DBNull to other types.
-InvalidCast_FromTo = Invalid cast from '{0}' to '{1}'.
-InvalidCast_IConvertible = Object must implement IConvertible.
-InvalidCast_OATypeMismatch = OleAut reported a type mismatch.
-InvalidCast_StoreArrayElement = Object cannot be stored in an array of this type.
-InvalidCast_CannotCoerceByRefVariant = Object cannot be coerced to the original type of the ByRef VARIANT it was obtained from.
-InvalidCast_CannotCastNullToValueType = Null object cannot be converted to a value type.
-#if FEATURE_COMINTEROP
-InvalidCast_WinRTIPropertyValueElement = Object in an IPropertyValue is of type '{0}', which cannot be converted to a '{1}'.
-InvalidCast_WinRTIPropertyValueCoersion = Object in an IPropertyValue is of type '{0}' with value '{1}', which cannot be converted to a '{2}'.
-InvalidCast_WinRTIPropertyValueArrayCoersion = Object in an IPropertyValue is of type '{0}' which cannot be convereted to a '{1}' due to array element '{2}': {3}.
-#endif // FEATURE_COMINTEROP
-
-; InvalidOperationException
-InvalidOperation_ActivationArgsAppTrustMismatch = The activation arguments and application trust for the AppDomain must correspond to the same application identity.
-InvalidOperation_AddContextFrozen = Attempted to add properties to a frozen context.
-InvalidOperation_AppDomainSandboxAPINeedsExplicitAppBase = This API requires the ApplicationBase to be specified explicitly in the AppDomainSetup parameter.
-InvalidOperation_CantCancelCtrlBreak = Applications may not prevent control-break from terminating their process.
-InvalidOperation_CalledTwice = The method cannot be called twice on the same instance.
-InvalidOperation_CollectionCorrupted = A prior operation on this collection was interrupted by an exception. Collection's state is no longer trusted.
-InvalidOperation_CriticalTransparentAreMutuallyExclusive = SecurityTransparent and SecurityCritical attributes cannot be applied to the assembly scope at the same time.
-InvalidOperation_ExceptionStateCrossAppDomain = Thread.ExceptionState cannot access an ExceptionState from a different AppDomain.
-InvalidOperation_DebuggerLaunchFailed = Debugger unable to launch.
-InvalidOperation_ApartmentStateSwitchFailed = Failed to set the specified COM apartment state.
-InvalidOperation_EmptyQueue = Queue empty.
-InvalidOperation_EmptyStack = Stack empty.
-InvalidOperation_CannotRemoveFromStackOrQueue = Removal is an invalid operation for Stack or Queue.
-InvalidOperation_EnumEnded = Enumeration already finished.
-InvalidOperation_EnumFailedVersion = Collection was modified; enumeration operation may not execute.
-InvalidOperation_EnumNotStarted = Enumeration has not started. Call MoveNext.
-InvalidOperation_EnumOpCantHappen = Enumeration has either not started or has already finished.
-InvalidOperation_ModifyRONumFmtInfo = Unable to modify a read-only NumberFormatInfo object.
-InvalidOperation_MustBeSameThread = This operation must take place on the same thread on which the object was created.
-InvalidOperation_MustRevertPrivilege = Must revert the privilege prior to attempting this operation.
-InvalidOperation_ReadOnly = Instance is read-only.
-InvalidOperation_RegRemoveSubKey = Registry key has subkeys and recursive removes are not supported by this method.
-InvalidOperation_IComparerFailed = Failed to compare two elements in the array.
-InvalidOperation_InternalState = Invalid internal state.
-InvalidOperation_DuplicatePropertyName = Another property by this name already exists.
-InvalidOperation_NotCurrentDomain = You can only define a dynamic assembly on the current AppDomain.
-InvalidOperation_ContextAlreadyFrozen = Context is already frozen.
-InvalidOperation_WriteOnce = This property has already been set and cannot be modified.
-InvalidOperation_MethodBaked = Type definition of the method is complete.
-InvalidOperation_MethodHasBody = Method already has a body.
-InvalidOperation_ModificationOfNonCanonicalAcl = This access control list is not in canonical form and therefore cannot be modified.
-InvalidOperation_Method = This method is not supported by the current object.
-InvalidOperation_NativeOverlappedReused = NativeOverlapped cannot be reused for multiple operations.
-InvalidOperation_NotADebugModule = Not a debug ModuleBuilder.
-InvalidOperation_NoMultiModuleAssembly = You cannot have more than one dynamic module in each dynamic assembly in this version of the runtime.
-InvalidOperation_OpenLocalVariableScope = Local variable scope was not properly closed.
-InvalidOperation_SetVolumeLabelFailed = Volume labels can only be set for writable local volumes.
-InvalidOperation_SetData = An additional permission should not be supplied for setting loader information.
-InvalidOperation_SetData_OnlyOnce = SetData can only be used to set the value of a given name once.
-InvalidOperation_SetData_OnlyLocationURI = SetData cannot be used to set the value for '{0}'.
-InvalidOperation_TypeHasBeenCreated = Unable to change after type has been created.
-InvalidOperation_TypeNotCreated = Type has not been created.
-InvalidOperation_NoUnderlyingTypeOnEnum = Underlying type information on enumeration is not specified.
-InvalidOperation_ResMgrBadResSet_Type = '{0}': ResourceSet derived classes must provide a constructor that takes a String file name and a constructor that takes a Stream.
-InvalidOperation_AssemblyHasBeenSaved = Assembly '{0}' has been saved.
-InvalidOperation_ModuleHasBeenSaved = Module '{0}' has been saved.
-InvalidOperation_CannotAlterAssembly = Unable to alter assembly information.
-InvalidOperation_BadTransientModuleReference = Unable to make a reference to a transient module from a non-transient module.
-InvalidOperation_BadILGeneratorUsage = ILGenerator usage is invalid.
-InvalidOperation_BadInstructionOrIndexOutOfBound = MSIL instruction is invalid or index is out of bounds.
-InvalidOperation_ShouldNotHaveMethodBody = Method body should not exist.
-InvalidOperation_EntryMethodNotDefinedInAssembly = Entry method is not defined in the same assembly.
-InvalidOperation_CantSaveTransientAssembly = Cannot save a transient assembly.
-InvalidOperation_BadResourceContainer = Unable to add resource to transient module or transient assembly.
-InvalidOperation_CantInstantiateAbstractClass = Instances of abstract classes cannot be created.
-InvalidOperation_CantInstantiateFunctionPointer = Instances of function pointers cannot be created.
-InvalidOperation_BadTypeAttributesNotAbstract = Type must be declared abstract if any of its methods are abstract.
-InvalidOperation_BadInterfaceNotAbstract = Interface must be declared abstract.
-InvalidOperation_ConstructorNotAllowedOnInterface = Interface cannot have constructors.
-InvalidOperation_BadMethodBody = Method '{0}' cannot have a method body.
-InvalidOperation_MetaDataError = Metadata operation failed.
-InvalidOperation_BadEmptyMethodBody = Method '{0}' does not have a method body.
-InvalidOperation_EndInvokeCalledMultiple = EndInvoke can only be called once for each asynchronous operation.
-InvalidOperation_EndReadCalledMultiple = EndRead can only be called once for each asynchronous operation.
-InvalidOperation_EndWriteCalledMultiple = EndWrite can only be called once for each asynchronous operation.
-InvalidOperation_AsmLoadedForReflectionOnly = Assembly has been loaded as ReflectionOnly. This API requires an assembly capable of execution.
-InvalidOperation_NoAsmName = Assembly does not have an assembly name. In order to be registered for use by COM, an assembly must have a valid assembly name.
-InvalidOperation_NoAsmCodeBase = Assembly does not have a code base.
-InvalidOperation_HandleIsNotInitialized = Handle is not initialized.
-InvalidOperation_HandleIsNotPinned = Handle is not pinned.
-InvalidOperation_SlotHasBeenFreed = LocalDataStoreSlot storage has been freed.
-InvalidOperation_GlobalsHaveBeenCreated = Type definition of the global function has been completed.
-InvalidOperation_NotAVarArgCallingConvention = Calling convention must be VarArgs.
-InvalidOperation_CannotImportGlobalFromDifferentModule = Unable to import a global method or field from a different module.
-InvalidOperation_NonStaticComRegFunction = COM register function must be static.
-InvalidOperation_NonStaticComUnRegFunction = COM unregister function must be static.
-InvalidOperation_InvalidComRegFunctionSig = COM register function must have a System.Type parameter and a void return type.
-InvalidOperation_InvalidComUnRegFunctionSig = COM unregister function must have a System.Type parameter and a void return type.
-InvalidOperation_MultipleComRegFunctions = Type '{0}' has more than one COM registration function.
-InvalidOperation_MultipleComUnRegFunctions = Type '{0}' has more than one COM unregistration function.
-InvalidOperation_MustCallInitialize = You must call Initialize on this object instance before using it.
-InvalidOperation_MustLockForReadOrWrite = Object must be locked for read or write.
-InvalidOperation_MustLockForWrite = Object must be locked for read.
-InvalidOperation_NoValue = Nullable object must have a value.
-InvalidOperation_ResourceNotStream_Name = Resource '{0}' was not a Stream - call GetObject instead.
-InvalidOperation_ResourceNotString_Name = Resource '{0}' was not a String - call GetObject instead.
-InvalidOperation_ResourceNotString_Type = Resource was of type '{0}' instead of String - call GetObject instead.
-InvalidOperation_ResourceWriterSaved = The resource writer has already been closed and cannot be edited.
-InvalidOperation_UnderlyingArrayListChanged = This range in the underlying list is invalid. A possible cause is that elements were removed.
-InvalidOperation_AnonymousCannotImpersonate = An anonymous identity cannot perform an impersonation.
-InvalidOperation_DefaultConstructorILGen = Unable to access ILGenerator on a constructor created with DefineDefaultConstructor.
-InvalidOperation_DefaultConstructorDefineBody = The method body of the default constructor cannot be changed.
-InvalidOperation_ComputerName = Computer name could not be obtained.
-InvalidOperation_MismatchedAsyncResult = The IAsyncResult object provided does not match this delegate.
-InvalidOperation_PIAMustBeStrongNamed = Primary interop assemblies must be strongly named.
-InvalidOperation_HashInsertFailed = Hashtable insert failed. Load factor too high. The most common cause is multiple threads writing to the Hashtable simultaneously.
-InvalidOperation_UnknownEnumType = Unknown enum type.
-InvalidOperation_GetVersion = OSVersion's call to GetVersionEx failed.
-InvalidOperation_DateTimeParsing = Internal Error in DateTime and Calendar operations.
-InvalidOperation_UserDomainName = UserDomainName native call failed.
-InvalidOperation_WaitOnTransparentProxy = Cannot wait on a transparent proxy.
-InvalidOperation_NoPublicAddMethod = Cannot add the event handler since no public add method exists for the event.
-InvalidOperation_NoPublicRemoveMethod = Cannot remove the event handler since no public remove method exists for the event.
-InvalidOperation_NotSupportedOnWinRTEvent = Adding or removing event handlers dynamically is not supported on WinRT events.
-InvalidOperation_ConsoleKeyAvailableOnFile = Cannot see if a key has been pressed when either application does not have a console or when console input has been redirected from a file. Try Console.In.Peek.
-InvalidOperation_ConsoleReadKeyOnFile = Cannot read keys when either application does not have a console or when console input has been redirected from a file. Try Console.Read.
-InvalidOperation_ThreadWrongThreadStart = The thread was created with a ThreadStart delegate that does not accept a parameter.
-InvalidOperation_ThreadAPIsNotSupported = Use CompressedStack.(Capture/Run) or ExecutionContext.(Capture/Run) APIs instead.
-InvalidOperation_NotNewCaptureContext = Cannot apply a context that has been marshaled across AppDomains, that was not acquired through a Capture operation or that has already been the argument to a Set call.
-InvalidOperation_NullContext = Cannot call Set on a null context
-InvalidOperation_CannotCopyUsedContext = Only newly captured contexts can be copied
-InvalidOperation_CannotUseSwitcherOtherThread = Undo operation must be performed on the thread where the corresponding context was Set.
-InvalidOperation_SwitcherCtxMismatch = The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
-InvalidOperation_CannotOverrideSetWithoutRevert = Must override both HostExecutionContextManager.SetHostExecutionContext and HostExecutionContextManager.Revert.
-InvalidOperation_CannotUseAFCOtherThread = AsyncFlowControl object must be used on the thread where it was created.
-InvalidOperation_CannotRestoreUnsupressedFlow = Cannot restore context flow when it is not suppressed.
-InvalidOperation_CannotSupressFlowMultipleTimes = Context flow is already suppressed.
-InvalidOperation_CannotUseAFCMultiple = AsyncFlowControl object can be used only once to call Undo().
-InvalidOperation_AsyncFlowCtrlCtxMismatch = AsyncFlowControl objects can be used to restore flow only on a Context that had its flow suppressed.
-InvalidOperation_TimeoutsNotSupported = Timeouts are not supported on this stream.
-InvalidOperation_Overlapped_Pack = Cannot pack a packed Overlapped again.
-InvalidOperation_OnlyValidForDS = Adding ACEs with Object Flags and Object GUIDs is only valid for directory-object ACLs.
-InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple = Either the IAsyncResult object did not come from the corresponding async method on this type, or EndRead was called multiple times with the same IAsyncResult.
-InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple = Either the IAsyncResult object did not come from the corresponding async method on this type, or EndWrite was called multiple times with the same IAsyncResult.
-InvalidOperation_WrongAsyncResultOrEndCalledMultiple = Either the IAsyncResult object did not come from the corresponding async method on this type, or the End method was called multiple times with the same IAsyncResult.
-InvalidOperation_NoSecurityDescriptor = The object does not contain a security descriptor.
-InvalidOperation_NotAllowedInReflectionOnly = The requested operation is invalid in the ReflectionOnly context.
-InvalidOperation_NotAllowedInDynamicMethod = The requested operation is invalid for DynamicMethod.
-InvalidOperation_PropertyInfoNotAvailable = This API does not support PropertyInfo tokens.
-InvalidOperation_EventInfoNotAvailable = This API does not support EventInfo tokens.
-InvalidOperation_UnexpectedWin32Error = Unexpected error when calling an operating system function. The returned error code is 0x{0:x}.
-InvalidOperation_AssertTransparentCode = Cannot perform CAS Asserts in Security Transparent methods
-InvalidOperation_NullModuleHandle = The requested operation is invalid when called on a null ModuleHandle.
-InvalidOperation_NotWithConcurrentGC = This API is not available when the concurrent GC is enabled.
-InvalidOperation_WithoutARM = This API is not available when AppDomain Resource Monitoring is not turned on.
-InvalidOperation_NotGenericType = This operation is only valid on generic types.
-InvalidOperation_TypeCannotBeBoxed = The given type cannot be boxed.
-InvalidOperation_HostModifiedSecurityState = The security state of an AppDomain was modified by an AppDomainManager configured with the NoSecurityChanges flag.
-InvalidOperation_StrongNameKeyPairRequired = A strong name key pair is required to emit a strong-named dynamic assembly.
-#if FEATURE_COMINTEROP
-InvalidOperation_EventTokenTableRequiresDelegate = Type '{0}' is not a delegate type. EventTokenTable may only be used with delegate types.
-#endif // FEATURE_COMINTEROP
-InvalidOperation_NullArray = The underlying array is null.
-;system.security.claims
-InvalidOperation_ClaimCannotBeRemoved = The Claim '{0}' was not able to be removed. It is either not part of this Identity or it is a claim that is owned by the Principal that contains this Identity. For example, the Principal will own the claim when creating a GenericPrincipal with roles. The roles will be exposed through the Identity that is passed in the constructor, but not actually owned by the Identity. Similar logic exists for a RolePrincipal.
-InvalidOperationException_ActorGraphCircular = Actor cannot be set so that circular directed graph will exist chaining the subjects together.
-InvalidOperation_AsyncIOInProgress = The stream is currently in use by a previous operation on the stream.
-InvalidOperation_APIInvalidForCurrentContext = The API '{0}' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information.
-
-; InvalidProgramException
-InvalidProgram_Default = Common Language Runtime detected an invalid program.
-
-; Isolated Storage
-#if FEATURE_ISOSTORE
-IsolatedStorage_AssemblyMissingIdentity = Unable to determine assembly of the caller.
-IsolatedStorage_ApplicationMissingIdentity = Unable to determine application identity of the caller.
-IsolatedStorage_DomainMissingIdentity = Unable to determine domain of the caller.
-IsolatedStorage_AssemblyGrantSet = Unable to determine granted permission for assembly.
-IsolatedStorage_DomainGrantSet = Unable to determine granted permission for domain.
-IsolatedStorage_ApplicationGrantSet = Unable to determine granted permission for application.
-IsolatedStorage_Init = Initialization failed.
-IsolatedStorage_ApplicationNoEvidence = Unable to determine identity of application.
-IsolatedStorage_AssemblyNoEvidence = Unable to determine identity of assembly.
-IsolatedStorage_DomainNoEvidence = Unable to determine the identity of domain.
-IsolatedStorage_DeleteDirectories = Unable to delete; directory or files in the directory could be in use.
-IsolatedStorage_DeleteFile = Unable to delete file.
-IsolatedStorage_CreateDirectory = Unable to create directory.
-IsolatedStorage_DeleteDirectory = Unable to delete, directory not empty or does not exist.
-IsolatedStorage_Operation_ISFS = Operation not permitted on IsolatedStorageFileStream.
-IsolatedStorage_Operation = Operation not permitted.
-IsolatedStorage_Path = Path must be a valid file name.
-IsolatedStorage_FileOpenMode = Invalid mode, see System.IO.FileMode.
-IsolatedStorage_SeekOrigin = Invalid origin, see System.IO.SeekOrigin.
-IsolatedStorage_Scope_U_R_M = Invalid scope, expected User, User|Roaming or Machine.
-IsolatedStorage_Scope_Invalid = Invalid scope.
-IsolatedStorage_Exception = An error occurred while accessing IsolatedStorage.
-IsolatedStorage_QuotaIsUndefined = {0} is not defined for this store. An operation was performed that requires access to {0}. Stores obtained using enumeration APIs do not have a well-defined {0}, since partial evidence is used to open the store.
-IsolatedStorage_CurrentSizeUndefined = Current size cannot be determined for this store.
-IsolatedStorage_DomainUndefined = Domain cannot be determined on an Assembly or Application store.
-IsolatedStorage_ApplicationUndefined = Application cannot be determined on an Assembly or Domain store.
-IsolatedStorage_AssemblyUndefined = Assembly cannot be determined for an Application store.
-IsolatedStorage_StoreNotOpen = Store must be open for this operation.
-IsolatedStorage_OldQuotaLarger = The new quota must be larger than the old quota.
-IsolatedStorage_UsageWillExceedQuota = There is not enough free space to perform the operation.
-IsolatedStorage_NotValidOnDesktop = The Site scope is currently not supported.
-IsolatedStorage_OnlyIncreaseUserApplicationStore = Increasing the quota of this scope is not supported. Only the user application scope’s quota can be increased.
-#endif // FEATURE_ISOSTORE
-
-; Verification Exception
-Verification_Exception = Operation could destabilize the runtime.
-
-; IL stub marshaler exceptions
-Marshaler_StringTooLong = Marshaler restriction: Excessively long string.
-
-; Missing (General)
-MissingConstructor_Name = Constructor on type '{0}' not found.
-MissingField = Field not found.
-MissingField_Name = Field '{0}' not found.
-MissingMember = Member not found.
-MissingMember_Name = Member '{0}' not found.
-MissingMethod_Name = Method '{0}' not found.
-MissingModule = Module '{0}' not found.
-MissingType = Type '{0}' not found.
-
-; MissingManifestResourceException
-Arg_MissingManifestResourceException = Unable to find manifest resource.
-MissingManifestResource_LooselyLinked = Could not find a manifest resource entry called "{0}" in assembly "{1}". Please check spelling, capitalization, and build rules to ensure "{0}" is being linked into the assembly.
-MissingManifestResource_NoNeutralAsm = Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "{0}" was correctly embedded or linked into assembly "{1}" at compile time, or that all the satellite assemblies required are loadable and fully signed.
-MissingManifestResource_NoNeutralDisk = Could not find any resources appropriate for the specified culture (or the neutral culture) on disk.
-MissingManifestResource_MultipleBlobs = A case-insensitive lookup for resource file "{0}" in assembly "{1}" found multiple entries. Remove the duplicates or specify the exact case.
-MissingManifestResource_ResWFileNotLoaded = Unable to load resources for resource file "{0}" in package "{1}".
-MissingManifestResource_NoPRIresources = Unable to open Package Resource Index.
-
-; MissingMember
-MissingMemberTypeRef = FieldInfo does not match the target Type.
-MissingMemberNestErr = TypedReference can only be made on nested value Types.
-
-; MissingSatelliteAssemblyException
-MissingSatelliteAssembly_Default = Resource lookup fell back to the ultimate fallback resources in a satellite assembly, but that satellite either was not found or could not be loaded. Please consider reinstalling or repairing the application.
-MissingSatelliteAssembly_Culture_Name = The satellite assembly named "{1}" for fallback culture "{0}" either could not be found or could not be loaded. This is generally a setup problem. Please consider reinstalling or repairing the application.
-
-; MulticastNotSupportedException
-Multicast_Combine = Delegates that are not of type MulticastDelegate may not be combined.
-
-; NotImplementedException
-Arg_NotImplementedException = The method or operation is not implemented.
-NotImplemented_ResourcesLongerThan2^63 = Resource files longer than 2^63 bytes are not currently implemented.
-
-; NotSupportedException
-NotSupported_NYI = This feature is not currently implemented.
-NotSupported_AbstractNonCLS = This non-CLS method is not implemented.
-NotSupported_ChangeType = ChangeType operation is not supported.
-NotSupported_ByRefLike = Cannot create boxed ByRef-like values.
-NotSupported_ByRefLike[] = Cannot create arrays of ByRef-like values.
-NotSupported_OpenType = Cannot create arrays of open type.
-NotSupported_DBNullSerial = Only one DBNull instance may exist, and calls to DBNull deserialization methods are not allowed.
-NotSupported_DelegateSerHolderSerial = DelegateSerializationHolder objects are designed to represent a delegate during serialization and are not serializable themselves.
-NotSupported_DelegateCreationFromPT = Application code cannot use Activator.CreateInstance to create types that derive from System.Delegate. Delegate.CreateDelegate can be used instead.
-NotSupported_EncryptionNeedsNTFS = File encryption support only works on NTFS partitions.
-NotSupported_FileStreamOnNonFiles = FileStream was asked to open a device that was not a file. For support for devices like 'com1:' or 'lpt1:', call CreateFile, then use the FileStream constructors that take an OS handle as an IntPtr.
-NotSupported_FixedSizeCollection = Collection was of a fixed size.
-NotSupported_KeyCollectionSet = Mutating a key collection derived from a dictionary is not allowed.
-NotSupported_ValueCollectionSet = Mutating a value collection derived from a dictionary is not allowed.
-NotSupported_MemStreamNotExpandable = Memory stream is not expandable.
-NotSupported_ObsoleteResourcesFile = Found an obsolete .resources file in assembly '{0}'. Rebuild that .resources file then rebuild that assembly.
-NotSupported_OleAutBadVarType = The given Variant type is not supported by this OleAut function.
-NotSupported_PopulateData = This Surrogate does not support PopulateData().
-NotSupported_ReadOnlyCollection = Collection is read-only.
-NotSupported_RangeCollection = The specified operation is not supported on Ranges.
-NotSupported_SortedListNestedWrite = This operation is not supported on SortedList nested types because they require modifying the original SortedList.
-NotSupported_SubclassOverride = Derived classes must provide an implementation.
-NotSupported_TypeCannotDeserialized = Direct deserialization of type '{0}' is not supported.
-NotSupported_UnreadableStream = Stream does not support reading.
-NotSupported_UnseekableStream = Stream does not support seeking.
-NotSupported_UnwritableStream = Stream does not support writing.
-NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed = Cannot write to a BufferedStream while the read buffer is not empty if the underlying stream is not seekable. Ensure that the stream underlying this BufferedStream can seek or avoid interleaving read and write operations on this BufferedStream.
-NotSupported_Method = Method is not supported.
-NotSupported_Constructor = Object cannot be created through this constructor.
-NotSupported_DynamicModule = The invoked member is not supported in a dynamic module.
-NotSupported_TypeNotYetCreated = The invoked member is not supported before the type is created.
-NotSupported_SymbolMethod = Not supported in an array method of a type definition that is not complete.
-NotSupported_NotDynamicModule = The MethodRental.SwapMethodBody method can only be called to swap the method body of a method in a dynamic module.
-NotSupported_DynamicAssembly = The invoked member is not supported in a dynamic assembly.
-NotSupported_NotAllTypesAreBaked = Type '{0}' was not completed.
-NotSupported_CannotSaveModuleIndividually = Unable to save a ModuleBuilder if it was created underneath an AssemblyBuilder. Call Save on the AssemblyBuilder instead.
-NotSupported_MaxWaitHandles = The number of WaitHandles must be less than or equal to 64.
-NotSupported_IllegalOneByteBranch = Illegal one-byte branch at position: {0}. Requested branch was: {1}.
-NotSupported_OutputStreamUsingTypeBuilder = Output streams do not support TypeBuilders.
-NotSupported_ValueClassCM = Custom marshalers for value types are not currently supported.
-NotSupported_Void[] = Arrays of System.Void are not supported.
-NotSupported_NoParentDefaultConstructor = Parent does not have a default constructor. The default constructor must be explicitly defined.
-NotSupported_NonReflectedType = Not supported in a non-reflected type.
-NotSupported_GlobalFunctionNotBaked = The type definition of the global function is not completed.
-NotSupported_SecurityPermissionUnion = Union is not implemented.
-NotSupported_UnitySerHolder = The UnitySerializationHolder object is designed to transmit information about other types and is not serializable itself.
-NotSupported_UnknownTypeCode = TypeCode '{0}' was not valid.
-NotSupported_WaitAllSTAThread = WaitAll for multiple handles on a STA thread is not supported.
-NotSupported_SignalAndWaitSTAThread = SignalAndWait on a STA thread is not supported.
-NotSupported_CreateInstanceWithTypeBuilder = CreateInstance cannot be used with an object of type TypeBuilder.
-NotSupported_NonUrlAttrOnMBR = UrlAttribute is the only attribute supported for MarshalByRefObject.
-NotSupported_ActivAttrOnNonMBR = Activation Attributes are not supported for types not deriving from MarshalByRefObject.
-NotSupported_ActivAttr = Activation Attributes are not supported.
-NotSupported_ActivForCom = Activation Attributes not supported for COM Objects.
-NotSupported_NoCodepageData = No data is available for encoding {0}. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
-NotSupported_CodePage50229 = The ISO-2022-CN Encoding (Code page 50229) is not supported.
-NotSupported_DynamicAssemblyNoRunAccess = Cannot execute code on a dynamic assembly without run access.
-NotSupported_IDispInvokeDefaultMemberWithNamedArgs = Invoking default method with named arguments is not supported.
-NotSupported_Type = Type is not supported.
-NotSupported_GetMethod = The 'get' method is not supported on this property.
-NotSupported_SetMethod = The 'set' method is not supported on this property.
-NotSupported_DeclarativeUnion = Declarative unionizing of these permissions is not supported.
-NotSupported_StringComparison = The string comparison type passed in is currently not supported.
-NotSupported_WrongResourceReader_Type = This .resources file should not be read with this reader. The resource reader type is "{0}".
-NotSupported_MustBeModuleBuilder = Module argument must be a ModuleBuilder.
-NotSupported_CallToVarArg = Vararg calling convention not supported.
-NotSupported_TooManyArgs = Stack size too deep. Possibly too many arguments.
-NotSupported_DeclSecVarArg = Assert, Deny, and PermitOnly are not supported on methods with a Vararg calling convention.
-NotSupported_AmbiguousIdentity = The operation is ambiguous because the permission represents multiple identities.
-NotSupported_DynamicMethodFlags = Wrong MethodAttributes or CallingConventions for DynamicMethod. Only public, static, standard supported
-NotSupported_GlobalMethodSerialization = Serialization of global methods (including implicit serialization via the use of asynchronous delegates) is not supported.
-NotSupported_InComparableType = A type must implement IComparable<T> or IComparable to support comparison.
-NotSupported_ManagedActivation = Cannot create uninitialized instances of types requiring managed activation.
-NotSupported_ByRefReturn = ByRef return value not supported in reflection invocation.
-NotSupported_DelegateMarshalToWrongDomain = Delegates cannot be marshaled from native code into a domain other than their home domain.
-NotSupported_ResourceObjectSerialization = Cannot read resources that depend on serialization.
-NotSupported_One = The arithmetic type '{0}' cannot represent the number one.
-NotSupported_Zero = The arithmetic type '{0}' cannot represent the number zero.
-NotSupported_MaxValue = The arithmetic type '{0}' does not have a maximum value.
-NotSupported_MinValue = The arithmetic type '{0}' does not have a minimum value.
-NotSupported_PositiveInfinity = The arithmetic type '{0}' cannot represent positive infinity.
-NotSupported_NegativeInfinity = The arithmetic type '{0}' cannot represent negative infinity.
-NotSupported_UmsSafeBuffer = This operation is not supported for an UnmanagedMemoryStream created from a SafeBuffer.
-NotSupported_Reading = Accessor does not support reading.
-NotSupported_Writing = Accessor does not support writing.
-NotSupported_UnsafePointer = This accessor was created with a SafeBuffer; use the SafeBuffer to gain access to the pointer.
-NotSupported_CollectibleCOM = COM Interop is not supported for collectible types.
-NotSupported_CollectibleAssemblyResolve = Resolving to a collectible assembly is not supported.
-NotSupported_CollectibleBoundNonCollectible = A non-collectible assembly may not reference a collectible assembly.
-NotSupported_CollectibleDelegateMarshal = Delegate marshaling for types within collectible assemblies is not supported.
-NotSupported_NonStaticMethod = Non-static methods with NativeCallableAttribute are not supported.
-NotSupported_NativeCallableTarget = Methods with NativeCallableAttribute cannot be used as delegate target.
-NotSupported_GenericMethod = Generic methods with NativeCallableAttribute are not supported.
-NotSupported_NonBlittableTypes = Non-blittable parameter types are not supported for NativeCallable methods.
-
-NotSupported_UserDllImport = DllImport cannot be used on user-defined methods.
-NotSupported_UserCOM = COM Interop is not supported for user-defined types.
-
-#if FEATURE_APPX
-NotSupported_AppX = {0} is not supported in AppX.
-LoadOfFxAssemblyNotSupported_AppX = {0} of .NET Framework assemblies is not supported in AppX.
-#endif
-#if FEATURE_COMINTEROP
-NotSupported_WinRT_PartialTrust = Windows Runtime is not supported in partial trust.
-#endif // FEATURE_COMINTEROP
-; ReflectionTypeLoadException
-ReflectionTypeLoad_LoadFailed = Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
-#if FEATURE_COMINTEROP
-NotSupported_PIAInAppxProcess = A Primary Interop Assembly is not supported in AppX.
-#endif
-NotSupported_AssemblyLoadCodeBase = Assembly.Load with a Codebase is not supported.
-NotSupported_AssemblyLoadFromHash = Assembly.LoadFrom with hashValue is not supported.
-NotSupported_CannotCallEqualsOnSpan = Equals() on Span and ReadOnlySpan is not supported. Use operator== instead.
-NotSupported_CannotCallGetHashCodeOnSpan = GetHashCode() on Span and ReadOnlySpan is not supported.
-NotSupported_ReflectionOnlyLoad = Assembly.ReflectionOnlyLoad is not supported.
-NotSupported_ReflectionOnlyGetType = Type.ReflectionOnlyGetType is not supported.
-
-; TypeLoadException
-TypeLoad_ResolveType = Could not resolve type '{0}'.
-TypeLoad_ResolveTypeFromAssembly = Could not resolve type '{0}' in assembly '{1}'.
-TypeLoad_ResolveNestedType = Could not resolve nested type '{0}' in type "{1}'.
-FileNotFound_ResolveAssembly = Could not resolve assembly '{0}'.
-
-; NullReferenceException
-NullReference_This = The pointer for this method was null.
-
-; ObjectDisposedException
-ObjectDisposed_Generic = Cannot access a disposed object.
-ObjectDisposed_FileClosed = Cannot access a closed file.
-ObjectDisposed_ObjectName_Name = Object name: '{0}'.
-ObjectDisposed_ReaderClosed = Cannot read from a closed TextReader.
-ObjectDisposed_ResourceSet = Cannot access a closed resource set.
-ObjectDisposed_RegKeyClosed = Cannot access a closed registry key.
-ObjectDisposed_StreamClosed = Cannot access a closed Stream.
-ObjectDisposed_WriterClosed = Cannot write to a closed TextWriter.
-ObjectDisposed_ViewAccessorClosed = Cannot access a closed accessor.
-
-; OperationCanceledException
-OperationCanceled = The operation was canceled.
-
-; OutOfMemoryException
-OutOfMemory_GCHandleMDA = The GCHandle MDA has run out of available cookies.
-
-; OverflowException
-Overflow_Byte = Value was either too large or too small for an unsigned byte.
-Overflow_Char = Value was either too large or too small for a character.
-Overflow_Currency = Value was either too large or too small for a Currency.
-Overflow_Decimal = Value was either too large or too small for a Decimal.
-Overflow_Int16 = Value was either too large or too small for an Int16.
-Overflow_Int32 = Value was either too large or too small for an Int32.
-Overflow_Int64 = Value was either too large or too small for an Int64.
-Overflow_NegateTwosCompNum = Negating the minimum value of a twos complement number is invalid.
-Overflow_NegativeUnsigned = The string was being parsed as an unsigned number and could not have a negative sign.
-Overflow_SByte = Value was either too large or too small for a signed byte.
-Overflow_Single = Value was either too large or too small for a Single.
-Overflow_Double = Value was either too large or too small for a Double.
-Overflow_TimeSpanTooLong = TimeSpan overflowed because the duration is too long.
-Overflow_TimeSpanElementTooLarge = The TimeSpan could not be parsed because at least one of the numeric components is out of range or contains too many digits.
-Overflow_Duration = The duration cannot be returned for TimeSpan.MinValue because the absolute value of TimeSpan.MinValue exceeds the value of TimeSpan.MaxValue.
-Overflow_UInt16 = Value was either too large or too small for a UInt16.
-Overflow_UInt32 = Value was either too large or too small for a UInt32.
-Overflow_UInt64 = Value was either too large or too small for a UInt64.
-
-; PlatformNotsupportedException
-PlatformNotSupported_RequiresLonghorn = This operation is only supported on Windows Vista and above.
-PlatformNotSupported_RequiresNT = This operation is only supported on Windows 2000, Windows XP, and higher.
-PlatformNotSupported_RequiresW2kSP3 = This operation is only supported on Windows 2000 SP3 or later operating systems.
-#if FEATURE_COMINTEROP
-PlatformNotSupported_WinRT = Windows Runtime is not supported on this operating system.
-#endif // FEATURE_COMINTEROP
-
-; PolicyException
-; This still appears in bcl.small but should go away eventually
-Policy_Default = Error occurred while performing a policy operation.
-Policy_CannotLoadSemiTrustAssembliesDuringInit = All assemblies loaded as part of AppDomain initialization must be fully trusted.
-Policy_SaveNotFileBased = PolicyLevel object not based on a file cannot be saved.
-Policy_AppTrustMustGrantAppRequest = ApplicationTrust grant set does not contain ActivationContext's minimum request set.
-
-Error_SecurityPolicyFileParse = Error occurred while parsing the '{0}' policy level. The default policy level was used instead.
-Error_SecurityPolicyFileParseEx = Error '{1}' occurred while parsing the '{0}' policy level. The default policy level was used instead.
-
-; RankException
-Rank_MultiDimNotSupported = Only single dimension arrays are supported here.
-Rank_MustMatch = The specified arrays must have the same number of dimensions.
-
-; TypeInitializationException
-TypeInitialization_Default = Type constructor threw an exception.
-TypeInitialization_Type = The type initializer for '{0}' threw an exception.
-
-; TypeLoadException
-
-
-;
-; Reflection exceptions
-;
-RtType.InvalidCaller = Caller is not a friend.
-
-;CustomAttributeFormatException
-RFLCT.InvalidPropFail = '{0}' property specified was not found.
-RFLCT.InvalidFieldFail = '{0}' field specified was not found.
-
-;InvalidFilterCriteriaException
-RFLCT.FltCritString = A String must be provided for the filter criteria.
-RFLCT.FltCritInt = An Int32 must be provided for the filter criteria.
-
-; TargetException
-RFLCT.Targ_ITargMismatch = Object does not match target type.
-RFLCT.Targ_StatMethReqTarg = Non-static method requires a target.
-RFLCT.Targ_StatFldReqTarg = Non-static field requires a target.
-
-;AmbiguousMatchException
-RFLCT.Ambiguous = Ambiguous match found.
-RFLCT.AmbigCust = Multiple custom attributes of the same type found.
-
-;
-; Remoting exceptions
-;
-Remoting_AppDomainUnloaded_ThreadUnwound = The application domain in which the thread was running has been unloaded.
-Remoting_AppDomainUnloaded = The target application domain has been unloaded.
-Remoting_CantRemotePointerType = Pointer types cannot be passed in a remote call.
-Remoting_TypeCantBeRemoted = The given type cannot be passed in a remote call.
-Remoting_Delegate_TooManyTargets = The delegate must have only one target.
-Remoting_InvalidContext = The context is not valid.
-Remoting_InvalidValueTypeFieldAccess = An attempt was made to calculate the address of a value type field on a remote object. This was likely caused by an attempt to directly get or set the value of a field within this embedded value type. Avoid this and instead provide and use access methods for each field in the object that will be accessed remotely.
-Remoting_Message_BadRetValOrOutArg = Bad return value or out-argument inside the return message.
-Remoting_NonPublicOrStaticCantBeCalledRemotely = Permission denied: cannot call non-public or static methods remotely.
-Remoting_Proxy_ProxyTypeIsNotMBR = classToProxy argument must derive from MarshalByRef type.
-Remoting_TP_NonNull = The transparent proxy field of a real proxy must be null.
-
-; Resources exceptions
-;
-Resources_StreamNotValid = Stream is not a valid resource file.
-ResourceReaderIsClosed = ResourceReader is closed.
-
-; RuntimeWrappedException
-RuntimeWrappedException = An object that does not derive from System.Exception has been wrapped in a RuntimeWrappedException.
-
-; UnauthorizedAccessException
-UnauthorizedAccess_MemStreamBuffer = MemoryStream's internal buffer cannot be accessed.
-UnauthorizedAccess_IODenied_Path = Access to the path '{0}' is denied.
-UnauthorizedAccess_IODenied_NoPathName = Access to the path is denied.
-UnauthorizedAccess_RegistryKeyGeneric_Key = Access to the registry key '{0}' is denied.
-UnauthorizedAccess_RegistryNoWrite = Cannot write to the registry key.
-UnauthorizedAccess_SystemDomain = Cannot execute an assembly in the system domain.
-
-;
-; Security exceptions
-;
-
-;SecurityException
-; These still appear in bcl.small but should go away eventually
-Security_Generic = Request for the permission of type '{0}' failed.
-Security_GenericNoType = Request failed.
-Security_NoAPTCA = That assembly does not allow partially trusted callers.
-Security_RegistryPermission = Requested registry access is not allowed.
-Security_MustRevertOverride = Stack walk modifier must be reverted before another modification of the same type can be performed.
-
-;
-; HostProtection exceptions
-;
-
-HostProtection_HostProtection = Attempted to perform an operation that was forbidden by the CLR host.
-HostProtection_ProtectedResources = The protected resources (only available with full trust) were:
-HostProtection_DemandedResources = The demanded resources were:
-
-;
-; IO exceptions
-;
-
-; EOFException
-IO.EOF_ReadBeyondEOF = Unable to read beyond the end of the stream.
-
-; FileNotFoundException
-IO.FileNotFound = Unable to find the specified file.
-IO.FileNotFound_FileName = Could not find file '{0}'.
-IO.FileName_Name = File name: '{0}'
-IO.FileLoad = Could not load the specified file.
-
-; IOException
-IO.IO_AlreadyExists_Name = Cannot create "{0}" because a file or directory with the same name already exists.
-IO.IO_BindHandleFailed = BindHandle for ThreadPool failed on this handle.
-IO.IO_FileExists_Name = The file '{0}' already exists.
-IO.IO_FileStreamHandlePosition = The OS handle's position is not what FileStream expected. Do not use a handle simultaneously in one FileStream and in Win32 code or another FileStream. This may cause data loss.
-IO.IO_FileTooLong2GB = The file is too long. This operation is currently limited to supporting files less than 2 gigabytes in size.
-IO.IO_FileTooLongOrHandleNotSync = IO operation will not work. Most likely the file will become too long or the handle was not opened to support synchronous IO operations.
-IO.IO_FixedCapacity = Unable to expand length of this stream beyond its capacity.
-IO.IO_InvalidStringLen_Len = BinaryReader encountered an invalid string length of {0} characters.
-IO.IO_NoConsole = There is no console.
-IO.IO_NoPermissionToDirectoryName = <Path discovery permission to the specified directory was denied.>
-IO.IO_SeekBeforeBegin = An attempt was made to move the position before the beginning of the stream.
-IO.IO_SeekAppendOverwrite = Unable seek backward to overwrite data that previously existed in a file opened in Append mode.
-IO.IO_SetLengthAppendTruncate = Unable to truncate data that previously existed in a file opened in Append mode.
-IO.IO_SharingViolation_File = The process cannot access the file '{0}' because it is being used by another process.
-IO.IO_SharingViolation_NoFileName = The process cannot access the file because it is being used by another process.
-IO.IO_StreamTooLong = Stream was too long.
-IO.IO_CannotCreateDirectory = The specified directory '{0}' cannot be created.
-IO.IO_SourceDestMustBeDifferent = Source and destination path must be different.
-IO.IO_SourceDestMustHaveSameRoot = Source and destination path must have identical roots. Move will not work across volumes.
-
-; DirectoryNotFoundException
-IO.DriveNotFound_Drive = Could not find the drive '{0}'. The drive might not be ready or might not be mapped.
-IO.PathNotFound_Path = Could not find a part of the path '{0}'.
-IO.PathNotFound_NoPathName = Could not find a part of the path.
-
-; PathTooLongException
-IO.PathTooLong = The specified file name or path is too long, or a component of the specified path is too long.
-
-; SecurityException
-FileSecurityState_OperationNotPermitted = File operation not permitted. Access to path '{0}' is denied.
-
-; PrivilegeNotHeldException
-PrivilegeNotHeld_Default = The process does not possess some privilege required for this operation.
-PrivilegeNotHeld_Named = The process does not possess the '{0}' privilege which is required for this operation.
-
-; General strings used in the IO package
-IO_UnknownFileName = [Unknown]
-IO_StreamWriterBufferedDataLost = A StreamWriter was not closed and all buffered data within that StreamWriter was not flushed to the underlying stream. (This was detected when the StreamWriter was finalized with data in its buffer.) A portion of the data was lost. Consider one of calling Close(), Flush(), setting the StreamWriter's AutoFlush property to true, or allocating the StreamWriter with a "using" statement. Stream type: {0}\r\nFile name: {1}\r\nAllocated from:\r\n {2}
-IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled = callstack information is not captured by default for performance reasons. Please enable captureAllocatedCallStack config switch for streamWriterBufferedDataLost MDA (refer to MSDN MDA documentation for how to do this).
-
-;
-; Serialization Exceptions
-;
-; SerializationException
-Serialization_InvalidData=An error occurred while deserializing the object. The serialized data is corrupt.
-Serialization_InvalidPtrValue = An IntPtr or UIntPtr with an eight byte value cannot be deserialized on a machine with a four byte word size.
-Serialization_MemberTypeNotRecognized = Unknown member type.
-Serialization_InsufficientState = Insufficient state to return the real object.
-Serialization_InvalidFieldState = Object fields may not be properly initialized.
-Serialization_MissField = Field {0} is missing.
-Serialization_NullSignature = The method signature cannot be null.
-Serialization_UnknownMember = Cannot get the member '{0}'.
-Serialization_InsufficientDeserializationState = Insufficient state to deserialize the object. Missing field '{0}'. More information is needed.
-Serialization_UnableToFindModule = The given module {0} cannot be found within the assembly {1}.
-Serialization_InvalidOnDeser = OnDeserialization method was called while the object was not being deserialized.
-Serialization_MissingKeys = The Keys for this Hashtable are missing.
-Serialization_MissingValues = The values for this dictionary are missing.
-Serialization_NullKey = One of the serialized keys is null.
-Serialization_KeyValueDifferentSizes = The keys and values arrays have different sizes.
-Serialization_SameNameTwice = Cannot add the same member twice to a SerializationInfo object.
-Serialization_BadParameterInfo = Non existent ParameterInfo. Position bigger than member's parameters length.
-Serialization_NoParameterInfo = Serialized member does not have a ParameterInfo.
-Serialization_NotFound = Member '{0}' was not found.
-Serialization_StringBuilderMaxCapacity = The serialized MaxCapacity property of StringBuilder must be positive and greater than or equal to the String length.
-Serialization_StringBuilderCapacity = The serialized Capacity property of StringBuilder must be positive, less than or equal to MaxCapacity and greater than or equal to the String length.
-Serialization_InvalidDelegateType = Cannot serialize delegates over unmanaged function pointers, dynamic methods or methods outside the delegate creator's assembly.
-Serialization_OptionalFieldVersionValue = Version value must be positive.
-Serialization_MissingDateTimeData = Invalid serialized DateTime data. Unable to find 'ticks' or 'dateData'.
-Serialization_DateTimeTicksOutOfRange = Invalid serialized DateTime data. Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
-; The following serialization exception messages appear in native resources too (mscorrc.rc)
-Serialization_MemberOutOfRange = The deserialized value of the member "{0}" in the class "{1}" is out of range.
-
-#if FEATURE_SERIALIZATION
-Serialization_NoID = Object has never been assigned an objectID.
-Serialization_UnknownMemberInfo = Only FieldInfo, PropertyInfo, and SerializationMemberInfo are recognized.
-Serialization_UnableToFixup = Cannot perform fixup.
-Serialization_NoType = Object does not specify a type.
-Serialization_ValueTypeFixup = ValueType fixup on Arrays is not implemented.
-Serialization_PartialValueTypeFixup = Fixing up a partially available ValueType chain is not implemented.
-Serialization_InvalidID = Object specifies an invalid ID.
-Serialization_DuplicateSelector = Selector is already on the list of checked selectors.
-Serialization_NoBaseType = Object does not specify a base type.
-Serialization_ArrayNoLength = Array does not specify a length.
-Serialization_CannotGetType = Cannot get the type '{0}'.
-Serialization_AssemblyNotFound = Unable to find assembly '{0}'.
-Serialization_ArrayInvalidLength = Array specifies an invalid length.
-Serialization_MalformedArray = The array information in the stream is invalid.
-Serialization_MultipleMembers = Cannot resolve multiple members with the same name.
-Serialization_ObjectUsedBeforeDeserCallback = An object was used before its deserialization callback ran, which may break higher-level consistency guarantees in the application.
-Serialization_RegisterTwice = An object cannot be registered twice.
-Serialization_IdTooSmall = Object IDs must be greater than zero.
-Serialization_TooManyReferences = The implementation of the IObjectReference interface returns too many nested references to other objects that implement IObjectReference.
-Serialization_NotISer = The given object does not implement the ISerializable interface.
-Serialization_MissingKeyValuePairs = The KeyValuePairs for this Dictionary are missing.
-Serialization_SurrogateCycleInArgument = Selector contained a cycle.
-Serialization_SurrogateCycle = Adding selector will introduce a cycle.
-Serialization_NeverSeen = A fixup is registered to the object with ID {0}, but the object does not appear in the graph.
-Serialization_IORIncomplete = The object with ID {0} implements the IObjectReference interface for which all dependencies cannot be resolved. The likely cause is two instances of IObjectReference that have a mutual dependency on each other.
-Serialization_NotCyclicallyReferenceableSurrogate = {0}.SetObjectData returns a value that is neither null nor equal to the first parameter. Such Surrogates cannot be part of cyclical reference.
-Serialization_ObjectNotSupplied = The object with ID {0} was referenced in a fixup but does not exist.
-Serialization_TooManyElements = The internal array cannot expand to greater than Int32.MaxValue elements.
-Serialization_InvalidType = Only system-provided types can be passed to the GetUninitializedObject method. '{0}' is not a valid instance of a type.
-Serialization_MissingObject = The object with ID {0} was referenced in a fixup but has not been registered.
-Serialization_InvalidFixupType = A member fixup was registered for an object which implements ISerializable or has a surrogate. In this situation, a delayed fixup must be used.
-Serialization_InvalidFixupDiscovered = A fixup on an object implementing ISerializable or having a surrogate was discovered for an object which does not have a SerializationInfo available.
-Serialization_InvalidFormat = The input stream is not a valid binary format. The starting contents (in bytes) are: {0} ...
-Serialization_ParentChildIdentical = The ID of the containing object cannot be the same as the object ID.
-Serialization_IncorrectNumberOfFixups = The ObjectManager found an invalid number of fixups. This usually indicates a problem in the Formatter.
-; The following serialization exception messages appear in native resources too (mscorrc.rc)
-Serialization_NonSerType = Type '{0}' in Assembly '{1}' is not marked as serializable.
-Serialization_ConstructorNotFound = The constructor to deserialize an object of type '{0}' was not found.
-
-; SerializationException used by Formatters
-Serialization_ArrayType = Invalid array type '{0}'.
-Serialization_ArrayTypeObject = Array element type is Object, 'dt' attribute is null.
-Serialization_Assembly = No assembly information is available for object on the wire, '{0}'.
-Serialization_AssemblyId = No assembly ID for object type '{0}'.
-Serialization_BinaryHeader = Binary stream '{0}' does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.
-Serialization_CrossAppDomainError = Cross-AppDomain BinaryFormatter error; expected '{0}' but received '{1}'.
-Serialization_CorruptedStream = Invalid BinaryFormatter stream.
-Serialization_HeaderReflection = Header reflection error: number of value members: {0}.
-Serialization_ISerializableTypes = Types not available for ISerializable object '{0}'.
-Serialization_ISerializableMemberInfo = MemberInfo requested for ISerializable type.
-Serialization_MBRAsMBV = Type {0} must be marshaled by reference in this context.
-Serialization_Map = No map for object '{0}'.
-Serialization_MemberInfo = MemberInfo cannot be obtained for ISerialized Object '{0}'.
-Serialization_Method = Invalid MethodCall or MethodReturn stream format.
-Serialization_MissingMember = Member '{0}' in class '{1}' is not present in the serialized stream and is not marked with {2}.
-Serialization_NoMemberInfo = No MemberInfo for Object {0}.
-Serialization_ObjNoID = Object {0} has never been assigned an objectID.
-Serialization_ObjectTypeEnum = Invalid ObjectTypeEnum {0}.
-Serialization_ParseError = Parse error. Current element is not compatible with the next element, {0}.
-Serialization_SerMemberInfo = MemberInfo type {0} cannot be serialized.
-Serialization_Stream = Attempting to deserialize an empty stream.
-Serialization_StreamEnd = End of Stream encountered before parsing was completed.
-Serialization_TopObject = No top object.
-Serialization_TopObjectInstantiate = Top object cannot be instantiated for element '{0}'.
-Serialization_TypeCode = Invalid type code in stream '{0}'.
-Serialization_TypeExpected = Invalid expected type.
-Serialization_TypeMissing = Type is missing for member of type Object '{0}'.
-Serialization_TypeRead = Invalid read type request '{0}'.
-Serialization_TypeSecurity = Type {0} and the types derived from it (such as {1}) are not permitted to be deserialized at this security level.
-Serialization_TypeWrite = Invalid write type request '{0}'.
-Serialization_XMLElement = Invalid element '{0}'.
-Serialization_Security = Because of security restrictions, the type {0} cannot be accessed.
-Serialization_TypeLoadFailure = Unable to load type {0} required for deserialization.
-Serialization_RequireFullTrust = A type '{0}' that is defined in a partially trusted assembly cannot be type forwarded from an assembly with a different Public Key Token or without a public key token. To fix this, please either turn on unsafeTypeForwarding flag in the configuration file or remove the TypeForwardedFrom attribute.
-; The following serialization exception messages appear in native resources too (mscorrc.rc)
-Serialization_TypeResolved = Type is not resolved for member '{0}'.
-Serialization_MemberOutOfRange = The deserialized value of the member "{0}" in the class "{1}" is out of range.
-#endif // FEATURE_SERIALIZATION
-
-;
-; StringBuilder Exceptions
-;
-Arg_LongerThanSrcString = Source string was not long enough. Check sourceIndex and count.
-
-
-;
-; System.Threading
-;
-
-;
-; Thread Exceptions
-;
-ThreadState_NoAbortRequested = Unable to reset abort because no abort was requested.
-Threading.WaitHandleTooManyPosts = The WaitHandle cannot be signaled because it would exceed its maximum count.
-;
-; WaitHandleCannotBeOpenedException
-;
-Threading.WaitHandleCannotBeOpenedException = No handle of the given name exists.
-Threading.WaitHandleCannotBeOpenedException_InvalidHandle = A WaitHandle with system-wide name '{0}' cannot be created. A WaitHandle of a different type might have the same name.
-
-;
-; AbandonedMutexException
-;
-Threading.AbandonedMutexException = The wait completed due to an abandoned mutex.
-
-; AggregateException
-AggregateException_ctor_DefaultMessage=One or more errors occurred.
-AggregateException_ctor_InnerExceptionNull=An element of innerExceptions was null.
-AggregateException_DeserializationFailure=The serialization stream contains no inner exceptions.
-AggregateException_ToString={0}{1}---> (Inner Exception #{2}) {3}{4}{5}
-
-; Cancellation
-CancellationToken_CreateLinkedToken_TokensIsEmpty=No tokens were supplied.
-CancellationTokenSource_Disposed=The CancellationTokenSource has been disposed.
-CancellationToken_SourceDisposed=The CancellationTokenSource associated with this CancellationToken has been disposed.
-
-; Exceptions shared by all concurrent collection
-ConcurrentCollection_SyncRoot_NotSupported=The SyncRoot property may not be used for the synchronization of concurrent collections.
-
-; Exceptions shared by ConcurrentStack and ConcurrentQueue
-ConcurrentStackQueue_OnDeserialization_NoData=The serialization stream contains no elements.
-
-; ConcurrentStack<T>
-ConcurrentStack_PushPopRange_StartOutOfRange=The startIndex argument must be greater than or equal to zero.
-ConcurrentStack_PushPopRange_CountOutOfRange=The count argument must be greater than or equal to zero.
-ConcurrentStack_PushPopRange_InvalidCount=The sum of the startIndex and count arguments must be less than or equal to the collection's Count.
-
-; ConcurrentDictionary<TKey, TValue>
-ConcurrentDictionary_ItemKeyIsNull=TKey is a reference type and item.Key is null.
-ConcurrentDictionary_SourceContainsDuplicateKeys=The source argument contains duplicate keys.
-ConcurrentDictionary_IndexIsNegative=The index argument is less than zero.
-ConcurrentDictionary_ConcurrencyLevelMustBePositive=The concurrencyLevel argument must be positive.
-ConcurrentDictionary_CapacityMustNotBeNegative=The capacity argument must be greater than or equal to zero.
-ConcurrentDictionary_ArrayNotLargeEnough=The index is equal to or greater than the length of the array, or the number of elements in the dictionary is greater than the available space from index to the end of the destination array.
-ConcurrentDictionary_ArrayIncorrectType=The array is multidimensional, or the type parameter for the set cannot be cast automatically to the type of the destination array.
-ConcurrentDictionary_KeyAlreadyExisted=The key already existed in the dictionary.
-ConcurrentDictionary_TypeOfKeyIncorrect=The key was of an incorrect type for this dictionary.
-ConcurrentDictionary_TypeOfValueIncorrect=The value was of an incorrect type for this dictionary.
-
-; Partitioner
-Partitioner_DynamicPartitionsNotSupported=Dynamic partitions are not supported by this partitioner.
-
-; OrderablePartitioner
-OrderablePartitioner_GetPartitions_WrongNumberOfPartitions=GetPartitions returned an incorrect number of partitions.
-
-; PartitionerStatic
-PartitionerStatic_CurrentCalledBeforeMoveNext=MoveNext must be called at least once before calling Current.
-PartitionerStatic_CanNotCallGetEnumeratorAfterSourceHasBeenDisposed=Can not call GetEnumerator on partitions after the source enumerable is disposed
-
-; CDSCollectionETWBCLProvider events
-event_ConcurrentStack_FastPushFailed=Push to ConcurrentStack spun {0} time(s).
-event_ConcurrentStack_FastPopFailed=Pop from ConcurrentStack spun {0} time(s).
-event_ConcurrentDictionary_AcquiringAllLocks=ConcurrentDictionary acquiring all locks on {0} bucket(s).
-event_ConcurrentBag_TryTakeSteals=ConcurrentBag stealing in TryTake.
-event_ConcurrentBag_TryPeekSteals=ConcurrentBag stealing in TryPeek.
-
-; CountdownEvent
-CountdownEvent_Decrement_BelowZero=Invalid attempt made to decrement the event's count below zero.
-CountdownEvent_Increment_AlreadyZero=The event is already signaled and cannot be incremented.
-CountdownEvent_Increment_AlreadyMax=The increment operation would cause the CurrentCount to overflow.
-
-; Parallel
-Parallel_Invoke_ActionNull=One of the actions was null.
-Parallel_ForEach_OrderedPartitionerKeysNotNormalized=This method requires the use of an OrderedPartitioner with the KeysNormalized property set to true.
-Parallel_ForEach_PartitionerNotDynamic=The Partitioner used here must support dynamic partitioning.
-Parallel_ForEach_PartitionerReturnedNull=The Partitioner used here returned a null partitioner source.
-Parallel_ForEach_NullEnumerator=The Partitioner source returned a null enumerator.
-
-; Semaphore
-Argument_SemaphoreInitialMaximum=The initial count for the semaphore must be greater than or equal to zero and less than the maximum count.
-
-; SemaphoreFullException
-Threading_SemaphoreFullException=Adding the specified count to the semaphore would cause it to exceed its maximum count.
-
-; Lazy
-Lazy_ctor_ValueSelectorNull=The valueSelector argument is null.
-Lazy_ctor_InfoNull=The info argument is null.
-Lazy_ctor_deserialization_ValueInvalid=The Value cannot be null.
-Lazy_ctor_ModeInvalid=The mode argument specifies an invalid value.
-Lazy_CreateValue_NoParameterlessCtorForT=The lazily-initialized type does not have a public, parameterless constructor.
-Lazy_StaticInit_InvalidOperation=ValueFactory returned null.
-Lazy_Value_RecursiveCallsToValue=ValueFactory attempted to access the Value property of this instance.
-Lazy_ToString_ValueNotCreated=Value is not created.
-
-
-;ThreadLocal
-ThreadLocal_Value_RecursiveCallsToValue=ValueFactory attempted to access the Value property of this instance.
-ThreadLocal_Disposed=The ThreadLocal object has been disposed.
-ThreadLocal_ValuesNotAvailable=The ThreadLocal object is not tracking values. To use the Values property, use a ThreadLocal constructor that accepts the trackAllValues parameter and set the parameter to true.
-
-; SemaphoreSlim
-SemaphoreSlim_ctor_InitialCountWrong=The initialCount argument must be non-negative and less than or equal to the maximumCount.
-SemaphoreSlim_ctor_MaxCountWrong=The maximumCount argument must be a positive number. If a maximum is not required, use the constructor without a maxCount parameter.
-SemaphoreSlim_Wait_TimeoutWrong=The timeout must represent a value between -1 and Int32.MaxValue, inclusive.
-SemaphoreSlim_Release_CountWrong=The releaseCount argument must be greater than zero.
-SemaphoreSlim_Disposed=The semaphore has been disposed.
-
-; ManualResetEventSlim
-ManualResetEventSlim_ctor_SpinCountOutOfRange=The spinCount argument must be in the range 0 to {0}, inclusive.
-ManualResetEventSlim_ctor_TooManyWaiters=There are too many threads currently waiting on the event. A maximum of {0} waiting threads are supported.
-ManualResetEventSlim_Disposed=The event has been disposed.
-
-; SpinLock
-SpinLock_TryEnter_ArgumentOutOfRange=The timeout must be a value between -1 and Int32.MaxValue, inclusive.
-SpinLock_TryEnter_LockRecursionException=The calling thread already holds the lock.
-SpinLock_TryReliableEnter_ArgumentException=The tookLock argument must be set to false before calling this method.
-SpinLock_Exit_SynchronizationLockException=The calling thread does not hold the lock.
-SpinLock_IsHeldByCurrentThread=Thread tracking is disabled.
-
-; SpinWait
-SpinWait_SpinUntil_TimeoutWrong=The timeout must represent a value between -1 and Int32.MaxValue, inclusive.
-SpinWait_SpinUntil_ArgumentNull=The condition argument is null.
-
-; CdsSyncEtwBCLProvider events
-event_SpinLock_FastPathFailed=SpinLock beginning to spin.
-event_SpinWait_NextSpinWillYield=Next spin will yield.
-event_Barrier_PhaseFinished=Barrier finishing phase {1}.
-
-#if PLATFORM_UNIX
-; Unix threading
-PlatformNotSupported_NamedSynchronizationPrimitives=The named version of this synchronization primitive is not supported on this platform.
-PlatformNotSupported_NamedSyncObjectWaitAnyWaitAll=Wait operations on multiple wait handles including a named synchronization primitive are not supported on this platform.
-#endif
-
-;
-; System.Threading.Tasks
-;
-
-; AsyncMethodBuilder
-AsyncMethodBuilder_InstanceNotInitialized=The builder was not properly initialized.
-
-; TaskAwaiter and YieldAwaitable
-AwaitableAwaiter_InstanceNotInitialized=The awaitable or awaiter was not properly initialized.
-TaskAwaiter_TaskNotCompleted=The awaited task has not yet completed.
-
-; Task<T>
-TaskT_SetException_HasAnInitializer=A task's Exception may only be set directly if the task was created without a function.
-TaskT_TransitionToFinal_AlreadyCompleted=An attempt was made to transition a task to a final state when it had already completed.
-TaskT_ctor_SelfReplicating=It is invalid to specify TaskCreationOptions.SelfReplicating for a Task<TResult>.
-TaskT_DebuggerNoResult={Not yet computed}
-
-; Task
-Task_ctor_LRandSR=(Internal)An attempt was made to create a LongRunning SelfReplicating task.
-Task_ThrowIfDisposed=The task has been disposed.
-Task_Dispose_NotCompleted=A task may only be disposed if it is in a completion state (RanToCompletion, Faulted or Canceled).
-Task_Start_Promise=Start may not be called on a promise-style task.
-Task_Start_AlreadyStarted=Start may not be called on a task that was already started.
-Task_Start_TaskCompleted=Start may not be called on a task that has completed.
-Task_Start_ContinuationTask=Start may not be called on a continuation task.
-Task_RunSynchronously_AlreadyStarted=RunSynchronously may not be called on a task that was already started.
-Task_RunSynchronously_TaskCompleted=RunSynchronously may not be called on a task that has already completed.
-Task_RunSynchronously_Promise=RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.
-Task_RunSynchronously_Continuation=RunSynchronously may not be called on a continuation task.
-Task_ContinueWith_NotOnAnything=The specified TaskContinuationOptions excluded all continuation kinds.
-Task_ContinueWith_ESandLR=The specified TaskContinuationOptions combined LongRunning and ExecuteSynchronously. Synchronous continuations should not be long running.
-Task_MultiTaskContinuation_NullTask=The tasks argument included a null value.
-Task_MultiTaskContinuation_FireOptions=It is invalid to exclude specific continuation kinds for continuations off of multiple tasks.
-Task_MultiTaskContinuation_EmptyTaskList=The tasks argument contains no tasks.
-Task_FromAsync_TaskManagerShutDown=FromAsync was called with a TaskManager that had already shut down.
-Task_FromAsync_SelfReplicating=It is invalid to specify TaskCreationOptions.SelfReplicating in calls to FromAsync.
-Task_FromAsync_LongRunning=It is invalid to specify TaskCreationOptions.LongRunning in calls to FromAsync.
-Task_FromAsync_PreferFairness=It is invalid to specify TaskCreationOptions.PreferFairness in calls to FromAsync.
-Task_WaitMulti_NullTask=The tasks array included at least one null element.
-Task_Delay_InvalidMillisecondsDelay=The value needs to be either -1 (signifying an infinite timeout), 0 or a positive integer.
-Task_Delay_InvalidDelay=The value needs to translate in milliseconds to -1 (signifying an infinite timeout), 0 or a positive integer less than or equal to Int32.MaxValue.
-
-; TaskCanceledException
-TaskCanceledException_ctor_DefaultMessage=A task was canceled.
-
-;TaskCompletionSource<T>
-TaskCompletionSourceT_TrySetException_NullException=The exceptions collection included at least one null element.
-TaskCompletionSourceT_TrySetException_NoExceptions=The exceptions collection was empty.
-
-;TaskExceptionHolder
-TaskExceptionHolder_UnknownExceptionType=(Internal)Expected an Exception or an IEnumerable<Exception>
-TaskExceptionHolder_UnhandledException=A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
-
-; TaskScheduler
-TaskScheduler_ExecuteTask_TaskAlreadyExecuted=ExecuteTask may not be called for a task which was already executed.
-TaskScheduler_ExecuteTask_WrongTaskScheduler=ExecuteTask may not be called for a task which was previously queued to a different TaskScheduler.
-TaskScheduler_InconsistentStateAfterTryExecuteTaskInline=The TryExecuteTaskInline call to the underlying scheduler succeeded, but the task body was not invoked.
-TaskScheduler_FromCurrentSynchronizationContext_NoCurrent=The current SynchronizationContext may not be used as a TaskScheduler.
-
-; TaskSchedulerException
-TaskSchedulerException_ctor_DefaultMessage=An exception was thrown by a TaskScheduler.
-
-;
-; ParallelState ( used in Parallel.For(), Parallel.ForEach() )
-ParallelState_Break_InvalidOperationException_BreakAfterStop=Break was called after Stop was called.
-ParallelState_Stop_InvalidOperationException_StopAfterBreak=Stop was called after Break was called.
-ParallelState_NotSupportedException_UnsupportedMethod=This method is not supported.
-
-;
-; TPLETWProvider events
-event_ParallelLoopBegin=Beginning {3} loop {2} from Task {1}.
-event_ParallelLoopEnd=Ending loop {2} after {3} iterations.
-event_ParallelInvokeBegin=Beginning ParallelInvoke {2} from Task {1} for {4} actions.
-event_ParallelInvokeEnd=Ending ParallelInvoke {2}.
-event_ParallelFork=Task {1} entering fork/join {2}.
-event_ParallelJoin=Task {1} leaving fork/join {2}.
-event_TaskScheduled=Task {2} scheduled to TaskScheduler {0}.
-event_TaskStarted=Task {2} executing.
-event_TaskCompleted=Task {2} completed.
-event_TaskWaitBegin=Beginning wait ({3}) on Task {2}.
-event_TaskWaitEnd=Ending wait on Task {2}.
-
-
-;
-; Weak Reference Exception
-;
-WeakReference_NoLongerValid = The weak reference is no longer valid.
-
-
-;
-; Interop Exceptions
-;
-Interop.COM_TypeMismatch = Type mismatch between source and destination types.
-Interop_Marshal_Unmappable_Char = Cannot marshal: Encountered unmappable character.
-
-;
-; Loader Exceptions
-;
-Loader_InvalidPath = Relative path must be a string that contains the substring, "..", or does not contain a root directory.
-Loader_Name = Name:
-Loader_NoContextPolicies = There are no context policies.
-Loader_ContextPolicies = Context Policies:
-
-;
-; AppDomain Exceptions
-AppDomain_RequireApplicationName = ApplicationName must be set before the DynamicBase can be set.
-AppDomain_AppBaseNotSet = The ApplicationBase must be set before retrieving this property.
-AppDomain_BindingModelIsLocked = Binding model is already locked for the AppDomain and cannot be reset.
-Argument_CustomAssemblyLoadContextRequestedNameMismatch = Resolved assembly's simple name should be the same as of the requested assembly.
-
-;
-; XMLSyntaxExceptions
-XMLSyntax_UnexpectedEndOfFile = Unexpected end of file.
-XMLSyntax_ExpectedCloseBracket = Expected > character.
-XMLSyntax_ExpectedSlashOrString = Expected / character or string.
-XMLSyntax_UnexpectedCloseBracket = Unexpected > character.
-XMLSyntax_SyntaxError = Invalid syntax on line {0}.
-XMLSyntax_SyntaxErrorEx = Invalid syntax on line {0} - '{1}'.
-XMLSyntax_InvalidSyntax = Invalid syntax.
-XML_Syntax_InvalidSyntaxInFile = Invalid XML in file '{0}' near element '{1}'.
-XMLSyntax_InvalidSyntaxSatAssemTag = Invalid XML in file "{0}" near element "{1}". The <satelliteassemblies> section only supports <assembly> tags.
-XMLSyntax_InvalidSyntaxSatAssemTagBadAttr = Invalid XML in file "{0}" near "{1}" and "{2}". In the <satelliteassemblies> section, the <assembly> tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name.
-XMLSyntax_InvalidSyntaxSatAssemTagNoAttr = Invalid XML in file "{0}". In the <satelliteassemblies> section, the <assembly> tag must have exactly 1 attribute called 'name', whose value is a fully-qualified assembly name.
-
-; MembershipConditions
-StrongName_ToString = StrongName - {0}{1}{2}
-StrongName_Name = name = {0}
-StrongName_Version = version = {0}
-Site_ToString = Site
-Publisher_ToString = Publisher
-Hash_ToString = Hash - {0} = {1}
-ApplicationDirectory_ToString = ApplicationDirectory
-Zone_ToString = Zone - {0}
-All_ToString = All code
-Url_ToString = Url
-GAC_ToString = GAC
-
-; Interop non exception strings.
-TypeLibConverter_ImportedTypeLibProductName = Assembly imported from type library '{0}'.
-
-;
-; begin System.TimeZoneInfo ArgumentException's
-;
-Argument_AdjustmentRulesNoNulls = The AdjustmentRule array cannot contain null elements.
-Argument_AdjustmentRulesOutOfOrder = The elements of the AdjustmentRule array must be in chronological order and must not overlap.
-Argument_AdjustmentRulesAmbiguousOverlap = The elements of the AdjustmentRule array must not contain ambiguous time periods that extend beyond the DateStart or DateEnd properties of the element.
-Argument_AdjustmentRulesrDaylightSavingTimeOverlap = The elements of the AdjustmentRule array must not contain Daylight Saving Time periods that overlap adjacent elements in such a way as to cause invalid or ambiguous time periods.
-Argument_AdjustmentRulesrDaylightSavingTimeOverlapNonRuleRange = The elements of the AdjustmentRule array must not contain Daylight Saving Time periods that overlap the DateStart or DateEnd properties in such a way as to cause invalid or ambiguous time periods.
-Argument_AdjustmentRulesInvalidOverlap = The elements of the AdjustmentRule array must not contain invalid time periods that extend beyond the DateStart or DateEnd properties of the element.
-Argument_ConvertMismatch = The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local.
-Argument_DateTimeHasTimeOfDay = The supplied DateTime includes a TimeOfDay setting. This is not supported.
-Argument_DateTimeIsInvalid = The supplied DateTime represents an invalid time. For example, when the clock is adjusted forward, any time in the period that is skipped is invalid.
-Argument_DateTimeIsNotAmbiguous = The supplied DateTime is not in an ambiguous time range.
-Argument_DateTimeOffsetIsNotAmbiguous = The supplied DateTimeOffset is not in an ambiguous time range.
-Argument_DateTimeKindMustBeUnspecifiedOrUtc = The supplied DateTime must have the Kind property set to DateTimeKind.Unspecified or DateTimeKind.Utc.
-Argument_DateTimeHasTicks = The supplied DateTime must have the Year, Month, and Day properties set to 1. The time cannot be specified more precisely than whole milliseconds.
-Argument_InvalidId = The specified ID parameter '{0}' is not supported.
-Argument_InvalidSerializedString = The specified serialized string '{0}' is not supported.
-Argument_InvalidREG_TZI_FORMAT = The REG_TZI_FORMAT structure is corrupt.
-Argument_OutOfOrderDateTimes = The DateStart property must come before the DateEnd property.
-Argument_TimeSpanHasSeconds = The TimeSpan parameter cannot be specified more precisely than whole minutes.
-Argument_TimeZoneInfoBadTZif = The tzfile does not begin with the magic characters 'TZif'. Please verify that the file is not corrupt.
-Argument_TimeZoneInfoInvalidTZif = The TZif data structure is corrupt.
-Argument_TransitionTimesAreIdentical = The DaylightTransitionStart property must not equal the DaylightTransitionEnd property.
-;
-; begin System.TimeZoneInfo ArgumentOutOfRangeException's
-;
-ArgumentOutOfRange_DayParam = The Day parameter must be in the range 1 through 31.
-ArgumentOutOfRange_DayOfWeek = The DayOfWeek enumeration must be in the range 0 through 6.
-ArgumentOutOfRange_MonthParam = The Month parameter must be in the range 1 through 12.
-ArgumentOutOfRange_UtcOffset = The TimeSpan parameter must be within plus or minus 14.0 hours.
-ArgumentOutOfRange_UtcOffsetAndDaylightDelta = The sum of the BaseUtcOffset and DaylightDelta properties must within plus or minus 14.0 hours.
-ArgumentOutOfRange_Week = The Week parameter must be in the range 1 through 5.
-;
-; begin System.TimeZoneInfo InvalidTimeZoneException's
-;
-InvalidTimeZone_InvalidRegistryData = The time zone ID '{0}' was found on the local computer, but the registry information was corrupt.
-InvalidTimeZone_InvalidFileData = The time zone ID '{0}' was found on the local computer, but the file at '{1}' was corrupt.
-InvalidTimeZone_InvalidWin32APIData = The Local time zone was found on the local computer, but the data was corrupt.
-InvalidTimeZone_NoTTInfoStructures = There are no ttinfo structures in the tzfile. At least one ttinfo structure is required in order to construct a TimeZoneInfo object.
-InvalidTimeZone_UnparseablePosixMDateString = '{0}' is not a valid POSIX-TZ-environment-variable MDate rule. A valid rule has the format 'Mm.w.d'.
-InvalidTimeZone_JulianDayNotSupported = Julian dates in POSIX strings are unsupported.
-;
-; begin System.TimeZoneInfo SecurityException's
-;
-Security_CannotReadRegistryData = The time zone ID '{0}' was found on the local computer, but the application does not have permission to read the registry information.
-Security_CannotReadFileData = The time zone ID '{0}' was found on the local computer, but the application does not have permission to read the file.
-;
-; begin System.TimeZoneInfo SerializationException's
-;
-Serialization_CorruptField = The value of the field '{0}' is invalid. The serialized data is corrupt.
-Serialization_InvalidEscapeSequence = The serialized data contained an invalid escape sequence '\\{0}'.
-;
-; begin System.TimeZoneInfo TimeZoneNotFoundException's
-;
-TimeZoneNotFound_MissingData = The time zone ID '{0}' was not found on the local computer.
-;
-; end System.TimeZoneInfo
-;
-
-
-; Tuple
-ArgumentException_TupleIncorrectType=Argument must be of type {0}.
-ArgumentException_TupleNonIComparableElement=The tuple contains an element of type {0} which does not implement the IComparable interface.
-ArgumentException_TupleLastArgumentNotATuple=The last element of an eight element tuple must be a Tuple.
-ArgumentException_OtherNotArrayOfCorrectLength=Object is not a array with the same number of elements as the array to compare it to.
-
-; WinRT collection adapters
-Argument_IndexOutOfArrayBounds=The specified index is out of bounds of the specified array.
-Argument_InsufficientSpaceToCopyCollection=The specified space is not sufficient to copy the elements from this Collection.
-ArgumentOutOfRange_IndexLargerThanMaxValue=This collection cannot work with indices larger than Int32.MaxValue - 1 (0x7FFFFFFF - 1).
-ArgumentOutOfRange_IndexOutOfRange=The specified index is outside the current index range of this collection.
-InvalidOperation_CollectionBackingListTooLarge=The collection backing this List contains too many elements.
-InvalidOperation_CollectionBackingDictionaryTooLarge=The collection backing this Dictionary contains too many elements.
-InvalidOperation_CannotRemoveLastFromEmptyCollection=Cannot remove the last element from an empty collection.
-
-; Buffers
-ArgumentException_BufferNotFromPool=The buffer is not associated with this pool and may not be returned to it.
-
-;------------------
-; Encoding names:
-;
-;Total items: 147
-;
-Globalization.cp_1200 = Unicode
-Globalization.cp_1201 = Unicode (Big-Endian)
-Globalization.cp_65001 = Unicode (UTF-8)
-Globalization.cp_65000 = Unicode (UTF-7)
-Globalization.cp_12000 = Unicode (UTF-32)
-Globalization.cp_12001 = Unicode (UTF-32 Big-Endian)
-Globalization.cp_20127 = US-ASCII
-Globalization.cp_28591 = Western European (ISO)
-
-#if FEATURE_NON_UNICODE_CODE_PAGES
-Globalization.cp_37 = IBM EBCDIC (US-Canada)
-Globalization.cp_437 = OEM United States
-Globalization.cp_500 = IBM EBCDIC (International)
-Globalization.cp_708 = Arabic (ASMO 708)
-Globalization.cp_720 = Arabic (DOS)
-Globalization.cp_737 = Greek (DOS)
-Globalization.cp_775 = Baltic (DOS)
-Globalization.cp_850 = Western European (DOS)
-Globalization.cp_852 = Central European (DOS)
-Globalization.cp_855 = OEM Cyrillic
-Globalization.cp_857 = Turkish (DOS)
-Globalization.cp_858 = OEM Multilingual Latin I
-Globalization.cp_860 = Portuguese (DOS)
-Globalization.cp_861 = Icelandic (DOS)
-Globalization.cp_862 = Hebrew (DOS)
-Globalization.cp_863 = French Canadian (DOS)
-Globalization.cp_864 = Arabic (864)
-Globalization.cp_865 = Nordic (DOS)
-Globalization.cp_866 = Cyrillic (DOS)
-Globalization.cp_869 = Greek, Modern (DOS)
-Globalization.cp_870 = IBM EBCDIC (Multilingual Latin-2)
-Globalization.cp_874 = Thai (Windows)
-Globalization.cp_875 = IBM EBCDIC (Greek Modern)
-Globalization.cp_932 = Japanese (Shift-JIS)
-Globalization.cp_936 = Chinese Simplified (GB2312)
-Globalization.cp_949 = Korean
-Globalization.cp_950 = Chinese Traditional (Big5)
-Globalization.cp_1026 = IBM EBCDIC (Turkish Latin-5)
-Globalization.cp_1047 = IBM Latin-1
-Globalization.cp_1140 = IBM EBCDIC (US-Canada-Euro)
-Globalization.cp_1141 = IBM EBCDIC (Germany-Euro)
-Globalization.cp_1142 = IBM EBCDIC (Denmark-Norway-Euro)
-Globalization.cp_1143 = IBM EBCDIC (Finland-Sweden-Euro)
-Globalization.cp_1144 = IBM EBCDIC (Italy-Euro)
-Globalization.cp_1145 = IBM EBCDIC (Spain-Euro)
-Globalization.cp_1146 = IBM EBCDIC (UK-Euro)
-Globalization.cp_1147 = IBM EBCDIC (France-Euro)
-Globalization.cp_1148 = IBM EBCDIC (International-Euro)
-Globalization.cp_1149 = IBM EBCDIC (Icelandic-Euro)
-Globalization.cp_1250 = Central European (Windows)
-Globalization.cp_1251 = Cyrillic (Windows)
-Globalization.cp_1252 = Western European (Windows)
-Globalization.cp_1253 = Greek (Windows)
-Globalization.cp_1254 = Turkish (Windows)
-Globalization.cp_1255 = Hebrew (Windows)
-Globalization.cp_1256 = Arabic (Windows)
-Globalization.cp_1257 = Baltic (Windows)
-Globalization.cp_1258 = Vietnamese (Windows)
-Globalization.cp_1361 = Korean (Johab)
-Globalization.cp_10000 = Western European (Mac)
-Globalization.cp_10001 = Japanese (Mac)
-Globalization.cp_10002 = Chinese Traditional (Mac)
-Globalization.cp_10003 = Korean (Mac)
-Globalization.cp_10004 = Arabic (Mac)
-Globalization.cp_10005 = Hebrew (Mac)
-Globalization.cp_10006 = Greek (Mac)
-Globalization.cp_10007 = Cyrillic (Mac)
-Globalization.cp_10008 = Chinese Simplified (Mac)
-Globalization.cp_10010 = Romanian (Mac)
-Globalization.cp_10017 = Ukrainian (Mac)
-Globalization.cp_10021 = Thai (Mac)
-Globalization.cp_10029 = Central European (Mac)
-Globalization.cp_10079 = Icelandic (Mac)
-Globalization.cp_10081 = Turkish (Mac)
-Globalization.cp_10082 = Croatian (Mac)
-Globalization.cp_20000 = Chinese Traditional (CNS)
-Globalization.cp_20001 = TCA Taiwan
-Globalization.cp_20002 = Chinese Traditional (Eten)
-Globalization.cp_20003 = IBM5550 Taiwan
-Globalization.cp_20004 = TeleText Taiwan
-Globalization.cp_20005 = Wang Taiwan
-Globalization.cp_20105 = Western European (IA5)
-Globalization.cp_20106 = German (IA5)
-Globalization.cp_20107 = Swedish (IA5)
-Globalization.cp_20108 = Norwegian (IA5)
-Globalization.cp_20261 = T.61
-Globalization.cp_20269 = ISO-6937
-Globalization.cp_20273 = IBM EBCDIC (Germany)
-Globalization.cp_20277 = IBM EBCDIC (Denmark-Norway)
-Globalization.cp_20278 = IBM EBCDIC (Finland-Sweden)
-Globalization.cp_20280 = IBM EBCDIC (Italy)
-Globalization.cp_20284 = IBM EBCDIC (Spain)
-Globalization.cp_20285 = IBM EBCDIC (UK)
-Globalization.cp_20290 = IBM EBCDIC (Japanese katakana)
-Globalization.cp_20297 = IBM EBCDIC (France)
-Globalization.cp_20420 = IBM EBCDIC (Arabic)
-Globalization.cp_20423 = IBM EBCDIC (Greek)
-Globalization.cp_20424 = IBM EBCDIC (Hebrew)
-Globalization.cp_20833 = IBM EBCDIC (Korean Extended)
-Globalization.cp_20838 = IBM EBCDIC (Thai)
-Globalization.cp_20866 = Cyrillic (KOI8-R)
-Globalization.cp_20871 = IBM EBCDIC (Icelandic)
-Globalization.cp_20880 = IBM EBCDIC (Cyrillic Russian)
-Globalization.cp_20905 = IBM EBCDIC (Turkish)
-Globalization.cp_20924 = IBM Latin-1
-Globalization.cp_20932 = Japanese (JIS 0208-1990 and 0212-1990)
-Globalization.cp_20936 = Chinese Simplified (GB2312-80)
-Globalization.cp_20949 = Korean Wansung
-Globalization.cp_21025 = IBM EBCDIC (Cyrillic Serbian-Bulgarian)
-Globalization.cp_21027 = Ext Alpha Lowercase
-Globalization.cp_21866 = Cyrillic (KOI8-U)
-Globalization.cp_28592 = Central European (ISO)
-Globalization.cp_28593 = Latin 3 (ISO)
-Globalization.cp_28594 = Baltic (ISO)
-Globalization.cp_28595 = Cyrillic (ISO)
-Globalization.cp_28596 = Arabic (ISO)
-Globalization.cp_28597 = Greek (ISO)
-Globalization.cp_28598 = Hebrew (ISO-Visual)
-Globalization.cp_28599 = Turkish (ISO)
-Globalization.cp_28603 = Estonian (ISO)
-Globalization.cp_28605 = Latin 9 (ISO)
-Globalization.cp_29001 = Europa
-Globalization.cp_38598 = Hebrew (ISO-Logical)
-Globalization.cp_50000 = User Defined
-Globalization.cp_50220 = Japanese (JIS)
-Globalization.cp_50221 = Japanese (JIS-Allow 1 byte Kana)
-Globalization.cp_50222 = Japanese (JIS-Allow 1 byte Kana - SO/SI)
-Globalization.cp_50225 = Korean (ISO)
-Globalization.cp_50227 = Chinese Simplified (ISO-2022)
-Globalization.cp_50229 = Chinese Traditional (ISO-2022)
-Globalization.cp_50930 = IBM EBCDIC (Japanese and Japanese Katakana)
-Globalization.cp_50931 = IBM EBCDIC (Japanese and US-Canada)
-Globalization.cp_50933 = IBM EBCDIC (Korean and Korean Extended)
-Globalization.cp_50935 = IBM EBCDIC (Simplified Chinese)
-Globalization.cp_50937 = IBM EBCDIC (Traditional Chinese)
-Globalization.cp_50939 = IBM EBCDIC (Japanese and Japanese-Latin)
-Globalization.cp_51932 = Japanese (EUC)
-Globalization.cp_51936 = Chinese Simplified (EUC)
-Globalization.cp_51949 = Korean (EUC)
-Globalization.cp_52936 = Chinese Simplified (HZ)
-Globalization.cp_54936 = Chinese Simplified (GB18030)
-Globalization.cp_57002 = ISCII Devanagari
-Globalization.cp_57003 = ISCII Bengali
-Globalization.cp_57004 = ISCII Tamil
-Globalization.cp_57005 = ISCII Telugu
-Globalization.cp_57006 = ISCII Assamese
-Globalization.cp_57007 = ISCII Oriya
-Globalization.cp_57008 = ISCII Kannada
-Globalization.cp_57009 = ISCII Malayalam
-Globalization.cp_57010 = ISCII Gujarati
-Globalization.cp_57011 = ISCII Punjabi
-#endif // FEATURE_NON_UNICODE_CODE_PAGES
-#endif // INCLUDE_DEBUG
-
-;------------------
-
-; ValueTuple
-ArgumentException_ValueTupleIncorrectType=Argument must be of type {0}.
-ArgumentException_ValueTupleLastArgumentNotAValueTuple=The last element of an eight element ValueTuple must be a ValueTuple.
diff --git a/src/mscorlib/src/System/Action.cs b/src/mscorlib/src/System/Action.cs
deleted file mode 100644
index 23c7e93194..0000000000
--- a/src/mscorlib/src/System/Action.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.
-
-namespace System
-{
- public delegate void Action<in T>(T obj);
-
- public delegate void Action();
- public delegate void Action<in T1,in T2>(T1 arg1, T2 arg2);
- public delegate void Action<in T1,in T2,in T3>(T1 arg1, T2 arg2, T3 arg3);
- public delegate void Action<in T1,in T2,in T3,in T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
-
- public delegate TResult Func<out TResult>();
- public delegate TResult Func<in T, out TResult>(T arg);
- public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
- public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
- public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
-
- public delegate void Action<in T1,in T2,in T3,in T4,in T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
- public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
- public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
- public delegate void Action<in T1,in T2,in T3,in T4,in T5,in T6,in T7,in T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
-
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
- public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
-
- public delegate int Comparison<in T>(T x, T y);
-
- public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
-
- public delegate bool Predicate<in T>(T obj);
-}
diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs
index 323fbba9cc..34c6ea5874 100644
--- a/src/mscorlib/src/System/Activator.cs
+++ b/src/mscorlib/src/System/Activator.cs
@@ -11,8 +11,9 @@
//
//
//
-namespace System {
+namespace System
+{
using System;
using System.Reflection;
using System.Runtime.Remoting;
@@ -29,9 +30,9 @@ namespace System {
// Only statics, does not need to be marked with the serializable attribute
public sealed class Activator
{
- internal const int LookupMask = 0x000000FF;
- internal const BindingFlags ConLookup = (BindingFlags) (BindingFlags.Instance | BindingFlags.Public);
- internal const BindingFlags ConstructorDefault= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
+ internal const int LookupMask = 0x000000FF;
+ internal const BindingFlags ConLookup = (BindingFlags)(BindingFlags.Instance | BindingFlags.Public);
+ internal const BindingFlags ConstructorDefault = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance;
// This class only contains statics, so hide the worthless constructor
private Activator()
@@ -47,12 +48,12 @@ namespace System {
BindingFlags bindingAttr,
Binder binder,
Object[] args,
- CultureInfo culture)
+ CultureInfo culture)
{
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
@@ -65,23 +66,24 @@ namespace System {
Contract.EndContractBlock();
if (type is System.Reflection.Emit.TypeBuilder)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"));
+ throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder);
// If they didn't specify a lookup, then we will provide the default lookup.
- if ((bindingAttr & (BindingFlags) LookupMask) == 0)
+ if ((bindingAttr & (BindingFlags)LookupMask) == 0)
bindingAttr |= Activator.ConstructorDefault;
- if (activationAttributes != null && activationAttributes.Length > 0){
- throw new PlatformNotSupportedException(Environment.GetResourceString("NotSupported_ActivAttr" ));
+ if (activationAttributes != null && activationAttributes.Length > 0)
+ {
+ throw new PlatformNotSupportedException(SR.NotSupported_ActivAttr);
}
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type));
+ 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, ref stackMark);
}
static public Object CreateInstance(Type type, params Object[] args)
@@ -98,14 +100,14 @@ namespace System {
Object[] args,
Object[] activationAttributes)
{
- return CreateInstance(type,
- Activator.ConstructorDefault,
- null,
- args,
- null,
- activationAttributes);
+ return CreateInstance(type,
+ Activator.ConstructorDefault,
+ null,
+ args,
+ null,
+ activationAttributes);
}
-
+
static public Object CreateInstance(Type type)
{
return Activator.CreateInstance(type, false);
@@ -116,13 +118,13 @@ namespace System {
* types to be created remotely without having to load the type locally.
*/
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public ObjectHandle CreateInstance(String assemblyName,
String typeName)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
- typeName,
+ typeName,
false,
Activator.ConstructorDefault,
null,
@@ -133,15 +135,15 @@ namespace System {
ref stackMark);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public ObjectHandle CreateInstance(String assemblyName,
String typeName,
Object[] activationAttributes)
-
+
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return CreateInstance(assemblyName,
- typeName,
+ typeName,
false,
Activator.ConstructorDefault,
null,
@@ -151,8 +153,8 @@ namespace System {
null,
ref stackMark);
}
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type, bool nonPublic)
{
if ((object)type == null)
@@ -162,13 +164,13 @@ namespace System {
RuntimeType rt = type.UnderlyingSystemType as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(type));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(type));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public T CreateInstance<T>()
{
RuntimeType rt = typeof(T) as RuntimeType;
@@ -176,7 +178,7 @@ namespace System {
// This is a workaround to maintain compatibility with V2. Without this we would throw a NotSupportedException for void[].
// Array, Ref, and Pointer types don't have default constructors.
if (rt.HasElementType)
- throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor"));
+ throw new MissingMethodException(SR.Arg_NoDefCTor);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -186,7 +188,7 @@ namespace System {
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName)
-
+
{
return CreateInstanceFrom(assemblyFile, typeName, null);
}
@@ -194,10 +196,10 @@ namespace System {
static public ObjectHandle CreateInstanceFrom(String assemblyFile,
String typeName,
Object[] activationAttributes)
-
+
{
return CreateInstanceFrom(assemblyFile,
- typeName,
+ typeName,
false,
Activator.ConstructorDefault,
null,
@@ -206,7 +208,7 @@ namespace System {
activationAttributes);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static ObjectHandle CreateInstance(string assemblyName,
string typeName,
bool ignoreCase,
@@ -229,10 +231,10 @@ namespace System {
ref stackMark);
}
- static internal ObjectHandle CreateInstance(String assemblyString,
- String typeName,
+ static internal ObjectHandle CreateInstance(String assemblyString,
+ String typeName,
bool ignoreCase,
- BindingFlags bindingAttr,
+ BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
@@ -242,18 +244,26 @@ namespace System {
{
Type type = null;
Assembly assembly = null;
- if (assemblyString == null) {
+ if (assemblyString == null)
+ {
assembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- } else {
+ }
+ else
+ {
RuntimeAssembly assemblyFromResolveEvent;
AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(assemblyString, false /*forIntrospection*/, out assemblyFromResolveEvent);
- if (assemblyFromResolveEvent != null) {
+ if (assemblyFromResolveEvent != null)
+ {
// Assembly was resolved via AssemblyResolve event
assembly = assemblyFromResolveEvent;
- } else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) {
+ }
+ else if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime)
+ {
// WinRT type - we have to use Type.GetType
type = Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, ignoreCase);
- } else {
+ }
+ else
+ {
// Classic managed type
assembly = RuntimeAssembly.InternalLoadAssemblyName(
assemblyName, securityInfo, null, ref stackMark,
@@ -261,14 +271,15 @@ namespace System {
}
}
- if (type == null) {
+ if (type == null)
+ {
// It's classic managed type (not WinRT type)
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyString);
- if(assembly == null) return null;
+ if (assembly == null) return null;
type = assembly.GetType(typeName, true /*throwOnError*/, ignoreCase);
}
-
+
Object o = Activator.CreateInstance(type,
bindingAttr,
binder,
@@ -277,9 +288,10 @@ namespace System {
activationAttributes);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
- if(o == null)
+ if (o == null)
return null;
- else {
+ else
+ {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
@@ -306,9 +318,9 @@ namespace System {
}
private static ObjectHandle CreateInstanceFromInternal(String assemblyFile,
- String typeName,
+ String typeName,
bool ignoreCase,
- BindingFlags bindingAttr,
+ BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
@@ -319,7 +331,7 @@ namespace System {
Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
#pragma warning restore 618
Type t = assembly.GetType(typeName, true, ignoreCase);
-
+
Object o = Activator.CreateInstance(t,
bindingAttr,
binder,
@@ -328,9 +340,10 @@ namespace System {
activationAttributes);
Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
- if(o == null)
+ if (o == null)
return null;
- else {
+ else
+ {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
@@ -343,30 +356,29 @@ namespace System {
typeName,
null,
AssemblyHashAlgorithm.None);
-
}
-
+
public static ObjectHandle CreateComInstanceFrom(String assemblyName,
String typeName,
- byte[] hashValue,
+ byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm)
{
Assembly assembly = Assembly.LoadFrom(assemblyName, hashValue, hashAlgorithm);
Type t = assembly.GetType(typeName, true, false);
- Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute),false);
+ Object[] Attr = t.GetCustomAttributes(typeof(ComVisibleAttribute), false);
if (Attr.Length > 0)
{
if (((ComVisibleAttribute)Attr[0]).Value == false)
- throw new TypeLoadException(Environment.GetResourceString( "Argument_TypeMustBeVisibleFromCom" ));
+ throw new TypeLoadException(SR.Argument_TypeMustBeVisibleFromCom);
}
Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
- if(assembly == null) return null;
+ if (assembly == null) return null;
+
-
Object o = Activator.CreateInstance(t,
Activator.ConstructorDefault,
null,
@@ -375,9 +387,10 @@ namespace System {
null);
Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
- if(o == null)
+ if (o == null)
return null;
- else {
+ else
+ {
ObjectHandle Handle = new ObjectHandle(o);
return Handle;
}
diff --git a/src/mscorlib/src/System/AggregateException.cs b/src/mscorlib/src/System/AggregateException.cs
index c0f21229ed..22bc323215 100644
--- a/src/mscorlib/src/System/AggregateException.cs
+++ b/src/mscorlib/src/System/AggregateException.cs
@@ -23,7 +23,6 @@ using System.Threading;
namespace System
{
-
/// <summary>Represents one or more errors that occur during application execution.</summary>
/// <remarks>
/// <see cref="AggregateException"/> is used to consolidate multiple failures into a single, throwable
@@ -33,14 +32,13 @@ namespace System
[DebuggerDisplay("Count = {InnerExceptionCount}")]
public class AggregateException : Exception
{
-
private ReadOnlyCollection<Exception> m_innerExceptions; // Complete set of exceptions.
/// <summary>
/// Initializes a new instance of the <see cref="AggregateException"/> class.
/// </summary>
public AggregateException()
- : base(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"))
+ : base(SR.AggregateException_ctor_DefaultMessage)
{
m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
}
@@ -85,7 +83,7 @@ namespace System
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(IEnumerable<Exception> innerExceptions) :
- this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions)
+ this(SR.AggregateException_ctor_DefaultMessage, innerExceptions)
{
}
@@ -99,7 +97,7 @@ namespace System
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptions"/> is
/// null.</exception>
public AggregateException(params Exception[] innerExceptions) :
- this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptions)
+ this(SR.AggregateException_ctor_DefaultMessage, innerExceptions)
{
}
@@ -163,7 +161,7 @@ namespace System
if (exceptionsCopy[i] == null)
{
- throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull"));
+ throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull);
}
}
@@ -182,7 +180,7 @@ namespace System
/// <exception cref="T:System.ArgumentException">An element of <paramref name="innerExceptionInfos"/> is
/// null.</exception>
internal AggregateException(IEnumerable<ExceptionDispatchInfo> innerExceptionInfos) :
- this(Environment.GetResourceString("AggregateException_ctor_DefaultMessage"), innerExceptionInfos)
+ this(SR.AggregateException_ctor_DefaultMessage, innerExceptionInfos)
{
}
@@ -202,9 +200,9 @@ namespace System
internal AggregateException(string message, IEnumerable<ExceptionDispatchInfo> innerExceptionInfos)
// If it's already an IList, pass that along (a defensive copy will be made in the delegated ctor). If it's null, just pass along
// null typed correctly. Otherwise, create an IList from the enumerable and pass that along.
- : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ??
- (innerExceptionInfos == null ?
- (List<ExceptionDispatchInfo>)null :
+ : this(message, innerExceptionInfos as IList<ExceptionDispatchInfo> ??
+ (innerExceptionInfos == null ?
+ (List<ExceptionDispatchInfo>)null :
new List<ExceptionDispatchInfo>(innerExceptionInfos)))
{
}
@@ -242,7 +240,7 @@ namespace System
if (exceptionsCopy[i] == null)
{
- throw new ArgumentException(Environment.GetResourceString("AggregateException_ctor_InnerExceptionNull"));
+ throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull);
}
}
@@ -269,7 +267,7 @@ namespace System
Exception[] innerExceptions = info.GetValue("InnerExceptions", typeof(Exception[])) as Exception[];
if (innerExceptions == null)
{
- throw new SerializationException(Environment.GetResourceString("AggregateException_DeserializationFailure"));
+ throw new SerializationException(SR.AggregateException_DeserializationFailure);
}
m_innerExceptions = new ReadOnlyCollection<Exception>(innerExceptions);
@@ -468,7 +466,7 @@ namespace System
{
text = String.Format(
CultureInfo.InvariantCulture,
- Environment.GetResourceString("AggregateException_ToString"),
+ SR.AggregateException_ToString,
text, Environment.NewLine, i, m_innerExceptions[i].ToString(), "<---", Environment.NewLine);
}
@@ -492,5 +490,4 @@ namespace System
}
}
}
-
}
diff --git a/src/mscorlib/src/System/AppContext/AppContext.cs b/src/mscorlib/src/System/AppContext/AppContext.cs
index 5a3b732fa8..7c7e74f19b 100644
--- a/src/mscorlib/src/System/AppContext/AppContext.cs
+++ b/src/mscorlib/src/System/AppContext/AppContext.cs
@@ -35,7 +35,7 @@ namespace System
{
// The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type.
// Otherwise the caller will get invalid cast exception
- return (string) AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory;
+ return (string)AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory;
}
}
@@ -72,16 +72,16 @@ namespace System
}
public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException
- {
- add
- {
- AppDomain.CurrentDomain.FirstChanceException += value;
- }
- remove
- {
- AppDomain.CurrentDomain.FirstChanceException -= value;
- }
- }
+ {
+ add
+ {
+ AppDomain.CurrentDomain.FirstChanceException += value;
+ }
+ remove
+ {
+ AppDomain.CurrentDomain.FirstChanceException -= value;
+ }
+ }
public static event System.EventHandler ProcessExit;
internal static event System.EventHandler Unloading;
@@ -116,7 +116,7 @@ namespace System
if (switchName == null)
throw new ArgumentNullException(nameof(switchName));
if (switchName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(switchName));
// By default, the switch is not enabled.
isEnabled = false;
@@ -144,7 +144,7 @@ namespace System
}
// We get the value of isEnabled from the value that we stored in the dictionary
- isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue;
+ isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue;
// 2. The switch has a valid value AND we have checked for overrides
if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride)
@@ -212,7 +212,7 @@ namespace System
if (switchName == null)
throw new ArgumentNullException(nameof(switchName));
if (switchName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(switchName));
SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue)
| SwitchValueState.HasLookedForOverride;
diff --git a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs
index 52bdf9d427..ddecf18646 100644
--- a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs
+++ b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.Defaults.cs
@@ -8,7 +8,6 @@ namespace System
{
internal static partial class AppContextDefaultValues
{
-
internal static readonly string SwitchNoAsyncCurrentCulture = "Switch.System.Globalization.NoAsyncCurrentCulture";
internal static readonly string SwitchThrowExceptionIfDisposedCancellationTokenSource = "Switch.System.Threading.ThrowExceptionIfDisposedCancellationTokenSource";
internal static readonly string SwitchPreserveEventListnerObjectIdentity = "Switch.System.Diagnostics.EventSource.PreserveEventListnerObjectIdentity";
diff --git a/src/mscorlib/src/System/AppContext/AppContextSwitches.cs b/src/mscorlib/src/System/AppContext/AppContextSwitches.cs
index 5fdd2bc1e6..03b535bda2 100644
--- a/src/mscorlib/src/System/AppContext/AppContextSwitches.cs
+++ b/src/mscorlib/src/System/AppContext/AppContextSwitches.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;
+using System.Runtime.CompilerServices;
+
namespace System
{
- using System;
- using System.Runtime.CompilerServices;
-
internal static class AppContextSwitches
{
private static int _noAsyncCurrentCulture;
diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs
index c6987392d5..7d2f2ceaf8 100644
--- a/src/mscorlib/src/System/AppDomain.cs
+++ b/src/mscorlib/src/System/AppDomain.cs
@@ -37,59 +37,6 @@ namespace System
using System.Diagnostics.Contracts;
using System.Runtime.ExceptionServices;
- public class ResolveEventArgs : EventArgs
- {
- private String _Name;
- private Assembly _RequestingAssembly;
-
- public String Name {
- get {
- return _Name;
- }
- }
-
- public Assembly RequestingAssembly
- {
- get
- {
- return _RequestingAssembly;
- }
- }
-
- public ResolveEventArgs(String name)
- {
- _Name = name;
- }
-
- public ResolveEventArgs(String name, Assembly requestingAssembly)
- {
- _Name = name;
- _RequestingAssembly = requestingAssembly;
- }
- }
-
- public class AssemblyLoadEventArgs : EventArgs
- {
- private Assembly _LoadedAssembly;
-
- public Assembly LoadedAssembly {
- get {
- return _LoadedAssembly;
- }
- }
-
- public AssemblyLoadEventArgs(Assembly loadedAssembly)
- {
- _LoadedAssembly = loadedAssembly;
- }
- }
-
- [Serializable]
- public delegate Assembly ResolveEventHandler(Object sender, ResolveEventArgs args);
-
- [Serializable]
- public delegate void AssemblyLoadEventHandler(Object sender, AssemblyLoadEventArgs args);
-
[Serializable]
internal delegate void AppDomainInitializer(string[] args);
@@ -106,62 +53,61 @@ namespace System
internal AppDomainInitializerInfo(AppDomainInitializer init)
{
- Info=null;
- if (init==null)
+ Info = null;
+ if (init == null)
return;
List<ItemInfo> itemInfo = new List<ItemInfo>();
List<AppDomainInitializer> nestedDelegates = new List<AppDomainInitializer>();
nestedDelegates.Add(init);
- int idx=0;
-
- while (nestedDelegates.Count>idx)
+ int idx = 0;
+
+ while (nestedDelegates.Count > idx)
{
AppDomainInitializer curr = nestedDelegates[idx++];
- Delegate[] list= curr.GetInvocationList();
- for (int i=0;i<list.Length;i++)
+ Delegate[] list = curr.GetInvocationList();
+ for (int i = 0; i < list.Length; i++)
{
- if (!list[i].Method.IsStatic)
+ if (!list[i].Method.IsStatic)
{
- if(list[i].Target==null)
+ if (list[i].Target == null)
continue;
-
+
AppDomainInitializer nested = list[i].Target as AppDomainInitializer;
- if (nested!=null)
+ if (nested != null)
nestedDelegates.Add(nested);
else
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStatic"),
- list[i].Method.ReflectedType.FullName+"::"+list[i].Method.Name);
+ throw new ArgumentException(SR.Arg_MustBeStatic,
+ list[i].Method.ReflectedType.FullName + "::" + list[i].Method.Name);
}
else
{
- ItemInfo info=new ItemInfo();
- info.TargetTypeAssembly=list[i].Method.ReflectedType.Module.Assembly.FullName;
- info.TargetTypeName=list[i].Method.ReflectedType.FullName;
- info.MethodName=list[i].Method.Name;
+ ItemInfo info = new ItemInfo();
+ info.TargetTypeAssembly = list[i].Method.ReflectedType.Module.Assembly.FullName;
+ info.TargetTypeName = list[i].Method.ReflectedType.FullName;
+ info.MethodName = list[i].Method.Name;
itemInfo.Add(info);
}
-
}
}
- Info = itemInfo.ToArray();
+ Info = itemInfo.ToArray();
}
-
+
internal AppDomainInitializer Unwrap()
{
- if (Info==null)
+ if (Info == null)
return null;
- AppDomainInitializer retVal=null;
- for (int i=0;i<Info.Length;i++)
+ AppDomainInitializer retVal = null;
+ for (int i = 0; i < Info.Length; i++)
{
- Assembly assembly=Assembly.Load(Info[i].TargetTypeAssembly);
- AppDomainInitializer newVal=(AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
+ Assembly assembly = Assembly.Load(Info[i].TargetTypeAssembly);
+ AppDomainInitializer newVal = (AppDomainInitializer)Delegate.CreateDelegate(typeof(AppDomainInitializer),
assembly.GetType(Info[i].TargetTypeName),
Info[i].MethodName);
- if(retVal==null)
- retVal=newVal;
+ if (retVal == null)
+ retVal = newVal;
else
- retVal+=newVal;
+ retVal += newVal;
}
return retVal;
}
@@ -176,10 +122,10 @@ namespace System
private AppDomainManager _domainManager;
private Dictionary<String, Object> _LocalStore;
- private AppDomainSetup _FusionStore;
- private Evidence _SecurityIdentity;
+ private AppDomainSetup _FusionStore;
+ private Evidence _SecurityIdentity;
#pragma warning disable 169
- private Object[] _Policies; // Called from the VM.
+ private Object[] _Policies; // Called from the VM.
#pragma warning restore 169
public event AssemblyLoadEventHandler AssemblyLoad;
@@ -246,30 +192,27 @@ namespace System
}
}
-#if FEATURE_REFLECTION_ONLY_LOAD
- public event ResolveEventHandler ReflectionOnlyAssemblyResolve;
-#endif // FEATURE_REFLECTION_ONLY
private ApplicationTrust _applicationTrust;
- private EventHandler _processExit;
+ private EventHandler _processExit;
- private EventHandler _domainUnload;
+ private EventHandler _domainUnload;
private UnhandledExceptionEventHandler _unhandledException;
// The compat flags are set at domain creation time to indicate that the given breaking
// changes (named in the strings) should not be used in this domain. We only use the
// keys, the vhe values are ignored.
- private Dictionary<String, object> _compatFlags;
+ private Dictionary<String, object> _compatFlags;
// Delegate that will hold references to FirstChance exception notifications
private EventHandler<FirstChanceExceptionEventArgs> _firstChanceException;
- private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
+ private IntPtr _pDomain; // this is an unmanaged pointer (AppDomain * m_pDomain)` used from the VM.
- private bool _HasSetPolicy;
- private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous
- private bool _compatFlagsInitialized;
+ private bool _HasSetPolicy;
+ private bool _IsFastFullTrustDomain; // quick check to see if the AppDomain is fully trusted and homogenous
+ private bool _compatFlagsInitialized;
internal const String TargetFrameworkNameAppCompatSetting = "TargetFrameworkName";
@@ -282,16 +225,12 @@ namespace System
[Flags]
private enum APPX_FLAGS
{
- APPX_FLAGS_INITIALIZED = 0x01,
-
- APPX_FLAGS_APPX_MODEL = 0x02,
- APPX_FLAGS_APPX_DESIGN_MODE = 0x04,
- APPX_FLAGS_APPX_NGEN = 0x08,
- APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL |
- APPX_FLAGS_APPX_DESIGN_MODE |
- APPX_FLAGS_APPX_NGEN,
+ APPX_FLAGS_INITIALIZED = 0x01,
- APPX_FLAGS_API_CHECK = 0x10,
+ APPX_FLAGS_APPX_MODEL = 0x02,
+ APPX_FLAGS_APPX_DESIGN_MODE = 0x04,
+ APPX_FLAGS_APPX_MASK = APPX_FLAGS_APPX_MODEL |
+ APPX_FLAGS_APPX_DESIGN_MODE,
}
private static APPX_FLAGS Flags
@@ -305,22 +244,6 @@ namespace System
return s_flags;
}
}
-
- internal static bool ProfileAPICheck
- {
- get
- {
- return (Flags & APPX_FLAGS.APPX_FLAGS_API_CHECK) != 0;
- }
- }
-
- internal static bool IsAppXNGen
- {
- get
- {
- return (Flags & APPX_FLAGS.APPX_FLAGS_APPX_NGEN) != 0;
- }
- }
#endif // FEATURE_APPX
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -361,7 +284,7 @@ namespace System
// uninitialized object through remoting, etc.
if (_pDomain.IsNull())
{
- throw new InvalidOperationException(Environment.GetResourceString("Argument_InvalidHandle"));
+ throw new InvalidOperationException(SR.Argument_InvalidHandle);
}
return new AppDomainHandle(_pDomain);
@@ -417,20 +340,20 @@ namespace System
}
catch (FileNotFoundException e)
{
- throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
+ throw new TypeLoadException(SR.Argument_NoDomainManager, e);
}
catch (SecurityException e)
{
- throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
+ throw new TypeLoadException(SR.Argument_NoDomainManager, e);
}
catch (TypeLoadException e)
{
- throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"), e);
+ throw new TypeLoadException(SR.Argument_NoDomainManager, e);
}
if (_domainManager == null)
{
- throw new TypeLoadException(Environment.GetResourceString("Argument_NoDomainManager"));
+ throw new TypeLoadException(SR.Argument_NoDomainManager);
}
// If this domain was not created by a managed call to CreateDomain, then the AppDomainSetup
@@ -463,7 +386,7 @@ namespace System
private void InitializeCompatibilityFlags()
{
AppDomainSetup adSetup = FusionStore;
-
+
// set up shim flags regardless of whether we create a DomainManager in this method.
if (adSetup.GetCompatibilityFlags() != null)
{
@@ -521,7 +444,7 @@ namespace System
{
#if FEATURE_APPX
if (IsAppXModel())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFrom"));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.LoadFrom"));
#endif
}
@@ -533,7 +456,7 @@ namespace System
{
#if FEATURE_APPX
if (IsAppXModel())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.LoadFile"));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.LoadFile"));
#endif
}
@@ -545,7 +468,7 @@ namespace System
{
#if FEATURE_APPX
if (IsAppXModel())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.ReflectionOnlyLoad"));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.ReflectionOnlyLoad"));
#endif
}
@@ -557,7 +480,7 @@ namespace System
{
#if FEATURE_APPX
if (IsAppXModel())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AppX", "Assembly.Load(byte[], ...)"));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_AppX, "Assembly.Load(byte[], ...)"));
#endif
}
@@ -603,17 +526,20 @@ namespace System
bool runtimeSuppliedHomogenousGrant = false;
ApplicationTrust appTrust = adSetup.ApplicationTrust;
- if (appTrust != null) {
+ if (appTrust != null)
+ {
SetupDomainSecurityForHomogeneousDomain(appTrust, runtimeSuppliedHomogenousGrant);
}
- else if (_IsFastFullTrustDomain) {
+ else if (_IsFastFullTrustDomain)
+ {
SetSecurityHomogeneousFlag(GetNativeHandle(), runtimeSuppliedHomogenousGrant);
}
// Get the evidence supplied for the domain. If no evidence was supplied, it means that we want
// to use the default evidence creation strategy for this domain
Evidence newAppDomainEvidence = (providedSecurityInfo != null ? providedSecurityInfo : creatorsSecurityInfo);
- if (newAppDomainEvidence == null && generateDefaultEvidence) {
+ if (newAppDomainEvidence == null && generateDefaultEvidence)
+ {
newAppDomainEvidence = new Evidence();
}
@@ -650,63 +576,18 @@ namespace System
runtimeSuppliedHomogenousGrantSet);
}
- public AppDomainManager DomainManager {
- get {
- return _domainManager;
- }
- }
-
-#if FEATURE_REFLECTION_ONLY_LOAD
- private Assembly ResolveAssemblyForIntrospection(Object sender, ResolveEventArgs args)
- {
- Contract.Requires(args != null);
- return Assembly.ReflectionOnlyLoad(ApplyPolicy(args.Name));
- }
-
- // Helper class for method code:EnableResolveAssembliesForIntrospection
- private class NamespaceResolverForIntrospection
+ public AppDomainManager DomainManager
{
- private IEnumerable<string> _packageGraphFilePaths;
- public NamespaceResolverForIntrospection(IEnumerable<string> packageGraphFilePaths)
- {
- _packageGraphFilePaths = packageGraphFilePaths;
- }
-
- public void ResolveNamespace(
- object sender,
- System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs args)
+ get
{
- Contract.Requires(args != null);
-
- IEnumerable<string> fileNames = System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ResolveNamespace(
- args.NamespaceName,
- null, // windowsSdkFilePath ... Use OS installed .winmd files
- _packageGraphFilePaths);
- foreach (string fileName in fileNames)
- {
- args.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(fileName));
- }
+ return _domainManager;
}
}
-
- // Called only by native function code:ValidateWorker
- private void EnableResolveAssembliesForIntrospection(string verifiedFileDirectory)
- {
- CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(ResolveAssemblyForIntrospection);
-
- string[] packageGraphFilePaths = null;
- if (verifiedFileDirectory != null)
- packageGraphFilePaths = new string[] { verifiedFileDirectory };
- NamespaceResolverForIntrospection namespaceResolver = new NamespaceResolverForIntrospection(packageGraphFilePaths);
-
- System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve +=
- new EventHandler<System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs>(namespaceResolver.ResolveNamespace);
- }
-#endif // FEATURE_REFLECTION_ONLY_LOAD
+
public ObjectHandle CreateInstance(String assemblyName,
String typeName)
-
+
{
// jit does not check for that, so we should do it ...
if (this == null)
@@ -722,7 +603,8 @@ namespace System
public static AppDomain CurrentDomain
{
- get {
+ get
+ {
Contract.Ensures(Contract.Result<AppDomain>() != null);
return Thread.GetDomain();
}
@@ -730,7 +612,8 @@ namespace System
public String BaseDirectory
{
- get {
+ get
+ {
return FusionStore.ApplicationBase;
}
}
@@ -740,26 +623,29 @@ namespace System
StringBuilder sb = StringBuilderCache.Acquire();
String fn = nGetFriendlyName();
- if (fn != null) {
- sb.Append(Environment.GetResourceString("Loader_Name") + fn);
+ if (fn != null)
+ {
+ sb.Append(SR.Loader_Name + fn);
sb.Append(Environment.NewLine);
}
- if(_Policies == null || _Policies.Length == 0)
- sb.Append(Environment.GetResourceString("Loader_NoContextPolicies")
+ if (_Policies == null || _Policies.Length == 0)
+ sb.Append(SR.Loader_NoContextPolicies
+ Environment.NewLine);
- else {
- sb.Append(Environment.GetResourceString("Loader_ContextPolicies")
+ else
+ {
+ sb.Append(SR.Loader_ContextPolicies
+ Environment.NewLine);
- for(int i = 0;i < _Policies.Length; i++) {
+ for (int i = 0; i < _Policies.Length; i++)
+ {
sb.Append(_Policies[i]);
sb.Append(Environment.NewLine);
}
}
-
+
return StringBuilderCache.GetStringAndRelease(sb);
}
-
+
// this is true when we've removed the handles etc so really can't do anything
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern bool IsUnloadingForcedFinalize();
@@ -772,22 +658,25 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void PublishAnonymouslyHostedDynamicMethodsAssembly(RuntimeAssembly assemblyHandle);
- public void SetData (string name, object data) {
+ public void SetData(string name, object data)
+ {
if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
// SetData should only be used to set values that don't already exist.
object currentVal;
- lock (((ICollection)LocalStore).SyncRoot) {
+ lock (((ICollection)LocalStore).SyncRoot)
+ {
LocalStore.TryGetValue(name, out currentVal);
}
if (currentVal != null)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_SetData_OnlyOnce"));
+ throw new InvalidOperationException(SR.InvalidOperation_SetData_OnlyOnce);
}
- lock (((ICollection)LocalStore).SyncRoot) {
+ lock (((ICollection)LocalStore).SyncRoot)
+ {
LocalStore[name] = data;
}
}
@@ -795,19 +684,20 @@ namespace System
[Pure]
public Object GetData(string name)
{
- if(name == null)
+ if (name == null)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
int key = AppDomainSetup.Locate(name);
- if(key == -1)
+ if (key == -1)
{
- if(name.Equals(AppDomainSetup.LoaderOptimizationKey))
+ if (name.Equals(AppDomainSetup.LoaderOptimizationKey))
return FusionStore.LoaderOptimization;
- else
+ else
{
object data;
- lock (((ICollection)LocalStore).SyncRoot) {
+ lock (((ICollection)LocalStore).SyncRoot)
+ {
LocalStore.TryGetValue(name, out data);
}
if (data == null)
@@ -815,27 +705,30 @@ namespace System
return data;
}
}
- else {
+ else
+ {
// Be sure to call these properties, not Value, so
// that the appropriate permission demand will be done
- switch(key) {
- case (int) AppDomainSetup.LoaderInformation.ApplicationBaseValue:
- return FusionStore.ApplicationBase;
- case (int) AppDomainSetup.LoaderInformation.ApplicationNameValue:
- return FusionStore.ApplicationName;
- default:
- Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
- return null;
+ switch (key)
+ {
+ case (int)AppDomainSetup.LoaderInformation.ApplicationBaseValue:
+ return FusionStore.ApplicationBase;
+ case (int)AppDomainSetup.LoaderInformation.ApplicationNameValue:
+ return FusionStore.ApplicationName;
+ default:
+ Debug.Assert(false, "Need to handle new LoaderInformation value in AppDomain.GetData()");
+ return null;
}
}
}
-
+
[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)]
public static extern int GetCurrentThreadId();
- private AppDomain() {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Constructor));
+ private AppDomain()
+ {
+ throw new NotSupportedException(SR.GetResourceString(ResId.NotSupported_Constructor));
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -866,13 +759,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_processExit += value;
}
}
remove
{
- lock(this)
+ lock (this)
_processExit -= value;
}
}
@@ -885,13 +778,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_domainUnload += value;
}
}
remove
{
- lock(this)
+ lock (this)
_domainUnload -= value;
}
}
@@ -904,13 +797,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_unhandledException += value;
}
}
remove
{
- lock(this)
+ lock (this)
_unhandledException -= value;
}
}
@@ -926,13 +819,13 @@ namespace System
if (value != null)
{
RuntimeHelpers.PrepareContractedDelegate(value);
- lock(this)
+ lock (this)
_firstChanceException += value;
}
}
remove
{
- lock(this)
+ lock (this)
_firstChanceException -= value;
}
}
@@ -940,22 +833,24 @@ namespace System
private void OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
{
AssemblyLoadEventHandler eventHandler = AssemblyLoad;
- if (eventHandler != null) {
+ if (eventHandler != null)
+ {
AssemblyLoadEventArgs ea = new AssemblyLoadEventArgs(LoadedAssembly);
eventHandler(this, ea);
}
}
-
+
// This method is called by the VM.
private RuntimeAssembly OnResourceResolveEvent(RuntimeAssembly assembly, String resourceName)
{
ResolveEventHandler eventHandler = _ResourceResolve;
- if ( eventHandler == null)
+ if (eventHandler == null)
return null;
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
- for (int i = 0; i < len; i++) {
+ for (int i = 0; i < len; i++)
+ {
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(resourceName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
@@ -964,7 +859,7 @@ namespace System
return null;
}
-
+
// This method is called by the VM
private RuntimeAssembly OnTypeResolveEvent(RuntimeAssembly assembly, String typeName)
{
@@ -974,7 +869,8 @@ namespace System
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
- for (int i = 0; i < len; i++) {
+ for (int i = 0; i < len; i++)
+ {
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(typeName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
@@ -996,13 +892,14 @@ namespace System
Delegate[] ds = eventHandler.GetInvocationList();
int len = ds.Length;
- for (int i = 0; i < len; i++) {
+ for (int i = 0; i < len; i++)
+ {
Assembly asm = ((ResolveEventHandler)ds[i])(this, new ResolveEventArgs(assemblyFullName, assembly));
RuntimeAssembly ret = GetRuntimeAssembly(asm);
if (ret != null)
return ret;
}
-
+
return null;
}
@@ -1016,8 +913,9 @@ namespace System
internal AppDomainSetup FusionStore
{
- get {
- Debug.Assert(_FusionStore != null,
+ get
+ {
+ Debug.Assert(_FusionStore != null,
"Fusion store has not been correctly setup in this domain");
return _FusionStore;
}
@@ -1041,10 +939,12 @@ namespace System
private Dictionary<String, Object> LocalStore
{
- get {
+ get
+ {
if (_LocalStore != null)
return _LocalStore;
- else {
+ else
+ {
_LocalStore = new Dictionary<String, Object>();
return _LocalStore;
}
@@ -1061,7 +961,7 @@ namespace System
if (info.ApplicationBase == null)
{
- info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized : true);
+ info.SetupDefaults(RuntimeEnvironment.GetModuleFileName(), imageLocationAlreadyNormalized: true);
}
nCreateContext();
@@ -1074,11 +974,11 @@ namespace System
private static void RunInitializer(AppDomainSetup setup)
{
- if (setup.AppDomainInitializer!=null)
+ if (setup.AppDomainInitializer != null)
{
- string[] args=null;
- if (setup.AppDomainInitializerArguments!=null)
- args=(string[])setup.AppDomainInitializerArguments.Clone();
+ string[] args = null;
+ if (setup.AppDomainInitializerArguments != null)
+ args = (string[])setup.AppDomainInitializerArguments.Clone();
setup.AppDomainInitializer(args);
}
}
@@ -1101,8 +1001,8 @@ namespace System
bool generateDefaultEvidence = false;
AppDomainInitializerInfo initializerInfo = null;
- if (setup!=null && setup.AppDomainInitializer!=null)
- initializerInfo=new AppDomainInitializerInfo(setup.AppDomainInitializer);
+ if (setup != null && setup.AppDomainInitializer != null)
+ initializerInfo = new AppDomainInitializerInfo(setup.AppDomainInitializer);
// will travel x-Ad, drop non-agile data
AppDomainSetup newSetup = new AppDomainSetup(setup, false);
@@ -1115,63 +1015,61 @@ namespace System
// System.AppDomainManager.CreateDomain() and add the flags to the AppDomainSetup
List<String> compatList = new List<String>();
- if(propertyNames!=null && propertyValues != null)
+ if (propertyNames != null && propertyValues != null)
{
- for (int i=0; i<propertyNames.Length; i++)
+ for (int i = 0; i < propertyNames.Length; i++)
{
- if(String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0)
+ if (String.Compare(propertyNames[i], "AppDomainCompatSwitch", StringComparison.OrdinalIgnoreCase) == 0)
{
compatList.Add(propertyValues[i]);
propertyNames[i] = null;
propertyValues[i] = null;
}
-
}
-
+
if (compatList.Count > 0)
{
newSetup.SetCompatibilitySwitches(compatList);
}
}
- return new Object[]
+ return new Object[]
{
- friendlyName,
- newSetup,
- parentSecurityDescriptor,
+ friendlyName,
+ newSetup,
+ parentSecurityDescriptor,
generateDefaultEvidence,
serializedEvidence,
initializerInfo,
sandboxName,
propertyNames,
propertyValues
- };
+ };
} // PrepareDataForSetup
- [MethodImplAttribute(MethodImplOptions.NoInlining)]
private static Object Setup(Object arg)
{
Contract.Requires(arg != null && arg is Object[]);
Contract.Requires(((Object[])arg).Length >= 8);
- Object[] args=(Object[])arg;
- String friendlyName = (String)args[0];
- AppDomainSetup setup = (AppDomainSetup)args[1];
- IntPtr parentSecurityDescriptor = (IntPtr)args[2];
- bool generateDefaultEvidence = (bool)args[3];
- byte[] serializedEvidence = (byte[])args[4];
- AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
- string sandboxName = (string)args[6];
- string[] propertyNames = (string[])args[7]; // can contain null elements
- string[] propertyValues = (string[])args[8]; // can contain null elements
+ Object[] args = (Object[])arg;
+ String friendlyName = (String)args[0];
+ AppDomainSetup setup = (AppDomainSetup)args[1];
+ IntPtr parentSecurityDescriptor = (IntPtr)args[2];
+ bool generateDefaultEvidence = (bool)args[3];
+ byte[] serializedEvidence = (byte[])args[4];
+ AppDomainInitializerInfo initializerInfo = (AppDomainInitializerInfo)args[5];
+ string sandboxName = (string)args[6];
+ string[] propertyNames = (string[])args[7]; // can contain null elements
+ string[] propertyValues = (string[])args[8]; // can contain null elements
// extract evidence
Evidence providedSecurityInfo = null;
Evidence creatorsSecurityInfo = null;
AppDomain ad = AppDomain.CurrentDomain;
- AppDomainSetup newSetup=new AppDomainSetup(setup,false);
+ AppDomainSetup newSetup = new AppDomainSetup(setup, false);
- if(propertyNames!=null && propertyValues != null)
+ if (propertyNames != null && propertyValues != null)
{
for (int i = 0; i < propertyNames.Length; i++)
{
@@ -1190,55 +1088,55 @@ namespace System
}
}
- for (int i=0; i<propertyNames.Length; i++)
+ for (int i = 0; i < propertyNames.Length; i++)
{
- if(propertyNames[i]=="APPBASE") // make sure in sync with Fusion
+ if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion
{
- if(propertyValues[i]==null)
+ if (propertyValues[i] == null)
throw new ArgumentNullException("APPBASE");
if (PathInternal.IsPartiallyQualified(propertyValues[i]))
- throw new ArgumentException( Environment.GetResourceString( "Argument_AbsolutePathRequired" ) );
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired);
newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true);
}
- else if(propertyNames[i]=="LOADER_OPTIMIZATION")
+ else if (propertyNames[i] == "LOADER_OPTIMIZATION")
{
- if(propertyValues[i]==null)
+ if (propertyValues[i] == null)
throw new ArgumentNullException("LOADER_OPTIMIZATION");
- switch(propertyValues[i])
+ switch (propertyValues[i])
{
- case "SingleDomain": newSetup.LoaderOptimization=LoaderOptimization.SingleDomain;break;
- case "MultiDomain": newSetup.LoaderOptimization=LoaderOptimization.MultiDomain;break;
- case "MultiDomainHost": newSetup.LoaderOptimization=LoaderOptimization.MultiDomainHost;break;
- case "NotSpecified": newSetup.LoaderOptimization=LoaderOptimization.NotSpecified;break;
- default: throw new ArgumentException(Environment.GetResourceString("Argument_UnrecognizedLoaderOptimization"), "LOADER_OPTIMIZATION");
+ case "SingleDomain": newSetup.LoaderOptimization = LoaderOptimization.SingleDomain; break;
+ case "MultiDomain": newSetup.LoaderOptimization = LoaderOptimization.MultiDomain; break;
+ case "MultiDomainHost": newSetup.LoaderOptimization = LoaderOptimization.MultiDomainHost; break;
+ case "NotSpecified": newSetup.LoaderOptimization = LoaderOptimization.NotSpecified; break;
+ default: throw new ArgumentException(SR.Argument_UnrecognizedLoaderOptimization, "LOADER_OPTIMIZATION");
}
}
- else if(propertyNames[i]=="TRUSTED_PLATFORM_ASSEMBLIES" ||
- propertyNames[i]=="PLATFORM_RESOURCE_ROOTS" ||
- propertyNames[i]=="APP_PATHS" ||
- propertyNames[i]=="APP_NI_PATHS")
+ else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" ||
+ propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" ||
+ propertyNames[i] == "APP_PATHS" ||
+ propertyNames[i] == "APP_NI_PATHS")
{
string values = propertyValues[i];
- if(values == null)
+ if (values == null)
throw new ArgumentNullException(propertyNames[i]);
ad.SetData(propertyNames[i], NormalizeAppPaths(values));
}
- else if(propertyNames[i]!= null)
+ else if (propertyNames[i] != null)
{
- ad.SetData(propertyNames[i],propertyValues[i]); // just propagate
+ ad.SetData(propertyNames[i], propertyValues[i]); // just propagate
}
}
}
ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup
-
+
// technically, we don't need this, newSetup refers to the same object as FusionStore
// but it's confusing since it isn't immediately obvious whether we have a ref or a copy
- AppDomainSetup adSetup = ad.FusionStore;
+ AppDomainSetup adSetup = ad.FusionStore;
adSetup.InternalSetApplicationTrust(sandboxName);
@@ -1264,10 +1162,10 @@ namespace System
generateDefaultEvidence,
parentSecurityDescriptor,
true);
-
+
// can load user code now
- if(initializerInfo!=null)
- adSetup.AppDomainInitializer=initializerInfo.Unwrap();
+ if (initializerInfo != null)
+ adSetup.AppDomainInitializer = initializerInfo.Unwrap();
RunInitializer(adSetup);
return null;
@@ -1299,7 +1197,7 @@ namespace System
continue;
if (PathInternal.IsPartiallyQualified(path))
- throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"));
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired);
string appPath = NormalizePath(path, fullCheck: true);
sb.Append(appPath);
@@ -1329,7 +1227,7 @@ namespace System
// (eg. one thread doing a com call and another doing attach for IJW)
lock (this)
{
- if(_FusionStore == null)
+ if (_FusionStore == null)
{
AppDomainSetup setup = new AppDomainSetup();
@@ -1349,7 +1247,6 @@ namespace System
JitHelpers.GetObjectHandleOnStack(ref stackEvidence),
creatorsSecurityDescriptor,
publishAppDomain);
-
}
[SuppressUnmanagedCodeSecurity]
@@ -1372,8 +1269,9 @@ namespace System
public AppDomainSetup SetupInformation
{
- get {
- return new AppDomainSetup(FusionStore,true);
+ get
+ {
+ return new AppDomainSetup(FusionStore, true);
}
}
@@ -1382,7 +1280,7 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern String GetOrInternString(String str);
-
+
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
private static extern void GetGrantSet(AppDomainHandle domain, ObjectHandleOnStack retGrantSet);
@@ -1407,14 +1305,14 @@ namespace System
public Int32 Id
{
- get {
+ get
+ {
return GetId();
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Int32 GetId();
-
}
/// <summary>
diff --git a/src/mscorlib/src/System/AppDomainAttributes.cs b/src/mscorlib/src/System/AppDomainAttributes.cs
index 960f9c1cac..deb43eadf9 100644
--- a/src/mscorlib/src/System/AppDomainAttributes.cs
+++ b/src/mscorlib/src/System/AppDomainAttributes.cs
@@ -11,19 +11,19 @@
**
=============================================================================*/
-namespace System {
-
+namespace System
+{
[Serializable]
- internal enum LoaderOptimization
+ internal enum LoaderOptimization
{
- NotSpecified = 0,
- SingleDomain = 1,
- MultiDomain = 2,
- MultiDomainHost = 3,
+ NotSpecified = 0,
+ SingleDomain = 1,
+ MultiDomain = 2,
+ MultiDomainHost = 3,
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- DomainMask = 3,
+ DomainMask = 3,
[Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- DisallowBindings = 4
+ DisallowBindings = 4
}
}
diff --git a/src/mscorlib/src/System/AppDomainManager.cs b/src/mscorlib/src/System/AppDomainManager.cs
index bd2faa0110..830de29c16 100644
--- a/src/mscorlib/src/System/AppDomainManager.cs
+++ b/src/mscorlib/src/System/AppDomainManager.cs
@@ -8,18 +8,18 @@
// participate in the creation and control the settings of new AppDomains.
//
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Security;
+using System.Runtime.InteropServices;
+
namespace System
{
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Security;
- using System.Runtime.InteropServices;
-
internal class AppDomainManager : MarshalByRefObject
{
- public AppDomainManager () {}
+ public AppDomainManager() { }
- public virtual void InitializeNewDomain (AppDomainSetup appDomainInfo)
+ public virtual void InitializeNewDomain(AppDomainSetup appDomainInfo)
{
// By default, InitializeNewDomain does nothing. AppDomain.CreateAppDomainManager relies on this fact.
}
@@ -28,8 +28,10 @@ namespace System
private static extern void GetEntryAssembly(ObjectHandleOnStack retAssembly);
private Assembly m_entryAssembly = null;
- public virtual Assembly EntryAssembly {
- get {
+ public virtual Assembly EntryAssembly
+ {
+ get
+ {
// The default AppDomainManager sets the EntryAssembly depending on whether the
// AppDomain is a manifest application domain or not. In the first case, we parse
// the application manifest to find out the entry point assembly and return that assembly.
@@ -46,15 +48,12 @@ namespace System
}
}
- internal static AppDomainManager CurrentAppDomainManager {
- get {
+ internal static AppDomainManager CurrentAppDomainManager
+ {
+ get
+ {
return AppDomain.CurrentDomain.DomainManager;
}
}
-
- public virtual bool CheckSecuritySettings (SecurityState state)
- {
- return false;
- }
}
}
diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs
index 0d19ad237f..142b8a05f7 100644
--- a/src/mscorlib/src/System/AppDomainSetup.cs
+++ b/src/mscorlib/src/System/AppDomainSetup.cs
@@ -4,15 +4,12 @@
/*=============================================================================
**
-** Class: AppDomainSetup
**
** Purpose: Defines the settings that the loader uses to find assemblies in an
** AppDomain
**
-** Date: Dec 22, 2000
**
=============================================================================*/
-
namespace System
{
using System.Text;
@@ -34,49 +31,29 @@ namespace System
// If you add a new value, add the corresponding property
// to AppDomain.GetData() and SetData()'s switch statements,
// as well as fusionsetup.h.
- ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE
- ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE
- DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE
- DevPathValue = 3, // LOADER_DEVPATH
- ApplicationNameValue = 4, // LOADER_APPLICATION_NAME
- PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH
- PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE
- ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES
- ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES
- CachePathValue = 9, // LOADER_CACHE_PATH
- LicenseFileValue = 10, // LOADER_LICENSE_FILE
- DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY
- DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD
+ ApplicationBaseValue = 0, // LOADER_APPLICATION_BASE
+ ConfigurationFileValue = 1, // LOADER_CONFIGURATION_BASE
+ DynamicBaseValue = 2, // LOADER_DYNAMIC_BASE
+ DevPathValue = 3, // LOADER_DEVPATH
+ ApplicationNameValue = 4, // LOADER_APPLICATION_NAME
+ PrivateBinPathValue = 5, // LOADER_PRIVATE_PATH
+ PrivateBinPathProbeValue = 6, // LOADER_PRIVATE_BIN_PATH_PROBE
+ ShadowCopyDirectoriesValue = 7, // LOADER_SHADOW_COPY_DIRECTORIES
+ ShadowCopyFilesValue = 8, // LOADER_SHADOW_COPY_FILES
+ CachePathValue = 9, // LOADER_CACHE_PATH
+ LicenseFileValue = 10, // LOADER_LICENSE_FILE
+ DisallowPublisherPolicyValue = 11, // LOADER_DISALLOW_PUBLISHER_POLICY
+ DisallowCodeDownloadValue = 12, // LOADER_DISALLOW_CODE_DOWNLOAD
DisallowBindingRedirectsValue = 13, // LOADER_DISALLOW_BINDING_REDIRECTS
- DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING
- ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES
- LoaderMaximum = 18 // LOADER_MAXIMUM
+ DisallowAppBaseProbingValue = 14, // LOADER_DISALLOW_APPBASE_PROBING
+ ConfigurationBytesValue = 15, // LOADER_CONFIGURATION_BYTES
+ LoaderMaximum = 18 // LOADER_MAXIMUM
}
-
+
// Constants from fusionsetup.h.
private const string LOADER_OPTIMIZATION = "LOADER_OPTIMIZATION";
- private const string CONFIGURATION_EXTENSION = ".config";
- private const string APPENV_RELATIVEPATH = "RELPATH";
- private const string MACHINE_CONFIGURATION_FILE = "config\\machine.config";
- private const string ACTAG_HOST_CONFIG_FILE = "HOST_CONFIG";
-
- // Constants from fusionpriv.h
- private const string ACTAG_APP_CONFIG_FILE = "APP_CONFIG_FILE";
- private const string ACTAG_MACHINE_CONFIG = "MACHINE_CONFIG";
+
private const string ACTAG_APP_BASE_URL = "APPBASE";
- private const string ACTAG_APP_NAME = "APP_NAME";
- private const string ACTAG_BINPATH_PROBE_ONLY = "BINPATH_PROBE_ONLY";
- private const string ACTAG_APP_CACHE_BASE = "CACHE_BASE";
- private const string ACTAG_DEV_PATH = "DEV_PATH";
- private const string ACTAG_APP_DYNAMIC_BASE = "DYNAMIC_BASE";
- private const string ACTAG_FORCE_CACHE_INSTALL = "FORCE_CACHE_INSTALL";
- private const string ACTAG_APP_PRIVATE_BINPATH = "PRIVATE_BINPATH";
- private const string ACTAG_APP_SHADOW_COPY_DIRS = "SHADOW_COPY_DIRS";
- private const string ACTAG_DISALLOW_APPLYPUBLISHERPOLICY = "DISALLOW_APP";
- private const string ACTAG_CODE_DOWNLOAD_DISABLED = "CODE_DOWNLOAD_DISABLED";
- private const string ACTAG_DISALLOW_APP_BINDING_REDIRECTS = "DISALLOW_APP_REDIRECTS";
- private const string ACTAG_DISALLOW_APP_BASE_PROBING = "DISALLOW_APP_BASE_PROBING";
- private const string ACTAG_APP_CONFIG_BLOB = "APP_CONFIG_BLOB";
// This class has an unmanaged representation so be aware you will need to make edits in vm\object.h if you change the order
// of these fields or add new ones.
@@ -87,7 +64,7 @@ namespace System
private String _AppBase; // for compat with v1.1
#pragma warning restore 169
[OptionalField(VersionAdded = 2)]
- private AppDomainInitializer _AppDomainInitializer;
+ private AppDomainInitializer _AppDomainInitializer;
[OptionalField(VersionAdded = 2)]
private string[] _AppDomainInitializerArguments;
@@ -125,7 +102,8 @@ namespace System
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
- if(copy != null) {
+ if (copy != null)
+ {
string[] other = copy.Value;
int mineSize = _Entries.Length;
int otherSize = other.Length;
@@ -152,7 +130,7 @@ namespace System
else
_AppDomainInitializer = null;
- _ConfigurationBytes = copy.GetConfigurationBytes();
+ _ConfigurationBytes = null;
#if FEATURE_COMINTEROP
_DisableInterfaceCache = copy._DisableInterfaceCache;
#endif // FEATURE_COMINTEROP
@@ -171,7 +149,7 @@ namespace System
#endif
}
- else
+ else
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
@@ -180,39 +158,37 @@ namespace System
_LoaderOptimization = LoaderOptimization.NotSpecified;
}
- internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false) {
- char[] sep = {'\\', '/'};
+ internal void SetupDefaults(string imageLocation, bool imageLocationAlreadyNormalized = false)
+ {
+ char[] sep = { '\\', '/' };
int i = imageLocation.LastIndexOfAny(sep);
- if (i == -1) {
+ if (i == -1)
+ {
ApplicationName = imageLocation;
}
- else {
- ApplicationName = imageLocation.Substring(i+1);
- string appBase = imageLocation.Substring(0, i+1);
+ else
+ {
+ ApplicationName = imageLocation.Substring(i + 1);
+ string appBase = imageLocation.Substring(0, i + 1);
if (imageLocationAlreadyNormalized)
- Value[(int) LoaderInformation.ApplicationBaseValue] = appBase;
- else
+ Value[(int)LoaderInformation.ApplicationBaseValue] = appBase;
+ else
ApplicationBase = appBase;
}
- ConfigurationFile = ApplicationName + AppDomainSetup.ConfigurationExtension;
}
internal string[] Value
{
- get {
- if( _Entries == null)
+ get
+ {
+ if (_Entries == null)
_Entries = new String[(int)LoaderInformation.LoaderMaximum];
return _Entries;
}
}
- internal String GetUnsecureApplicationBase()
- {
- return Value[(int) LoaderInformation.ApplicationBaseValue];
- }
-
public string AppDomainManagerAssembly
{
get { return _AppDomainManagerAssembly; }
@@ -228,233 +204,17 @@ namespace System
public String ApplicationBase
{
[Pure]
- get {
- return VerifyDir(GetUnsecureApplicationBase(), false);
- }
-
- set {
- Value[(int) LoaderInformation.ApplicationBaseValue] = NormalizePath(value, false);
- }
- }
-
- private String NormalizePath(String path, bool useAppBase)
- {
- if(path == null)
- return null;
-
- // If we add very long file name support ("\\?\") to the Path class then this is unnecesary,
- // but we do not plan on doing this for now.
-
- // Long path checks can be quirked, and as loading default quirks too early in the setup of an AppDomain is risky
- // we'll avoid checking path lengths- we'll still fail at MAX_PATH later if we're !useAppBase when we call Path's
- // NormalizePath.
- if (!useAppBase)
- path = Security.Util.URLString.PreProcessForExtendedPathRemoval(
- checkPathLength: false,
- url: path,
- isFileUrl: false);
-
-
- int len = path.Length;
- if (len == 0)
- return null;
-
-#if !PLATFORM_UNIX
- bool UNCpath = false;
-#endif // !PLATFORM_UNIX
-
- if ((len > 7) &&
- (String.Compare( path, 0, "file:", 0, 5, StringComparison.OrdinalIgnoreCase) == 0)) {
- int trim;
-
- if (path[6] == '\\') {
- if ((path[7] == '\\') || (path[7] == '/')) {
-
- // Don't allow "file:\\\\", because we can't tell the difference
- // with it for "file:\\" + "\\server" and "file:\\\" + "\localpath"
- if ( (len > 8) &&
- ((path[8] == '\\') || (path[8] == '/')) )
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
-
- // file:\\\ means local path
- else
-#if !PLATFORM_UNIX
- trim = 8;
-#else
- // For Unix platform, trim the first 7 charcaters only.
- // Trimming the first 8 characters will cause
- // the root path separator to be trimmed away,
- // and the absolute local path becomes a relative local path.
- trim = 7;
-#endif // !PLATFORM_UNIX
- }
-
- // file:\\ means remote server
- else {
- trim = 5;
-#if !PLATFORM_UNIX
- UNCpath = true;
-#endif // !PLATFORM_UNIX
- }
- }
-
- // local path
- else if (path[7] == '/')
-#if !PLATFORM_UNIX
- trim = 8;
-#else
- // For Unix platform, trim the first 7 characters only.
- // Trimming the first 8 characters will cause
- // the root path separator to be trimmed away,
- // and the absolute local path becomes a relative local path.
- trim = 7;
-#endif // !PLATFORM_UNIX
-
- // remote
- else {
- // file://\\remote
- if ( (len > 8) && (path[7] == '\\') && (path[8] == '\\') )
- trim = 7;
- else { // file://remote
- trim = 5;
-#if !PLATFORM_UNIX
- // Create valid UNC path by changing
- // all occurences of '/' to '\\' in path
- System.Text.StringBuilder winPathBuilder =
- new System.Text.StringBuilder(len);
- for (int i = 0; i < len; i++) {
- char c = path[i];
- if (c == '/')
- winPathBuilder.Append('\\');
- else
- winPathBuilder.Append(c);
- }
- path = winPathBuilder.ToString();
-#endif // !PLATFORM_UNIX
- }
-#if !PLATFORM_UNIX
- UNCpath = true;
-#endif // !PLATFORM_UNIX
- }
-
- path = path.Substring(trim);
- len -= trim;
- }
-
-#if !PLATFORM_UNIX
- bool localPath;
-
- // UNC
- if (UNCpath ||
- ( (len > 1) &&
- ( (path[0] == '/') || (path[0] == '\\') ) &&
- ( (path[1] == '/') || (path[1] == '\\') ) ))
- localPath = false;
-
- else {
- int colon = path.IndexOf(':') + 1;
-
- // protocol other than file:
- if ((colon != 0) &&
- (len > colon+1) &&
- ( (path[colon] == '/') || (path[colon] == '\\') ) &&
- ( (path[colon+1] == '/') || (path[colon+1] == '\\') ))
- localPath = false;
-
- else
- localPath = true;
- }
-
- if (localPath)
-#else
- if ( (len == 1) ||
- ( (path[0] != '/') && (path[0] != '\\') ) )
-#endif // !PLATFORM_UNIX
+ get
{
-
- if (useAppBase &&
- ( (len == 1) || (path[1] != ':') )) {
- String appBase = Value[(int) LoaderInformation.ApplicationBaseValue];
-
- if ((appBase == null) || (appBase.Length == 0))
- throw new MemberAccessException(Environment.GetResourceString("AppDomain_AppBaseNotSet"));
-
- StringBuilder result = StringBuilderCache.Acquire();
-
- bool slash = false;
- if ((path[0] == '/') || (path[0] == '\\')) {
- string pathRoot = AppDomain.NormalizePath(appBase, fullCheck: false);
- pathRoot = pathRoot.Substring(0, IO.PathInternal.GetRootLength(pathRoot));
-
- if (pathRoot.Length == 0) { // URL
- int index = appBase.IndexOf(":/", StringComparison.Ordinal);
- if (index == -1)
- index = appBase.IndexOf(":\\", StringComparison.Ordinal);
-
- // Get past last slashes of "url:http://"
- int urlLen = appBase.Length;
- for (index += 1;
- (index < urlLen) && ((appBase[index] == '/') || (appBase[index] == '\\'));
- index++);
-
- // Now find the next slash to get domain name
- for(; (index < urlLen) && (appBase[index] != '/') && (appBase[index] != '\\');
- index++);
-
- pathRoot = appBase.Substring(0, index);
- }
-
- result.Append(pathRoot);
- slash = true;
- }
- else
- result.Append(appBase);
-
- // Make sure there's a slash separator (and only one)
- int aLen = result.Length - 1;
- if ((result[aLen] != '/') &&
- (result[aLen] != '\\')) {
- if (!slash) {
-#if !PLATFORM_UNIX
- if (appBase.IndexOf(":/", StringComparison.Ordinal) == -1)
- result.Append('\\');
- else
-#endif // !PLATFORM_UNIX
- result.Append('/');
- }
- }
- else if (slash)
- result.Remove(aLen, 1);
-
- result.Append(path);
- path = StringBuilderCache.GetStringAndRelease(result);
- }
- else
- path = AppDomain.NormalizePath(path, fullCheck: true);
+ return Value[(int)LoaderInformation.ApplicationBaseValue];
}
- return path;
- }
-
- public String ConfigurationFile
- {
- get {
- return VerifyDir(Value[(int) LoaderInformation.ConfigurationFileValue], true);
- }
-
- set {
- Value[(int) LoaderInformation.ConfigurationFileValue] = value;
+ set
+ {
+ Value[(int)LoaderInformation.ApplicationBaseValue] = (value == null || value.Length == 0)?null:Path.GetFullPath(value);
}
}
-
- public byte[] GetConfigurationBytes()
- {
- if (_ConfigurationBytes == null)
- return null;
-
- return (byte[]) _ConfigurationBytes.Clone();
- }
-
+
// only needed by AppDomain.Setup(). Not really needed by users.
internal Dictionary<string, object> GetCompatibilityFlags()
{
@@ -469,10 +229,11 @@ namespace System
if (switches != null)
{
_CompatFlags = new Dictionary<string, object>();
- foreach (String str in switches)
+ foreach (String str in switches)
{
#if FEATURE_RANDOMIZED_STRING_HASHING
- if(StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str)) {
+ if (StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str))
+ {
_UseRandomizedStringHashing = true;
}
#endif
@@ -483,62 +244,55 @@ namespace System
{
_CompatFlags = null;
}
-
}
// A target Framework moniker, in a format parsible by the FrameworkName class.
- public String TargetFrameworkName {
- get {
+ public String TargetFrameworkName
+ {
+ get
+ {
return _TargetFrameworkName;
}
- set {
+ set
+ {
_TargetFrameworkName = value;
}
}
- private String VerifyDir(String dir, bool normalize)
- {
- if (dir != null) {
- if (dir.Length == 0)
- dir = null;
- else {
- if (normalize)
- dir = NormalizePath(dir, true);
- }
- }
-
- return dir;
- }
-
public String ApplicationName
{
- get {
- return Value[(int) LoaderInformation.ApplicationNameValue];
+ get
+ {
+ return Value[(int)LoaderInformation.ApplicationNameValue];
}
- set {
- Value[(int) LoaderInformation.ApplicationNameValue] = value;
+ set
+ {
+ Value[(int)LoaderInformation.ApplicationNameValue] = value;
}
}
- [XmlIgnoreMember]
public AppDomainInitializer AppDomainInitializer
{
- get {
+ get
+ {
return _AppDomainInitializer;
}
- set {
+ set
+ {
_AppDomainInitializer = value;
}
}
public string[] AppDomainInitializerArguments
{
- get {
+ get
+ {
return _AppDomainInitializerArguments;
}
- set {
+ set
+ {
_AppDomainInitializerArguments = value;
}
}
@@ -555,7 +309,6 @@ namespace System
_ApplicationTrust = permissionSetName;
}
- [XmlIgnoreMember]
internal ApplicationTrust ApplicationTrust
{
get
@@ -566,36 +319,32 @@ namespace System
public LoaderOptimization LoaderOptimization
{
- get {
+ get
+ {
return _LoaderOptimization;
}
- set {
+ set
+ {
_LoaderOptimization = value;
}
}
internal static string LoaderOptimizationKey
{
- get {
+ get
+ {
return LOADER_OPTIMIZATION;
}
}
- internal static string ConfigurationExtension
- {
- get {
- return CONFIGURATION_EXTENSION;
- }
- }
-
static internal int Locate(String s)
{
- if(String.IsNullOrEmpty(s))
+ if (String.IsNullOrEmpty(s))
return -1;
- Debug.Assert('A' == ACTAG_APP_BASE_URL[0] , "Assumption violated");
- if (s[0]=='A' && s == ACTAG_APP_BASE_URL)
+ Debug.Assert('A' == ACTAG_APP_BASE_URL[0], "Assumption violated");
+ if (s[0] == 'A' && s == ACTAG_APP_BASE_URL)
return (int)LoaderInformation.ApplicationBaseValue;
return -1;
diff --git a/src/mscorlib/src/System/AppDomainUnloadedException.cs b/src/mscorlib/src/System/AppDomainUnloadedException.cs
index 30bee7c7de..52cbb980af 100644
--- a/src/mscorlib/src/System/AppDomainUnloadedException.cs
+++ b/src/mscorlib/src/System/AppDomainUnloadedException.cs
@@ -11,21 +11,25 @@
**
=============================================================================*/
-namespace System {
- using System.Runtime.Serialization;
+using System.Runtime.Serialization;
+namespace System
+{
[Serializable]
- internal class AppDomainUnloadedException : SystemException {
- public AppDomainUnloadedException()
- : base(Environment.GetResourceString("Arg_AppDomainUnloadedException")) {
- SetErrorCode(__HResults.COR_E_APPDOMAINUNLOADED);
+ internal class AppDomainUnloadedException : SystemException
+ {
+ public AppDomainUnloadedException()
+ : base(SR.Arg_AppDomainUnloadedException)
+ {
+ HResult = __HResults.COR_E_APPDOMAINUNLOADED;
}
//
//This constructor is required for serialization.
//
- protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/ApplicationException.cs b/src/mscorlib/src/System/ApplicationException.cs
deleted file mode 100644
index 900feb57f9..0000000000
--- a/src/mscorlib/src/System/ApplicationException.cs
+++ /dev/null
@@ -1,56 +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 base class for all "less serious" exceptions that must be
-** declared or caught.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The ApplicationException is the base class for nonfatal,
- // application errors that occur. These exceptions are generated
- // (i.e., thrown) by an application, not the Runtime. Applications that need
- // to create their own exceptions do so by extending this class.
- // ApplicationException extends but adds no new functionality to
- // RecoverableException.
- //
- [Serializable]
- public class ApplicationException : Exception
- {
- // Creates a new ApplicationException with its message string set to
- // the empty string, its HRESULT set to COR_E_APPLICATION,
- // and its ExceptionInfo reference set to null.
- public ApplicationException()
- : base(SR.Arg_ApplicationException)
- {
- HResult = __HResults.COR_E_APPLICATION;
- }
-
- // Creates a new ApplicationException with its message string set to
- // message, its HRESULT set to COR_E_APPLICATION,
- // and its ExceptionInfo reference set to null.
- //
- public ApplicationException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_APPLICATION;
- }
-
- public ApplicationException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_APPLICATION;
- }
-
- protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/ArgIterator.cs b/src/mscorlib/src/System/ArgIterator.cs
index 83a60b95e1..584f85fbd3 100644
--- a/src/mscorlib/src/System/ArgIterator.cs
+++ b/src/mscorlib/src/System/ArgIterator.cs
@@ -2,8 +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.
-namespace System {
-
+namespace System
+{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -24,10 +24,10 @@ namespace System {
// Note, sigPtrLen is actually a DWORD, but on 64bit systems this structure becomes
// 8-byte aligned, which requires us to pad it.
-
+
private IntPtr ArgPtr; // Pointer to remaining args.
- private int RemainingArgs; // # of remaining args.
-
+ private int RemainingArgs; // # of remaining args.
+
#if VARARGS_ENABLED //The JIT doesn't support Varargs calling convention.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern ArgIterator(IntPtr arglist);
@@ -131,55 +131,55 @@ namespace System {
// Inherited from object
public override bool Equals(Object o)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI"));
+ throw new NotSupportedException(SR.NotSupported_NYI);
}
#else
public ArgIterator(RuntimeArgumentHandle arglist)
{
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
[CLSCompliant(false)]
public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr)
{
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
- public void End()
- {
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ public void End()
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
- public override bool Equals(Object o)
- {
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ public override bool Equals(Object o)
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
public override int GetHashCode()
- {
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
[System.CLSCompliantAttribute(false)]
public System.TypedReference GetNextArg()
{
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
[System.CLSCompliantAttribute(false)]
public System.TypedReference GetNextArg(System.RuntimeTypeHandle rth)
{
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
public unsafe System.RuntimeTypeHandle GetNextArgType()
{
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
public int GetRemainingCount()
- {
- throw new PlatformNotSupportedException(); //The JIT requires work to enable ArgIterator see: https://github.com/dotnet/coreclr/issues/9204.
+ {
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ArgIterator); // https://github.com/dotnet/coreclr/issues/9204
}
#endif //VARARGS_ENABLED
}
diff --git a/src/mscorlib/src/System/ArgumentException.cs b/src/mscorlib/src/System/ArgumentException.cs
deleted file mode 100644
index fe054a9aa0..0000000000
--- a/src/mscorlib/src/System/ArgumentException.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.
-
-/*=============================================================================
-**
-**
-**
-** Purpose: Exception class for invalid arguments to a method.
-**
-**
-=============================================================================*/
-
-using System.Globalization;
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The ArgumentException is thrown when an argument does not meet
- // the contract of the method. Ideally it should give a meaningful error
- // message describing what was wrong and which parameter is incorrect.
- //
- [Serializable]
- public class ArgumentException : SystemException, ISerializable
- {
- private String _paramName;
-
- // Creates a new ArgumentException with its message
- // string set to the empty string.
- public ArgumentException()
- : base(SR.Arg_ArgumentException)
- {
- HResult = __HResults.COR_E_ARGUMENT;
- }
-
- // Creates a new ArgumentException with its message
- // string set to message.
- //
- public ArgumentException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_ARGUMENT;
- }
-
- public ArgumentException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_ARGUMENT;
- }
-
- public ArgumentException(String message, String paramName, Exception innerException)
- : base(message, innerException)
- {
- _paramName = paramName;
- HResult = __HResults.COR_E_ARGUMENT;
- }
-
- public ArgumentException(String message, String paramName)
- : base(message)
- {
- _paramName = paramName;
- HResult = __HResults.COR_E_ARGUMENT;
- }
-
- protected ArgumentException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- _paramName = info.GetString("ParamName");
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
- info.AddValue("ParamName", _paramName, typeof(String));
- }
-
- public override String Message
- {
- get
- {
- String s = base.Message;
- if (!String.IsNullOrEmpty(_paramName))
- {
- String resourceString = SR.Format(SR.Arg_ParamName_Name, _paramName);
- return s + Environment.NewLine + resourceString;
- }
- else
- return s;
- }
- }
-
- public virtual String ParamName
- {
- get { return _paramName; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/ArgumentNullException.cs b/src/mscorlib/src/System/ArgumentNullException.cs
deleted file mode 100644
index 3a86223ccf..0000000000
--- a/src/mscorlib/src/System/ArgumentNullException.cs
+++ /dev/null
@@ -1,53 +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 class for null arguments to a method.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The ArgumentException is thrown when an argument
- // is null when it shouldn't be.
- //
- [Serializable]
- public class ArgumentNullException : ArgumentException
- {
- // Creates a new ArgumentNullException with its message
- // string set to a default message explaining an argument was null.
- public ArgumentNullException()
- : base(SR.ArgumentNull_Generic)
- {
- // Use E_POINTER - COM used that for null pointers. Description is "invalid pointer"
- HResult = __HResults.E_POINTER;
- }
-
- public ArgumentNullException(String paramName)
- : base(SR.ArgumentNull_Generic, paramName)
- {
- HResult = __HResults.E_POINTER;
- }
-
- public ArgumentNullException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.E_POINTER;
- }
-
- public ArgumentNullException(String paramName, String message)
- : base(message, paramName)
- {
- HResult = __HResults.E_POINTER;
- }
-
- protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
index 59a8434089..90837810d1 100644
--- a/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
+++ b/src/mscorlib/src/System/ArgumentOutOfRangeException.cs
@@ -11,92 +11,107 @@
**
=============================================================================*/
-namespace System {
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
+using System;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// The ArgumentOutOfRangeException is thrown when an argument
// is outside the legal range for that argument.
[Serializable]
- public class ArgumentOutOfRangeException : ArgumentException, ISerializable {
-
+ public class ArgumentOutOfRangeException : ArgumentException, ISerializable
+ {
private static volatile String _rangeMessage;
private Object m_actualValue;
- private static String RangeMessage {
- get {
+ private static String RangeMessage
+ {
+ get
+ {
if (_rangeMessage == null)
- _rangeMessage = Environment.GetResourceString("Arg_ArgumentOutOfRangeException");
+ _rangeMessage = SR.Arg_ArgumentOutOfRangeException;
return _rangeMessage;
}
}
// Creates a new ArgumentOutOfRangeException with its message
// string set to a default message explaining an argument was out of range.
- public ArgumentOutOfRangeException()
- : base(RangeMessage) {
- SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
+ public ArgumentOutOfRangeException()
+ : base(RangeMessage)
+ {
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
}
-
- public ArgumentOutOfRangeException(String paramName)
- : base(RangeMessage, paramName) {
- SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
+
+ public ArgumentOutOfRangeException(String paramName)
+ : base(RangeMessage, paramName)
+ {
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
}
-
- public ArgumentOutOfRangeException(String paramName, String message)
- : base(message, paramName) {
- SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
+
+ public ArgumentOutOfRangeException(String paramName, String message)
+ : base(message, paramName)
+ {
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
}
- public ArgumentOutOfRangeException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
+ public ArgumentOutOfRangeException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
}
-
+
// We will not use this in the classlibs, but we'll provide it for
// anyone that's really interested so they don't have to stick a bunch
// of printf's in their code.
- public ArgumentOutOfRangeException(String paramName, Object actualValue, String message)
- : base(message, paramName) {
+ public ArgumentOutOfRangeException(String paramName, Object actualValue, String message)
+ : base(message, paramName)
+ {
m_actualValue = actualValue;
- SetErrorCode(__HResults.COR_E_ARGUMENTOUTOFRANGE);
+ HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
}
-
- public override String Message {
- get {
+
+ public override String Message
+ {
+ get
+ {
String s = base.Message;
- if (m_actualValue != null) {
- String valueMessage = Environment.GetResourceString("ArgumentOutOfRange_ActualValue", m_actualValue.ToString());
+ if (m_actualValue != null)
+ {
+ String valueMessage = SR.Format(SR.ArgumentOutOfRange_ActualValue, m_actualValue.ToString());
if (s == null)
return valueMessage;
- return s + Environment.NewLine + valueMessage;
+ return s + Environment.NewLine + valueMessage;
}
return s;
}
}
-
+
// Gets the value of the argument that caused the exception.
// Note - we don't set this anywhere in the class libraries in
// version 1, but it might come in handy for other developers who
// want to avoid sticking printf's in their code.
- public virtual Object ActualValue {
+ public virtual Object ActualValue
+ {
get { return m_actualValue; }
}
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
base.GetObjectData(info, context);
info.AddValue("ActualValue", m_actualValue, typeof(Object));
}
-
- protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) {
+
+ protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
m_actualValue = info.GetValue("ActualValue", typeof(Object));
}
}
diff --git a/src/mscorlib/src/System/ArithmeticException.cs b/src/mscorlib/src/System/ArithmeticException.cs
deleted file mode 100644
index 081ba454f5..0000000000
--- a/src/mscorlib/src/System/ArithmeticException.cs
+++ /dev/null
@@ -1,51 +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 class for bad arithmetic conditions!
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The ArithmeticException is thrown when overflow or underflow
- // occurs.
- //
- [Serializable]
- public class ArithmeticException : SystemException
- {
- // Creates a new ArithmeticException with its message string set to
- // the empty string, its HRESULT set to COR_E_ARITHMETIC,
- // and its ExceptionInfo reference set to null.
- public ArithmeticException()
- : base(SR.Arg_ArithmeticException)
- {
- HResult = __HResults.COR_E_ARITHMETIC;
- }
-
- // Creates a new ArithmeticException with its message string set to
- // message, its HRESULT set to COR_E_ARITHMETIC,
- // and its ExceptionInfo reference set to null.
- //
- public ArithmeticException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_ARITHMETIC;
- }
-
- public ArithmeticException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_ARITHMETIC;
- }
-
- protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs
index 23989f30fb..05c4804cc5 100644
--- a/src/mscorlib/src/System/Array.cs
+++ b/src/mscorlib/src/System/Array.cs
@@ -8,32 +8,35 @@
** Purpose: Base class which can be used to access any array
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
+using System.Security;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// Note that we make a T[] (single-dimensional w/ zero as the lower bound) implement both
// IList<U> and IReadOnlyList<U>, where T : U dynamically. See the SZArrayHelper class for details.
[Serializable]
- public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
+ public abstract class Array : ICloneable, IList, IStructuralComparable, IStructuralEquatable
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
// "protected-and-internal" rather than "internal" but C# has no keyword for the former.
- internal Array() {}
+ internal Array() { }
- public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array) {
- if (array == null) {
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ public static ReadOnlyCollection<T> AsReadOnly<T>(T[] array)
+ {
+ if (array == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
@@ -41,22 +44,25 @@ namespace System {
return new ReadOnlyCollection<T>(array);
}
- public static void Resize<T>(ref T[] array, int newSize) {
+ public static void Resize<T>(ref T[] array, int newSize)
+ {
if (newSize < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Contract.Ensures(Contract.ValueAtReturn(out array) != null);
Contract.Ensures(Contract.ValueAtReturn(out array).Length == newSize);
Contract.EndContractBlock();
- T[] larray = array;
- if (larray == null) {
+ T[] larray = array;
+ if (larray == null)
+ {
array = new T[newSize];
return;
}
-
- if (larray.Length != newSize) {
+
+ if (larray.Length != newSize)
+ {
T[] newArray = new T[newSize];
- Array.Copy(larray, 0, newArray, 0, larray.Length > newSize? newSize : larray.Length);
+ Array.Copy(larray, 0, newArray, 0, larray.Length > newSize ? newSize : larray.Length);
array = newArray;
}
}
@@ -76,9 +82,9 @@ namespace System {
RuntimeType t = elementType.UnderlyingSystemType as RuntimeType;
if (t == null)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType);
- return InternalCreate((void*)t.TypeHandle.Value,1,&length,null);
+ return InternalCreate((void*)t.TypeHandle.Value, 1, &length, null);
}
-
+
public unsafe static Array CreateInstance(Type elementType, int length1, int length2)
{
if ((object)elementType == null)
@@ -98,9 +104,9 @@ namespace System {
int* pLengths = stackalloc int[2];
pLengths[0] = length1;
pLengths[1] = length2;
- return InternalCreate((void*)t.TypeHandle.Value,2,pLengths,null);
+ return InternalCreate((void*)t.TypeHandle.Value, 2, pLengths, null);
}
-
+
public unsafe static Array CreateInstance(Type elementType, int length1, int length2, int length3)
{
if ((object)elementType == null)
@@ -124,9 +130,9 @@ namespace System {
pLengths[0] = length1;
pLengths[1] = length2;
pLengths[2] = length3;
- return InternalCreate((void*)t.TypeHandle.Value,3,pLengths,null);
+ return InternalCreate((void*)t.TypeHandle.Value, 3, pLengths, null);
}
-
+
public unsafe static Array CreateInstance(Type elementType, params int[] lengths)
{
if ((object)elementType == null)
@@ -152,12 +158,13 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
fixed (int* pLengths = &lengths[0])
- return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,null);
+ return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, null);
}
public static Array CreateInstance(Type elementType, params long[] lengths)
{
- if( lengths == null) {
+ if (lengths == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths);
}
if (lengths.Length == 0)
@@ -165,22 +172,22 @@ namespace System {
Contract.Ensures(Contract.Result<Array>() != null);
Contract.Ensures(Contract.Result<Array>().Rank == lengths.Length);
Contract.EndContractBlock();
-
+
int[] intLengths = new int[lengths.Length];
- for (int i = 0; i < lengths.Length; ++i)
+ for (int i = 0; i < lengths.Length; ++i)
{
long len = lengths[i];
if (len > Int32.MaxValue || len < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.len, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- intLengths[i] = (int) len;
+ intLengths[i] = (int)len;
}
return Array.CreateInstance(elementType, intLengths);
}
-
- public unsafe static Array CreateInstance(Type elementType, int[] lengths,int[] lowerBounds)
+
+ public unsafe static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds)
{
if (elementType == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType);
@@ -204,17 +211,17 @@ namespace System {
// a good exception message if they are not; however we check this again inside the execution
// engine's low level allocation function after having made a copy of the array to prevent a
// malicious caller from mutating the array after this check.
- for (int i=0;i<lengths.Length;i++)
+ for (int i = 0; i < lengths.Length; i++)
if (lengths[i] < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
fixed (int* pLengths = &lengths[0])
- fixed(int* pLowerBounds = &lowerBounds[0])
- return InternalCreate((void*)t.TypeHandle.Value,lengths.Length,pLengths,pLowerBounds);
+ fixed (int* pLowerBounds = &lowerBounds[0])
+ return InternalCreate((void*)t.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private unsafe static extern Array InternalCreate(void* elementType,int rank,int *pLengths,int *pLowerBounds);
+ private unsafe static extern Array InternalCreate(void* elementType, int rank, int* pLengths, int* pLowerBounds);
internal static Array UnsafeCreateInstance(Type elementType, int length)
{
@@ -240,11 +247,11 @@ namespace System {
Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, false);
}
-
+
// Copies length elements from sourceArray, starting at sourceIndex, to
// destinationArray, starting at destinationIndex.
//
- public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
+ public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
{
Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, false);
}
@@ -271,7 +278,7 @@ namespace System {
if (length > Int32.MaxValue || length < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- Array.Copy(sourceArray, destinationArray, (int) length);
+ Array.Copy(sourceArray, destinationArray, (int)length);
}
public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length)
@@ -283,16 +290,16 @@ namespace System {
if (length > Int32.MaxValue || length < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- Array.Copy(sourceArray, (int) sourceIndex, destinationArray, (int) destinationIndex, (int) length);
+ Array.Copy(sourceArray, (int)sourceIndex, destinationArray, (int)destinationIndex, (int)length);
}
-
+
// Sets length elements in array to 0 (or null for Object arrays), starting
// at index.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Clear(Array array, int index, int length);
-
+
// The various Get values...
public unsafe Object GetValue(params int[] indices)
{
@@ -303,11 +310,11 @@ namespace System {
Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
- fixed(int* pIndices = &indices[0])
+ fixed (int* pIndices = &indices[0])
InternalGetReference(&elemref, indices.Length, pIndices);
return TypedReference.InternalToObject(&elemref);
}
-
+
public unsafe Object GetValue(int index)
{
if (Rank != 1)
@@ -318,7 +325,7 @@ namespace System {
InternalGetReference(&elemref, 1, &index);
return TypedReference.InternalToObject(&elemref);
}
-
+
public unsafe Object GetValue(int index1, int index2)
{
if (Rank != 2)
@@ -333,7 +340,7 @@ namespace System {
InternalGetReference(&elemref, 2, pIndices);
return TypedReference.InternalToObject(&elemref);
}
-
+
public unsafe Object GetValue(int index1, int index2, int index3)
{
if (Rank != 3)
@@ -356,7 +363,7 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- return this.GetValue((int) index);
+ return this.GetValue((int)index);
}
public Object GetValue(long index1, long index2)
@@ -367,7 +374,7 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- return this.GetValue((int) index1, (int) index2);
+ return this.GetValue((int)index1, (int)index2);
}
public Object GetValue(long index1, long index2, long index3)
@@ -379,8 +386,8 @@ namespace System {
if (index3 > Int32.MaxValue || index3 < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
-
- return this.GetValue((int) index1, (int) index2, (int) index3);
+
+ return this.GetValue((int)index1, (int)index2, (int)index3);
}
public Object GetValue(params long[] indices)
@@ -393,19 +400,19 @@ namespace System {
int[] intIndices = new int[indices.Length];
- for (int i = 0; i < indices.Length; ++i)
+ for (int i = 0; i < indices.Length; ++i)
{
long index = indices[i];
if (index > Int32.MaxValue || index < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- intIndices[i] = (int) index;
+ intIndices[i] = (int)index;
}
return this.GetValue(intIndices);
}
-
- public unsafe void SetValue(Object value,int index)
+
+ public unsafe void SetValue(Object value, int index)
{
if (Rank != 1)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray);
@@ -413,10 +420,10 @@ namespace System {
TypedReference elemref = new TypedReference();
InternalGetReference(&elemref, 1, &index);
- InternalSetValue(&elemref,value);
+ InternalSetValue(&elemref, value);
}
-
- public unsafe void SetValue(Object value,int index1, int index2)
+
+ public unsafe void SetValue(Object value, int index1, int index2)
{
if (Rank != 2)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray);
@@ -428,10 +435,10 @@ namespace System {
TypedReference elemref = new TypedReference();
InternalGetReference(&elemref, 2, pIndices);
- InternalSetValue(&elemref,value);
+ InternalSetValue(&elemref, value);
}
-
- public unsafe void SetValue(Object value,int index1, int index2, int index3)
+
+ public unsafe void SetValue(Object value, int index1, int index2, int index3)
{
if (Rank != 3)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray);
@@ -444,10 +451,10 @@ namespace System {
TypedReference elemref = new TypedReference();
InternalGetReference(&elemref, 3, pIndices);
- InternalSetValue(&elemref,value);
+ InternalSetValue(&elemref, value);
}
-
- public unsafe void SetValue(Object value,params int[] indices)
+
+ public unsafe void SetValue(Object value, params int[] indices)
{
if (indices == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices);
@@ -456,9 +463,9 @@ namespace System {
Contract.EndContractBlock();
TypedReference elemref = new TypedReference();
- fixed(int* pIndices = &indices[0])
+ fixed (int* pIndices = &indices[0])
InternalGetReference(&elemref, indices.Length, pIndices);
- InternalSetValue(&elemref,value);
+ InternalSetValue(&elemref, value);
}
public void SetValue(Object value, long index)
@@ -467,7 +474,7 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- this.SetValue(value, (int) index);
+ this.SetValue(value, (int)index);
}
public void SetValue(Object value, long index1, long index2)
@@ -478,7 +485,7 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- this.SetValue(value, (int) index1, (int) index2);
+ this.SetValue(value, (int)index1, (int)index2);
}
public void SetValue(Object value, long index1, long index2, long index3)
@@ -491,7 +498,7 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- this.SetValue(value, (int) index1, (int) index2, (int) index3);
+ this.SetValue(value, (int)index1, (int)index2, (int)index3);
}
public void SetValue(Object value, params long[] indices)
@@ -504,12 +511,12 @@ namespace System {
int[] intIndices = new int[indices.Length];
- for (int i = 0; i < indices.Length; ++i)
+ for (int i = 0; i < indices.Length; ++i)
{
long index = indices[i];
if (index > Int32.MaxValue || index < Int32.MinValue)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
- intIndices[i] = (int) index;
+ intIndices[i] = (int)index;
}
this.SetValue(value, intIndices);
@@ -517,23 +524,25 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
// reference to TypedReference is banned, so have to pass result as pointer
- private unsafe extern void InternalGetReference(void * elemRef, int rank, int * pIndices);
+ private unsafe extern void InternalGetReference(void* elemRef, int rank, int* pIndices);
// Ideally, we would like to use TypedReference.SetValue instead. Unfortunately, TypedReference.SetValue
// always throws not-supported exception
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private unsafe extern static void InternalSetValue(void * target, Object value);
+ private unsafe extern static void InternalSetValue(void* target, Object value);
- public extern int Length {
+ public extern int Length
+ {
[Pure]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
- private static int GetMedian(int low, int hi) {
+ private static int GetMedian(int low, int hi)
+ {
// Note both may be negative, if we are dealing with arrays w/ negative lower bounds.
Contract.Requires(low <= hi);
- Debug.Assert( hi - low >= 0, "Length overflow!");
+ Debug.Assert(hi - low >= 0, "Length overflow!");
return low + ((hi - low) >> 1);
}
@@ -545,7 +554,8 @@ namespace System {
internal const int MaxArrayLength = 0X7FEFFFFF;
internal const int MaxByteArrayLength = 0x7FFFFFC7;
- public extern long LongLength {
+ public extern long LongLength
+ {
[Pure]
[MethodImpl(MethodImplOptions.InternalCall)]
get;
@@ -556,12 +566,14 @@ namespace System {
public extern int GetLength(int dimension);
[Pure]
- public long GetLongLength(int dimension) {
+ public long GetLongLength(int dimension)
+ {
//This method should throw an IndexOufOfRangeException for compat if dimension < 0 or >= Rank
return GetLength(dimension);
}
- public extern int Rank {
+ public extern int Rank
+ {
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
@@ -582,20 +594,21 @@ namespace System {
int ICollection.Count
{ get { return Length; } }
-
+
// Returns an object appropriate for synchronizing access to this
// Array.
public Object SyncRoot
{ get { return this; } }
-
+
// Is this Array read-only?
public bool IsReadOnly
{ get { return false; } }
- public bool IsFixedSize {
+ public bool IsFixedSize
+ {
get { return true; }
}
-
+
// Is this Array synchronized (i.e., thread-safe)? If you want a synchronized
// collection, you can use SyncRoot as an object to synchronize your
// collection with. You could also call GetSynchronized()
@@ -604,7 +617,8 @@ namespace System {
{ get { return false; } }
- Object IList.this[int index] {
+ Object IList.this[int index]
+ {
get { return GetValue(index); }
set { SetValue(value, index); }
}
@@ -652,8 +666,10 @@ namespace System {
return MemberwiseClone();
}
- Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer) {
- if (other == null) {
+ Int32 IStructuralComparable.CompareTo(Object other, IComparer comparer)
+ {
+ if (other == null)
+ {
return 1;
}
@@ -667,39 +683,45 @@ namespace System {
int i = 0;
int c = 0;
- while (i < o.Length && c == 0) {
+ while (i < o.Length && c == 0)
+ {
object left = GetValue(i);
object right = o.GetValue(i);
c = comparer.Compare(left, right);
i++;
}
-
+
return c;
}
- Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer) {
-
- if (other == null) {
+ Boolean IStructuralEquatable.Equals(Object other, IEqualityComparer comparer)
+ {
+ if (other == null)
+ {
return false;
}
- if (Object.ReferenceEquals(this, other)) {
+ if (Object.ReferenceEquals(this, other))
+ {
return true;
}
Array o = other as Array;
- if (o == null || o.Length != this.Length) {
+ if (o == null || o.Length != this.Length)
+ {
return false;
}
int i = 0;
- while (i < o.Length) {
+ while (i < o.Length)
+ {
object left = GetValue(i);
object right = o.GetValue(i);
- if (!comparer.Equals(left, right)) {
+ if (!comparer.Equals(left, right))
+ {
return false;
}
i++;
@@ -709,18 +731,21 @@ namespace System {
}
// From System.Web.Util.HashCodeCombiner
- internal static int CombineHashCodes(int h1, int h2) {
+ internal static int CombineHashCodes(int h1, int h2)
+ {
return (((h1 << 5) + h1) ^ h2);
}
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
+ int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
+ {
if (comparer == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
Contract.EndContractBlock();
int ret = 0;
- for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++) {
+ for (int i = (this.Length >= 8 ? this.Length - 8 : 0); i < this.Length; i++)
+ {
ret = CombineHashCodes(ret, comparer.GetHashCode(GetValue(i)));
}
@@ -741,15 +766,16 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- public static int BinarySearch(Array array, Object value) {
- if (array==null)
+ public static int BinarySearch(Array array, Object value)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.Ensures((Contract.Result<int>() >= array.GetLowerBound(0) && Contract.Result<int>() <= array.GetUpperBound(0)) || (Contract.Result<int>() < array.GetLowerBound(0) && ~Contract.Result<int>() <= array.GetUpperBound(0) + 1));
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return BinarySearch(array, lb, array.Length, value, null);
}
-
+
// Searches a section of an array for a given element using a binary search
// algorithm. Elements of the array are compared to the search value using
// the IComparable interface, which must be implemented by all
@@ -764,10 +790,11 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- public static int BinarySearch(Array array, int index, int length, Object value) {
+ public static int BinarySearch(Array array, int index, int length, Object value)
+ {
return BinarySearch(array, index, length, value, null);
}
-
+
// Searches an array for a given element using a binary search algorithm.
// Elements of the array are compared to the search value using the given
// IComparer interface. If comparer is null, elements of the
@@ -783,14 +810,15 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- public static int BinarySearch(Array array, Object value, IComparer comparer) {
- if (array==null)
+ public static int BinarySearch(Array array, Object value, IComparer comparer)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return BinarySearch(array, lb, array.Length, value, comparer);
}
-
+
// Searches a section of an array for a given element using a binary search
// algorithm. Elements of the array are compared to the search value using
// the given IComparer interface. If comparer is null,
@@ -807,8 +835,9 @@ namespace System {
// is larger than the given search value.
//
[Pure]
- public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) {
- if (array==null)
+ public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
@@ -820,9 +849,10 @@ namespace System {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
if (array.Rank != 1)
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
-
+
if (comparer == null) comparer = Comparer.Default;
- if (comparer == Comparer.Default) {
+ if (comparer == Comparer.Default)
+ {
int retval;
bool r = TrySZBinarySearch(array, index, length, value, out retval);
if (r)
@@ -830,45 +860,57 @@ namespace System {
}
int lo = index;
- int hi = index + length - 1;
+ int hi = index + length - 1;
Object[] objArray = array as Object[];
- if(objArray != null) {
- while (lo <= hi) {
+ if (objArray != null)
+ {
+ while (lo <= hi)
+ {
// i might overflow if lo and hi are both large positive numbers.
int i = GetMedian(lo, hi);
int c = 0;
- try {
+ try
+ {
c = comparer.Compare(objArray[i], value);
}
- catch (Exception e) {
+ catch (Exception e)
+ {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
}
if (c == 0) return i;
- if (c < 0) {
+ if (c < 0)
+ {
lo = i + 1;
}
- else {
+ else
+ {
hi = i - 1;
}
}
}
- else {
- while (lo <= hi) {
- int i = GetMedian(lo, hi);
+ else
+ {
+ while (lo <= hi)
+ {
+ int i = GetMedian(lo, hi);
int c = 0;
- try {
+ try
+ {
c = comparer.Compare(array.GetValue(i), value);
}
- catch (Exception e) {
+ catch (Exception e)
+ {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e);
}
if (c == 0) return i;
- if (c < 0) {
+ if (c < 0)
+ {
lo = i + 1;
}
- else {
+ else
+ {
hi = i - 1;
}
}
@@ -878,31 +920,35 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool TrySZBinarySearch(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
-
+
[Pure]
- public static int BinarySearch<T>(T[] array, T value) {
- if (array==null)
+ public static int BinarySearch<T>(T[] array, T value)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
return BinarySearch<T>(array, 0, array.Length, value, null);
}
[Pure]
- public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer) {
- if (array==null)
+ public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
return BinarySearch<T>(array, 0, array.Length, value, comparer);
}
[Pure]
- public static int BinarySearch<T>(T[] array, int index, int length, T value) {
+ public static int BinarySearch<T>(T[] array, int index, int length, T value)
+ {
return BinarySearch<T>(array, index, length, value, null);
}
[Pure]
- public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer) {
- if (array==null)
+ public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
@@ -916,12 +962,15 @@ namespace System {
return ArraySortHelper<T>.Default.BinarySearch(array, index, length, value, comparer);
}
- public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput,TOutput> converter) {
- if( array == null) {
+ public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( converter == null) {
+ if (converter == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.Ensures(Contract.Result<TOutput[]>() != null);
@@ -929,7 +978,8 @@ namespace System {
Contract.EndContractBlock();
TOutput[] newArray = new TOutput[array.Length];
- for( int i = 0; i< array.Length; i++) {
+ for (int i = 0; i < array.Length; i++)
+ {
newArray[i] = converter(array[i]);
}
return newArray;
@@ -959,7 +1009,12 @@ namespace System {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported);
Contract.EndContractBlock();
- this.CopyTo(array, (int) index);
+ this.CopyTo(array, (int)index);
+ }
+
+ private static class EmptyArray<T>
+ {
+ internal static readonly T[] Value = new T[0];
}
[Pure]
@@ -972,7 +1027,8 @@ namespace System {
return EmptyArray<T>.Value;
}
- public static bool Exists<T>(T[] array, Predicate<T> match) {
+ public static bool Exists<T>(T[] array, Predicate<T> match)
+ {
return Array.FindIndex(array, match) != -1;
}
@@ -1012,45 +1068,57 @@ namespace System {
}
}
- public static T Find<T>(T[] array, Predicate<T> match) {
- if( array == null) {
+ public static T Find<T>(T[] array, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- for(int i = 0 ; i < array.Length; i++) {
- if(match(array[i])) {
+ for (int i = 0; i < array.Length; i++)
+ {
+ if (match(array[i]))
+ {
return array[i];
}
}
return default(T);
}
- public static T[] FindAll<T>(T[] array, Predicate<T> match) {
- if( array == null) {
+ public static T[] FindAll<T>(T[] array, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- List<T> list = new List<T>();
- for(int i = 0 ; i < array.Length; i++) {
- if(match(array[i])) {
+ List<T> list = new List<T>();
+ for (int i = 0; i < array.Length; i++)
+ {
+ if (match(array[i]))
+ {
list.Add(array[i]);
}
}
return list.ToArray();
}
- public static int FindIndex<T>(T[] array, Predicate<T> match) {
- if (array==null) {
+ public static int FindIndex<T>(T[] array, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
@@ -1059,62 +1127,77 @@ namespace System {
return FindIndex(array, 0, array.Length, match);
}
- public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match) {
- if (array==null) {
+ public static int FindIndex<T>(T[] array, int startIndex, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
Contract.EndContractBlock();
-
+
return FindIndex(array, startIndex, array.Length - startIndex, match);
}
- public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) {
- if (array==null) {
+ public static int FindIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( startIndex < 0 || startIndex > array.Length ) {
+ if (startIndex < 0 || startIndex > array.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
- if (count < 0 || startIndex > array.Length - count) {
+ if (count < 0 || startIndex > array.Length - count)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
Contract.EndContractBlock();
int endIndex = startIndex + count;
- for( int i = startIndex; i < endIndex; i++) {
- if( match(array[i])) return i;
+ for (int i = startIndex; i < endIndex; i++)
+ {
+ if (match(array[i])) return i;
}
return -1;
}
- public static T FindLast<T>(T[] array, Predicate<T> match) {
- if( array == null) {
+ public static T FindLast<T>(T[] array, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
-
- for(int i = array.Length - 1 ; i >= 0; i--) {
- if(match(array[i])) {
+
+ for (int i = array.Length - 1; i >= 0; i--)
+ {
+ if (match(array[i]))
+ {
return array[i];
}
}
return default(T);
}
- public static int FindLastIndex<T>(T[] array, Predicate<T> match) {
- if( array == null) {
+ public static int FindLastIndex<T>(T[] array, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.EndContractBlock();
@@ -1122,63 +1205,79 @@ namespace System {
return FindLastIndex(array, array.Length - 1, array.Length, match);
}
- public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match) {
- if( array == null) {
+ public static int FindLastIndex<T>(T[] array, int startIndex, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.EndContractBlock();
-
+
return FindLastIndex(array, startIndex, startIndex + 1, match);
}
- public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match) {
- if( array == null) {
+ public static int FindLastIndex<T>(T[] array, int startIndex, int count, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- if(array.Length == 0) {
+ if (array.Length == 0)
+ {
// Special case for 0 length List
- if( startIndex != -1) {
+ if (startIndex != -1)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
- else {
+ else
+ {
// Make sure we're not out of range
- if ( startIndex < 0 || startIndex >= array.Length) {
+ if (startIndex < 0 || startIndex >= array.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
-
+
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
- if (count < 0 || startIndex - count + 1 < 0) {
+ if (count < 0 || startIndex - count + 1 < 0)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
int endIndex = startIndex - count;
- for( int i = startIndex; i > endIndex; i--) {
- if( match(array[i])) {
+ for (int i = startIndex; i > endIndex; i--)
+ {
+ if (match(array[i]))
+ {
return i;
}
}
return -1;
}
- public static void ForEach<T>(T[] array, Action<T> action) {
- if( array == null) {
+ public static void ForEach<T>(T[] array, Action<T> action)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( action == null) {
+ if (action == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
Contract.EndContractBlock();
- for(int i = 0 ; i < array.Length; i++) {
+ for (int i = 0; i < array.Length; i++)
+ {
action(array[i]);
}
}
@@ -1195,43 +1294,46 @@ namespace System {
else
return new ArrayEnumerator(this, lowerBound, Length);
}
-
+
// Returns the index of the first occurrence of a given value in an array.
// The array is searched forwards, and the elements of the array are
// compared to the given value using the Object.Equals method.
//
- public static int IndexOf(Array array, Object value) {
- if (array==null)
+ public static int IndexOf(Array array, Object value)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return IndexOf(array, value, lb, array.Length);
}
-
+
// Returns the index of the first occurrence of a given value in a range of
// an array. The array is searched forwards, starting at index
// startIndex and ending at the last element of the array. The
// elements of the array are compared to the given value using the
// Object.Equals method.
//
- public static int IndexOf(Array array, Object value, int startIndex) {
- if (array==null)
+ public static int IndexOf(Array array, Object value, int startIndex)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return IndexOf(array, value, startIndex, array.Length - startIndex + lb);
}
-
+
// Returns the index of the first occurrence of a given value in a range of
// an array. The array is searched forwards, starting at index
// startIndex and upto count elements. The
// elements of the array are compared to the given value using the
// Object.Equals method.
//
- public static int IndexOf(Array array, Object value, int startIndex, int count) {
- if (array==null)
+ public static int IndexOf(Array array, Object value, int startIndex, int count)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (array.Rank != 1)
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
@@ -1252,27 +1354,36 @@ namespace System {
Object[] objArray = array as Object[];
int endIndex = startIndex + count;
- if (objArray != null) {
- if (value == null) {
- for (int i = startIndex; i < endIndex; i++) {
+ if (objArray != null)
+ {
+ if (value == null)
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (objArray[i] == null) return i;
}
}
- else {
- for (int i = startIndex; i < endIndex; i++) {
+ else
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
Object obj = objArray[i];
if (obj != null && obj.Equals(value)) return i;
}
}
}
- else {
- for (int i = startIndex; i < endIndex; i++) {
+ else
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
Object obj = array.GetValue(i);
- if( obj == null) {
- if(value == null) return i;
+ if (obj == null)
+ {
+ if (value == null) return i;
}
- else {
- if( obj.Equals(value)) return i;
+ else
+ {
+ if (obj.Equals(value)) return i;
}
}
}
@@ -1280,12 +1391,14 @@ namespace System {
// for arrays with a lower bound of -1 we will not return -1 when the
// item was not found. And for SZArrays (the vast majority), -1 still
// works for them.
- return lb-1;
+ return lb - 1;
}
[Pure]
- public static int IndexOf<T>(T[] array, T value) {
- if (array==null) {
+ public static int IndexOf<T>(T[] array, T value)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures((Contract.Result<int>() < 0) ||
@@ -1295,8 +1408,10 @@ namespace System {
return IndexOf(array, value, 0, array.Length);
}
- public static int IndexOf<T>(T[] array, T value, int startIndex) {
- if (array==null) {
+ public static int IndexOf<T>(T[] array, T value, int startIndex)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
@@ -1305,16 +1420,20 @@ namespace System {
return IndexOf(array, value, startIndex, array.Length - startIndex);
}
- public static int IndexOf<T>(T[] array, T value, int startIndex, int count) {
- if (array==null) {
+ public static int IndexOf<T>(T[] array, T value, int startIndex, int count)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (startIndex < 0 || startIndex > array.Length ) {
+ if (startIndex < 0 || startIndex > array.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
- if (count < 0 || count > array.Length - startIndex) {
+ if (count < 0 || count > array.Length - startIndex)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
Contract.Ensures(Contract.Result<int>() < array.Length);
@@ -1325,27 +1444,29 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal);
-
+
// Returns the index of the last occurrence of a given value in an array.
// The array is searched backwards, and the elements of the array are
// compared to the given value using the Object.Equals method.
//
- public static int LastIndexOf(Array array, Object value) {
- if (array==null)
+ public static int LastIndexOf(Array array, Object value)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
return LastIndexOf(array, value, array.Length - 1 + lb, array.Length);
}
-
+
// Returns the index of the last occurrence of a given value in a range of
// an array. The array is searched backwards, starting at index
// startIndex and ending at index 0. The elements of the array are
// compared to the given value using the Object.Equals method.
//
- public static int LastIndexOf(Array array, Object value, int startIndex) {
+ public static int LastIndexOf(Array array, Object value, int startIndex)
+ {
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
@@ -1353,21 +1474,23 @@ namespace System {
int lb = array.GetLowerBound(0);
return LastIndexOf(array, value, startIndex, startIndex + 1 - lb);
}
-
+
// Returns the index of the last occurrence of a given value in a range of
// an array. The array is searched backwards, starting at index
// startIndex and counting uptocount elements. The elements of
// the array are compared to the given value using the Object.Equals
// method.
//
- public static int LastIndexOf(Array array, Object value, int startIndex, int count) {
- if (array==null)
+ public static int LastIndexOf(Array array, Object value, int startIndex, int count)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.Ensures(Contract.Result<int>() < array.GetLowerBound(0) + array.Length);
Contract.EndContractBlock();
int lb = array.GetLowerBound(0);
- if (array.Length == 0) {
- return lb-1;
+ if (array.Length == 0)
+ {
+ return lb - 1;
}
if (startIndex < lb || startIndex >= array.Length + lb)
@@ -1387,35 +1510,46 @@ namespace System {
Object[] objArray = array as Object[];
int endIndex = startIndex - count + 1;
- if (objArray!=null) {
- if (value == null) {
- for (int i = startIndex; i >= endIndex; i--) {
+ if (objArray != null)
+ {
+ if (value == null)
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (objArray[i] == null) return i;
}
}
- else {
- for (int i = startIndex; i >= endIndex; i--) {
+ else
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
Object obj = objArray[i];
if (obj != null && obj.Equals(value)) return i;
}
}
}
- else {
- for (int i = startIndex; i >= endIndex; i--) {
+ else
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
Object obj = array.GetValue(i);
- if( obj == null) {
- if(value == null) return i;
+ if (obj == null)
+ {
+ if (value == null) return i;
}
- else {
- if( obj.Equals(value)) return i;
+ else
+ {
+ if (obj.Equals(value)) return i;
}
}
}
- return lb-1; // Return lb-1 for arrays with negative lower bounds.
+ return lb - 1; // Return lb-1 for arrays with negative lower bounds.
}
-
- public static int LastIndexOf<T>(T[] array, T value) {
- if (array==null) {
+
+ public static int LastIndexOf<T>(T[] array, T value)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
@@ -1424,50 +1558,59 @@ namespace System {
return LastIndexOf(array, value, array.Length - 1, array.Length);
}
- public static int LastIndexOf<T>(T[] array, T value, int startIndex) {
- if (array==null) {
+ public static int LastIndexOf<T>(T[] array, T value, int startIndex)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
Contract.EndContractBlock();
// if array is empty and startIndex is 0, we need to pass 0 as count
- return LastIndexOf(array, value, startIndex, (array.Length == 0)? 0 : (startIndex + 1));
+ return LastIndexOf(array, value, startIndex, (array.Length == 0) ? 0 : (startIndex + 1));
}
- public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count) {
- if (array==null) {
+ public static int LastIndexOf<T>(T[] array, T value, int startIndex, int count)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
Contract.Ensures(Contract.Result<int>() < array.Length);
Contract.EndContractBlock();
-
- if(array.Length == 0) {
+
+ if (array.Length == 0)
+ {
//
// Special case for 0 length List
// accept -1 and 0 as valid startIndex for compablility reason.
//
- if( startIndex != -1 && startIndex != 0) {
+ if (startIndex != -1 && startIndex != 0)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
// only 0 is a valid value for count if array is empty
- if( count != 0) {
+ if (count != 0)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
return -1;
}
// Make sure we're not out of range
- if ( startIndex < 0 || startIndex >= array.Length) {
+ if (startIndex < 0 || startIndex >= array.Length)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
-
+
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
- if (count < 0 || startIndex - count + 1 < 0) {
+ if (count < 0 || startIndex - count + 1 < 0)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
- return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count);
+ return EqualityComparer<T>.Default.LastIndexOf(array, value, startIndex, count);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1479,21 +1622,23 @@ namespace System {
// located at index length - i - 1, where length is the
// length of the array.
//
- public static void Reverse(Array array) {
- if (array==null)
+ public static void Reverse(Array array)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
Reverse(array, array.GetLowerBound(0), array.Length);
}
-
+
// Reverses the elements in a range of an array. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
// Reliability note: This may fail because it may have to box objects.
//
- public static void Reverse(Array array, int index, int length) {
- if (array==null)
+ public static void Reverse(Array array, int index, int length)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
int lowerBound = array.GetLowerBound(0);
if (index < lowerBound)
@@ -1514,8 +1659,10 @@ namespace System {
int i = index;
int j = index + length - 1;
Object[] objArray = array as Object[];
- if (objArray!=null) {
- while (i < j) {
+ if (objArray != null)
+ {
+ while (i < j)
+ {
Object temp = objArray[i];
objArray[i] = objArray[j];
objArray[j] = temp;
@@ -1523,8 +1670,10 @@ namespace System {
j--;
}
}
- else {
- while (i < j) {
+ else
+ {
+ while (i < j)
+ {
Object temp = array.GetValue(i);
array.SetValue(array.GetValue(j), i);
array.SetValue(temp, j);
@@ -1573,57 +1722,62 @@ namespace System {
// other using the IComparable interface, which must be implemented
// by all elements of the array.
//
- public static void Sort(Array array) {
- if (array==null)
+ public static void Sort(Array array)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
Sort(array, null, array.GetLowerBound(0), array.Length, null);
}
-
+
// Sorts the elements of two arrays based on the keys in the first array.
// Elements in the keys array specify the sort keys for
// corresponding elements in the items array. The sort compares the
// keys to each other using the IComparable interface, which must be
// implemented by all elements of the keys array.
//
- public static void Sort(Array keys, Array items) {
- if (keys==null)
+ public static void Sort(Array keys, Array items)
+ {
+ if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
Contract.EndContractBlock();
Sort(keys, items, keys.GetLowerBound(0), keys.Length, null);
}
-
+
// Sorts the elements in a section of an array. The sort compares the
// elements to each other using the IComparable interface, which
// must be implemented by all elements in the given section of the array.
//
- public static void Sort(Array array, int index, int length) {
+ public static void Sort(Array array, int index, int length)
+ {
Sort(array, null, index, length, null);
}
-
+
// Sorts the elements in a section of two arrays based on the keys in the
// first array. Elements in the keys array specify the sort keys for
// corresponding elements in the items array. The sort compares the
// keys to each other using the IComparable interface, which must be
// implemented by all elements of the keys array.
//
- public static void Sort(Array keys, Array items, int index, int length) {
+ public static void Sort(Array keys, Array items, int index, int length)
+ {
Sort(keys, items, index, length, null);
}
-
+
// Sorts the elements of an array. The sort compares the elements to each
// other using the given IComparer interface. If comparer is
// null, the elements are compared to each other using the
// IComparable interface, which in that case must be implemented by
// all elements of the array.
//
- public static void Sort(Array array, IComparer comparer) {
- if (array==null)
+ public static void Sort(Array array, IComparer comparer)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
Sort(array, null, array.GetLowerBound(0), array.Length, comparer);
}
-
+
// Sorts the elements of two arrays based on the keys in the first array.
// Elements in the keys array specify the sort keys for
// corresponding elements in the items array. The sort compares the
@@ -1632,23 +1786,25 @@ namespace System {
// the IComparable interface, which in that case must be implemented
// by all elements of the keys array.
//
- public static void Sort(Array keys, Array items, IComparer comparer) {
- if (keys==null)
+ public static void Sort(Array keys, Array items, IComparer comparer)
+ {
+ if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
Contract.EndContractBlock();
Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer);
}
-
+
// Sorts the elements in a section of an array. The sort compares the
// elements to each other using the given IComparer interface. If
// comparer is null, the elements are compared to each other using
// the IComparable interface, which in that case must be implemented
// by all elements in the given section of the array.
//
- public static void Sort(Array array, int index, int length, IComparer comparer) {
+ public static void Sort(Array array, int index, int length, IComparer comparer)
+ {
Sort(array, null, index, length, comparer);
}
-
+
// Sorts the elements in a section of two arrays based on the keys in the
// first array. Elements in the keys array specify the sort keys for
// corresponding elements in the items array. The sort compares the
@@ -1657,8 +1813,9 @@ namespace System {
// the IComparable interface, which in that case must be implemented
// by all elements of the given section of the keys array.
//
- public static void Sort(Array keys, Array items, int index, int length, IComparer comparer) {
- if (keys==null)
+ public static void Sort(Array keys, Array items, int index, int length, IComparer comparer)
+ {
+ if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
if (keys.Rank != 1 || (items != null && items.Rank != 1))
ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported);
@@ -1674,9 +1831,11 @@ namespace System {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
-
- if (length > 1) {
- if (comparer == Comparer.Default || comparer == null) {
+
+ if (length > 1)
+ {
+ if (comparer == Comparer.Default || comparer == null)
+ {
bool r = TrySZSort(keys, items, index, index + length - 1);
if (r)
return;
@@ -1686,58 +1845,67 @@ namespace System {
Object[] objItems = null;
if (objKeys != null)
objItems = items as Object[];
- if (objKeys != null && (items==null || objItems != null)) {
+ if (objKeys != null && (items == null || objItems != null))
+ {
SorterObjectArray sorter = new SorterObjectArray(objKeys, objItems, comparer);
sorter.Sort(index, length);
}
- else {
+ else
+ {
SorterGenericArray sorter = new SorterGenericArray(keys, items, comparer);
sorter.Sort(index, length);
}
}
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool TrySZSort(Array keys, Array items, int left, int right);
- public static void Sort<T>(T[] array) {
- if (array==null)
+ public static void Sort<T>(T[] array)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
Sort<T>(array, 0, array.Length, null);
}
- public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items) {
- if (keys==null)
+ public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items)
+ {
+ if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
Contract.EndContractBlock();
Sort<TKey, TValue>(keys, items, 0, keys.Length, null);
}
- public static void Sort<T>(T[] array, int index, int length) {
+ public static void Sort<T>(T[] array, int index, int length)
+ {
Sort<T>(array, index, length, null);
}
- public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length) {
+ public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length)
+ {
Sort<TKey, TValue>(keys, items, index, length, null);
}
- public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer) {
+ public static void Sort<T>(T[] array, System.Collections.Generic.IComparer<T> comparer)
+ {
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
Contract.EndContractBlock();
Sort<T>(array, 0, array.Length, comparer);
}
- public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer) {
- if (keys==null)
+ public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, System.Collections.Generic.IComparer<TKey> comparer)
+ {
+ if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
Contract.EndContractBlock();
Sort<TKey, TValue>(keys, items, 0, keys.Length, comparer);
}
- public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer) {
- if (array==null)
+ public static void Sort<T>(T[] array, int index, int length, System.Collections.Generic.IComparer<T> comparer)
+ {
+ if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
@@ -1747,19 +1915,23 @@ namespace System {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- if (length > 1) {
- if ( comparer == null || comparer == Comparer<T>.Default ) {
- if(TrySZSort(array, null, index, index + length - 1)) {
+ if (length > 1)
+ {
+ if (comparer == null || comparer == Comparer<T>.Default)
+ {
+ if (TrySZSort(array, null, index, index + length - 1))
+ {
return;
}
}
- ArraySortHelper<T>.Default.Sort(array, index, length, comparer);
+ ArraySortHelper<T>.Default.Sort(array, index, length, comparer);
}
}
- public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer) {
- if (keys==null)
+ public static void Sort<TKey, TValue>(TKey[] keys, TValue[] items, int index, int length, System.Collections.Generic.IComparer<TKey> comparer)
+ {
+ if (keys == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys);
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
@@ -1769,13 +1941,16 @@ namespace System {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- if (length > 1) {
- if ( comparer == null || comparer == Comparer<TKey>.Default ) {
- if(TrySZSort(keys, items, index, index + length - 1)) {
+ if (length > 1)
+ {
+ if (comparer == null || comparer == Comparer<TKey>.Default)
+ {
+ if (TrySZSort(keys, items, index, index + length - 1))
+ {
return;
}
}
-
+
if (items == null)
{
Sort<TKey>(keys, index, length, comparer);
@@ -1786,12 +1961,15 @@ namespace System {
}
}
- public static void Sort<T>(T[] array, Comparison<T> comparison) {
- if( array == null) {
+ public static void Sort<T>(T[] array, Comparison<T> comparison)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( comparison == null) {
+ if (comparison == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
Contract.EndContractBlock();
@@ -1799,18 +1977,23 @@ namespace System {
ArraySortHelper<T>.Sort(array, 0, array.Length, comparison);
}
- public static bool TrueForAll<T>(T[] array, Predicate<T> match) {
- if( array == null) {
+ public static bool TrueForAll<T>(T[] array, Predicate<T> match)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- for(int i = 0 ; i < array.Length; i++) {
- if( !match(array[i])) {
+ for (int i = 0; i < array.Length; i++)
+ {
+ if (!match(array[i]))
+ {
return false;
}
}
@@ -1823,15 +2006,16 @@ namespace System {
{
private Object[] keys;
private Object[] items;
- private IComparer comparer;
-
- internal SorterObjectArray(Object[] keys, Object[] items, IComparer comparer) {
+ private IComparer comparer;
+
+ internal SorterObjectArray(Object[] keys, Object[] items, IComparer comparer)
+ {
if (comparer == null) comparer = Comparer.Default;
this.keys = keys;
this.items = items;
this.comparer = comparer;
}
-
+
internal void SwapIfGreaterWithItems(int a, int b)
{
if (a != b)
@@ -1907,9 +2091,9 @@ namespace System {
}
if (partitionSize == 3)
{
- SwapIfGreaterWithItems(lo, hi-1);
+ SwapIfGreaterWithItems(lo, hi - 1);
SwapIfGreaterWithItems(lo, hi);
- SwapIfGreaterWithItems(hi-1, hi);
+ SwapIfGreaterWithItems(hi - 1, hi);
return;
}
@@ -1948,7 +2132,7 @@ namespace System {
while (comparer.Compare(keys[++left], pivot) < 0) ;
while (comparer.Compare(pivot, keys[--right]) < 0) ;
- if(left >= right)
+ if (left >= right)
break;
Swap(left, right);
@@ -1989,7 +2173,7 @@ namespace System {
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
- if(items != null)
+ if (items != null)
items[lo + i - 1] = items[lo + child - 1];
i = child;
}
@@ -2010,17 +2194,17 @@ namespace System {
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
- if(items != null)
+ if (items != null)
items[j + 1] = items[j];
j--;
}
keys[j + 1] = t;
- if(items != null)
+ if (items != null)
items[j + 1] = ti;
}
}
}
-
+
// Private value used by the Sort methods for instances of Array.
// This is slower than the one for Object[], since we can't use the JIT helpers
// to access the elements. We must use GetValue & SetValue.
@@ -2062,8 +2246,8 @@ namespace System {
Object t1 = keys.GetValue(i);
keys.SetValue(keys.GetValue(j), i);
keys.SetValue(t1, j);
-
- if(items != null)
+
+ if (items != null)
{
Object t2 = items.GetValue(i);
items.SetValue(items.GetValue(j), i);
@@ -2113,9 +2297,9 @@ namespace System {
}
if (partitionSize == 3)
{
- SwapIfGreaterWithItems(lo, hi-1);
+ SwapIfGreaterWithItems(lo, hi - 1);
SwapIfGreaterWithItems(lo, hi);
- SwapIfGreaterWithItems(hi-1, hi);
+ SwapIfGreaterWithItems(hi - 1, hi);
return;
}
@@ -2148,7 +2332,7 @@ namespace System {
Object pivot = keys.GetValue(mid);
Swap(mid, hi - 1);
int left = lo, right = hi - 1; // We already partitioned lo and hi and put the pivot in hi - 1. And we pre-increment & decrement below.
-
+
while (left < right)
{
while (comparer.Compare(keys.GetValue(++left), pivot) < 0) ;
@@ -2183,7 +2367,7 @@ namespace System {
private void DownHeap(int i, int n, int lo)
{
Object d = keys.GetValue(lo + i - 1);
- Object dt = (items != null)? items.GetValue(lo + i - 1) : null;
+ Object dt = (items != null) ? items.GetValue(lo + i - 1) : null;
int child;
while (i <= n / 2)
{
@@ -2197,12 +2381,12 @@ namespace System {
break;
keys.SetValue(keys.GetValue(lo + child - 1), lo + i - 1);
- if(items != null)
+ if (items != null)
items.SetValue(items.GetValue(lo + child - 1), lo + i - 1);
i = child;
}
keys.SetValue(d, lo + i - 1);
- if(items != null)
+ if (items != null)
items.SetValue(dt, lo + i - 1);
}
@@ -2214,30 +2398,32 @@ namespace System {
{
j = i;
t = keys.GetValue(i + 1);
- dt = (items != null)? items.GetValue(i + 1) : null;
+ dt = (items != null) ? items.GetValue(i + 1) : null;
while (j >= lo && comparer.Compare(t, keys.GetValue(j)) < 0)
{
keys.SetValue(keys.GetValue(j), j + 1);
- if(items != null)
+ if (items != null)
items.SetValue(items.GetValue(j), j + 1);
j--;
}
keys.SetValue(t, j + 1);
- if(items != null)
+ if (items != null)
items.SetValue(dt, j + 1);
}
}
}
- [Serializable] private sealed class SZArrayEnumerator : IEnumerator, ICloneable
+ [Serializable]
+ private sealed class SZArrayEnumerator : IEnumerator, ICloneable
{
private Array _array;
private int _index;
private int _endIndex; // cache array length, since it's a little slow.
- internal SZArrayEnumerator(Array array) {
+ 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;
@@ -2249,28 +2435,34 @@ namespace System {
return MemberwiseClone();
}
- public bool MoveNext() {
- if (_index < _endIndex) {
+ public bool MoveNext()
+ {
+ if (_index < _endIndex)
+ {
_index++;
return (_index < _endIndex);
}
return false;
}
-
- public Object Current {
- get {
+
+ public Object Current
+ {
+ get
+ {
if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array.GetValue(_index);
}
}
-
- public void Reset() {
+
+ public void Reset()
+ {
_index = -1;
}
}
-
- [Serializable] private sealed class ArrayEnumerator : IEnumerator, ICloneable
+
+ [Serializable]
+ private sealed class ArrayEnumerator : IEnumerator, ICloneable
{
private Array array;
private int index;
@@ -2279,23 +2471,26 @@ namespace System {
private int[] _indices; // The current position in a multidim array
private bool _complete;
- internal ArrayEnumerator(Array array, int index, int count) {
+ internal ArrayEnumerator(Array array, int index, int count)
+ {
this.array = array;
this.index = index - 1;
startIndex = index;
endIndex = index + count;
_indices = new int[array.Rank];
int checkForZero = 1; // Check for dimensions of size 0.
- for(int i=0; i<array.Rank; i++) {
+ for (int i = 0; i < array.Rank; i++)
+ {
_indices[i] = array.GetLowerBound(i);
checkForZero *= array.GetLength(i);
}
// To make MoveNext simpler, decrement least significant index.
- _indices[_indices.Length-1]--;
+ _indices[_indices.Length - 1]--;
_complete = (checkForZero == 0);
}
- private void IncArray() {
+ private void IncArray()
+ {
// This method advances us to the next valid array index,
// handling all the multiple dimension & bounds correctly.
// Think of it like an odometer in your car - we start with
@@ -2306,16 +2501,19 @@ namespace System {
// has rolled over it's upper bound, we're done.
//
int rank = array.Rank;
- _indices[rank-1]++;
- for(int dim=rank-1; dim>=0; dim--) {
- if (_indices[dim] > array.GetUpperBound(dim)) {
- if (dim==0) {
+ _indices[rank - 1]++;
+ for (int dim = rank - 1; dim >= 0; dim--)
+ {
+ if (_indices[dim] > array.GetUpperBound(dim))
+ {
+ if (dim == 0)
+ {
_complete = true;
break;
}
- for(int j=dim; j<rank; j++)
+ for (int j = dim; j < rank; j++)
_indices[j] = array.GetLowerBound(j);
- _indices[dim-1]++;
+ _indices[dim - 1]++;
}
}
}
@@ -2325,8 +2523,10 @@ namespace System {
return MemberwiseClone();
}
- public bool MoveNext() {
- if (_complete) {
+ public bool MoveNext()
+ {
+ if (_complete)
+ {
index = endIndex;
return false;
}
@@ -2334,25 +2534,29 @@ namespace System {
IncArray();
return !_complete;
}
-
- public Object Current {
- get {
+
+ public Object Current
+ {
+ get
+ {
if (index < startIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_complete) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return array.GetValue(_indices);
}
}
-
- public void Reset() {
+
+ public void Reset()
+ {
index = startIndex - 1;
int checkForZero = 1;
- for(int i=0; i<array.Rank; i++) {
+ for (int i = 0; i < array.Rank; i++)
+ {
_indices[i] = array.GetLowerBound(i);
checkForZero *= array.GetLength(i);
}
_complete = (checkForZero == 0);
// To make MoveNext simpler, decrement least significant index.
- _indices[_indices.Length-1]--;
+ _indices[_indices.Length - 1]--;
}
}
@@ -2393,16 +2597,19 @@ namespace System {
// array that is castable to "T[]" (i.e. for primitivs and valuetypes, it will be exactly
// "T[]" - for orefs, it may be a "U[]" where U derives from T.)
//----------------------------------------------------------------------------------------
- sealed class SZArrayHelper {
+ internal sealed class SZArrayHelper
+ {
// It is never legal to instantiate this class.
- private SZArrayHelper() {
+ private SZArrayHelper()
+ {
Debug.Assert(false, "Hey! How'd I get here?");
}
// -----------------------------------------------------------
// ------- Implement IEnumerable<T> interface methods --------
// -----------------------------------------------------------
- internal IEnumerator<T> GetEnumerator<T>() {
+ internal IEnumerator<T> GetEnumerator<T>()
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
@@ -2413,7 +2620,8 @@ namespace System {
// -----------------------------------------------------------
// ------- Implement ICollection<T> interface methods --------
// -----------------------------------------------------------
- void CopyTo<T>(T[] array, int index) {
+ private void CopyTo<T>(T[] array, int index)
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
@@ -2421,7 +2629,8 @@ namespace System {
Array.Copy(_this, 0, array, index, _this.Length);
}
- internal int get_Count<T>() {
+ internal int get_Count<T>()
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
@@ -2431,70 +2640,82 @@ namespace System {
// -----------------------------------------------------------
// ---------- Implement IList<T> interface methods -----------
// -----------------------------------------------------------
- internal T get_Item<T>(int index) {
+ internal T get_Item<T>(int index)
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
- if ((uint)index >= (uint)_this.Length) {
+ if ((uint)index >= (uint)_this.Length)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
return _this[index];
}
- internal void set_Item<T>(int index, T value) {
+ internal void set_Item<T>(int index, T value)
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
- if ((uint)index >= (uint)_this.Length) {
+ if ((uint)index >= (uint)_this.Length)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
_this[index] = value;
}
- void Add<T>(T value) {
+ private void Add<T>(T value)
+ {
// Not meaningful for arrays.
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
- bool Contains<T>(T value) {
+ private bool Contains<T>(T value)
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
return Array.IndexOf(_this, value, 0, _this.Length) >= 0;
}
-
- bool get_IsReadOnly<T>() {
- return true;
+
+ private bool get_IsReadOnly<T>()
+ {
+ return true;
}
-
- void Clear<T>() {
+
+ private void Clear<T>()
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
- ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
+ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- int IndexOf<T>(T value) {
+ private int IndexOf<T>(T value)
+ {
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
return Array.IndexOf(_this, value, 0, _this.Length);
}
-
- void Insert<T>(int index, T value) {
+
+ private void Insert<T>(int index, T value)
+ {
// Not meaningful for arrays
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
- bool Remove<T>(T value) {
+ private bool Remove<T>(T value)
+ {
// Not meaningful for arrays
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
return default(bool);
}
- void RemoveAt<T>(int index) {
+ private void RemoveAt<T>(int index)
+ {
// Not meaningful for arrays
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection);
}
@@ -2502,7 +2723,9 @@ namespace System {
// This is a normal generic Enumerator for SZ arrays. It doesn't have any of the "this" stuff
// that SZArrayHelper does.
//
- [Serializable] private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T> {
+ [Serializable]
+ private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T>
+ {
private T[] _array;
private int _index;
private int _endIndex; // cache array length, since it's a little slow.
@@ -2510,37 +2733,45 @@ namespace System {
// Passing -1 for endIndex so that MoveNext always returns false without mutating _index
internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(null, -1);
- internal SZGenericArrayEnumerator(T[] array, int endIndex) {
+ internal SZGenericArrayEnumerator(T[] array, int endIndex)
+ {
// 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).");
_array = array;
_index = -1;
_endIndex = endIndex;
}
-
- public bool MoveNext() {
- if (_index < _endIndex) {
+
+ public bool MoveNext()
+ {
+ if (_index < _endIndex)
+ {
_index++;
return (_index < _endIndex);
}
return false;
}
-
- public T Current {
- get {
+
+ public T Current
+ {
+ get
+ {
if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
return _array[_index];
}
}
-
- object IEnumerator.Current {
- get {
+
+ object IEnumerator.Current
+ {
+ get
+ {
return Current;
}
}
- void IEnumerator.Reset() {
+ void IEnumerator.Reset()
+ {
_index = -1;
}
@@ -2551,8 +2782,3 @@ namespace System {
}
}
-// Useful in number of places that return an empty byte array to avoid unnecessary memory allocation.
-internal static class EmptyArray<T>
-{
- public static readonly T[] Value = new T[0];
-}
diff --git a/src/mscorlib/src/System/ArraySegment.cs b/src/mscorlib/src/System/ArraySegment.cs
index 03556e492a..a18590d5d8 100644
--- a/src/mscorlib/src/System/ArraySegment.cs
+++ b/src/mscorlib/src/System/ArraySegment.cs
@@ -15,6 +15,7 @@
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
namespace System
@@ -27,6 +28,10 @@ namespace System
[Serializable]
public struct ArraySegment<T> : IList<T>, IReadOnlyList<T>
{
+ // Do not replace the array allocation with Array.Empty. We don't want to have the overhead of
+ // instantiating another generic type in addition to ArraySegment<T> for new type parameters.
+ public static ArraySegment<T> Empty { get; } = new ArraySegment<T>(new T[0]);
+
private readonly T[] _array;
private readonly int _offset;
private readonly int _count;
@@ -45,8 +50,9 @@ namespace System
public ArraySegment(T[] array, int offset, int count)
{
// Validate arguments, check is minimal instructions with reduced branching for inlinable fast-path
+ // Negative values discovered though conversion to high values when converted to unsigned
// Failure should be rare and location determination and message is delegated to failure functions
- if (array == null || (offset | count) < 0 || (array.Length - offset < count))
+ if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset))
ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count);
Contract.EndContractBlock();
@@ -55,62 +61,37 @@ namespace System
_count = count;
}
- public T[] Array
- {
- get
- {
- Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
- || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
- "ArraySegment is invalid");
+ public T[] Array => _array;
- return _array;
- }
- }
+ public int Offset => _offset;
- public int Offset
+ public int Count => _count;
+
+ public T this[int index]
{
get
{
- // Since copying value types is not atomic & callers cannot atomically
- // read all three fields, we cannot guarantee that Offset is within
- // the bounds of Array. That is our intent, but let's not specify
- // it as a postcondition - force callers to re-verify this themselves
- // after reading each field out of an ArraySegment into their stack.
- Contract.Ensures(Contract.Result<int>() >= 0);
-
- Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
- || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
- "ArraySegment is invalid");
-
- return _offset;
- }
- }
+ if ((uint)index >= (uint)_count)
+ {
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
+ }
- public int Count
- {
- get
+ return _array[_offset + index];
+ }
+ set
{
- // Since copying value types is not atomic & callers cannot atomically
- // read all three fields, we cannot guarantee that Count is within
- // the bounds of Array. That's our intent, but let's not specify
- // it as a postcondition - force callers to re-verify this themselves
- // after reading each field out of an ArraySegment into their stack.
- Contract.Ensures(Contract.Result<int>() >= 0);
-
- Debug.Assert( (null == _array && 0 == _offset && 0 == _count)
- || (null != _array && _offset >= 0 && _count >= 0 && _offset + _count <= _array.Length),
- "ArraySegment is invalid");
-
- return _count;
+ if ((uint)index >= (uint)_count)
+ {
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
+ }
+
+ _array[_offset + index] = value;
}
}
public Enumerator GetEnumerator()
{
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- Contract.EndContractBlock();
-
+ ThrowInvalidOperationIfDefault();
return new Enumerator(this);
}
@@ -120,17 +101,38 @@ namespace System
{
return 0;
}
-
+
int hash = 5381;
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _offset);
hash = System.Numerics.Hashing.HashHelpers.Combine(hash, _count);
-
+
// The array hash is expected to be an evenly-distributed mixture of bits,
// so rather than adding the cost of another rotation we just xor it.
hash ^= _array.GetHashCode();
return hash;
}
+ public void CopyTo(T[] destination) => CopyTo(destination, 0);
+
+ public void CopyTo(T[] destination, int destinationIndex)
+ {
+ ThrowInvalidOperationIfDefault();
+ System.Array.Copy(_array, _offset, destination, destinationIndex, _count);
+ }
+
+ public void CopyTo(ArraySegment<T> destination)
+ {
+ ThrowInvalidOperationIfDefault();
+ destination.ThrowInvalidOperationIfDefault();
+
+ if (_count > destination._count)
+ {
+ ThrowHelper.ThrowArgumentException_DestinationTooShort();
+ }
+
+ System.Array.Copy(_array, _offset, destination._array, destination._offset, _count);
+ }
+
public override bool Equals(Object obj)
{
if (obj is ArraySegment<T>)
@@ -138,30 +140,69 @@ namespace System
else
return false;
}
-
+
public bool Equals(ArraySegment<T> obj)
{
return obj._array == _array && obj._offset == _offset && obj._count == _count;
}
-
+
+ public ArraySegment<T> Slice(int index)
+ {
+ ThrowInvalidOperationIfDefault();
+
+ if ((uint)index > (uint)_count)
+ {
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
+ }
+
+ return new ArraySegment<T>(_array, _offset + index, _count - index);
+ }
+
+ public ArraySegment<T> Slice(int index, int count)
+ {
+ ThrowInvalidOperationIfDefault();
+
+ if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index))
+ {
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
+ }
+
+ return new ArraySegment<T>(_array, _offset + index, count);
+ }
+
+ public T[] ToArray()
+ {
+ ThrowInvalidOperationIfDefault();
+
+ if (_count == 0)
+ {
+ return Empty._array;
+ }
+
+ var array = new T[_count];
+ System.Array.Copy(_array, _offset, array, 0, _count);
+ return array;
+ }
+
public static bool operator ==(ArraySegment<T> a, ArraySegment<T> b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(ArraySegment<T> a, ArraySegment<T> b)
{
return !(a == b);
}
+ public static implicit operator ArraySegment<T>(T[] array) => new ArraySegment<T>(array);
+
#region IList<T>
T IList<T>.this[int index]
{
get
{
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- if (index < 0 || index >= _count)
+ ThrowInvalidOperationIfDefault();
+ if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
@@ -170,8 +211,7 @@ namespace System
set
{
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
+ ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
@@ -182,9 +222,7 @@ namespace System
int IList<T>.IndexOf(T item)
{
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- Contract.EndContractBlock();
+ ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
@@ -210,8 +248,7 @@ namespace System
{
get
{
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
+ ThrowInvalidOperationIfDefault();
if (index < 0 || index >= _count)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.EndContractBlock();
@@ -244,9 +281,7 @@ namespace System
bool ICollection<T>.Contains(T item)
{
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- Contract.EndContractBlock();
+ ThrowInvalidOperationIfDefault();
int index = System.Array.IndexOf<T>(_array, item, _offset, _count);
@@ -256,15 +291,6 @@ namespace System
return index >= 0;
}
- void ICollection<T>.CopyTo(T[] array, int arrayIndex)
- {
- if (_array == null)
- ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
- Contract.EndContractBlock();
-
- System.Array.Copy(_array, _offset, array, arrayIndex, _count);
- }
-
bool ICollection<T>.Remove(T item)
{
ThrowHelper.ThrowNotSupportedException();
@@ -282,6 +308,14 @@ namespace System
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
+ private void ThrowInvalidOperationIfDefault()
+ {
+ if (_array == null)
+ {
+ ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray);
+ }
+ }
+
[Serializable]
public struct Enumerator : IEnumerator<T>
{
diff --git a/src/mscorlib/src/System/ArrayTypeMismatchException.cs b/src/mscorlib/src/System/ArrayTypeMismatchException.cs
deleted file mode 100644
index 3e941fdf8e..0000000000
--- a/src/mscorlib/src/System/ArrayTypeMismatchException.cs
+++ /dev/null
@@ -1,51 +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 arrays are of different primitive types.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The ArrayMismatchException is thrown when an attempt to store
- // an object of the wrong type within an array occurs.
- //
- [Serializable]
- public class ArrayTypeMismatchException : SystemException
- {
- // Creates a new ArrayMismatchException with its message string set to
- // the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
- // and its ExceptionInfo reference set to null.
- public ArrayTypeMismatchException()
- : base(SR.Arg_ArrayTypeMismatchException)
- {
- HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
- }
-
- // Creates a new ArrayMismatchException with its message string set to
- // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
- // and its ExceptionInfo reference set to null.
- //
- public ArrayTypeMismatchException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
- }
-
- public ArrayTypeMismatchException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
- }
-
- protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/AsyncCallback.cs b/src/mscorlib/src/System/AsyncCallback.cs
deleted file mode 100644
index 5c49535cff..0000000000
--- a/src/mscorlib/src/System/AsyncCallback.cs
+++ /dev/null
@@ -1,17 +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.
-
-/*============================================================
-**
-** Interface: AsyncCallbackDelegate
-**
-** Purpose: Type of callback for async operations
-**
-===========================================================*/
-
-namespace System
-{
- [Serializable]
- public delegate void AsyncCallback(IAsyncResult ar);
-}
diff --git a/src/mscorlib/src/System/Attribute.cs b/src/mscorlib/src/System/Attribute.cs
index b44e13f959..baa9a71638 100644
--- a/src/mscorlib/src/System/Attribute.cs
+++ b/src/mscorlib/src/System/Attribute.cs
@@ -3,19 +3,20 @@
// See the LICENSE file in the project root for more information.
-namespace System {
-
- using System;
- using System.Reflection;
- using System.Collections.Generic;
- using System.Runtime.InteropServices;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Security;
+using System;
+using System.Reflection;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Security;
+
+namespace System
+{
[Serializable]
- [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple=false)]
+ [AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
public abstract class Attribute
{
#region Private Statics
@@ -42,7 +43,7 @@ namespace System {
//if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
-
+
PropertyInfo baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
@@ -61,12 +62,12 @@ namespace System {
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
-
+
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
- if (!usage.Inherited)
+ if (!usage.Inherited)
return false;
//if this is an index we need to get the parameter types to help disambiguate
@@ -92,9 +93,9 @@ namespace System {
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
- MethodInfo propAccessor = property.GetGetMethod(true);
+ MethodInfo propAccessor = property.GetGetMethod(true);
- if (propAccessor == null)
+ if (propAccessor == null)
propAccessor = property.GetSetMethod(true);
RuntimeMethodInfo rtPropAccessor = propAccessor as RuntimeMethodInfo;
@@ -166,25 +167,25 @@ namespace System {
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
- if (rtAdd != null)
+ if (rtAdd != null)
return rtAdd.DeclaringType.GetEvent(ev.Name);
}
return null;
}
- private static bool InternalIsDefined (EventInfo element, Type attributeType, bool inherit)
+ private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit)
{
Contract.Requires(element != null);
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
-
+
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
- if (!usage.Inherited)
+ if (!usage.Inherited)
return false;
EventInfo baseEvent = GetParentDefinition(element);
@@ -244,14 +245,14 @@ namespace System {
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
- Object [] objAttr;
+ Object[] objAttr;
if (type == null)
type = typeof(Attribute);
- objAttr = param.GetCustomAttributes(type, false);
-
- for (int i =0;i < objAttr.Length;i++)
+ objAttr = param.GetCustomAttributes(type, false);
+
+ for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
@@ -260,26 +261,26 @@ namespace System {
}
// Get all the attributes that have Attribute as the base class
- Attribute [] ret = null;
- if (objAttr.Length == 0)
- ret = CreateAttributeArrayHelper(type,0);
- else
+ Attribute[] ret = null;
+ if (objAttr.Length == 0)
+ ret = CreateAttributeArrayHelper(type, 0);
+ else
ret = (Attribute[])objAttr;
-
+
if (param.Member.DeclaringType == null) // This is an interface so we are done.
return ret;
-
- if (!inherit)
+
+ if (!inherit)
return ret;
ParameterInfo baseParam = GetParentDefinition(param);
while (baseParam != null)
{
- objAttr = baseParam.GetCustomAttributes(type, false);
-
+ objAttr = baseParam.GetCustomAttributes(type, false);
+
int count = 0;
- for (int i =0;i < objAttr.Length;i++)
+ for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
@@ -295,10 +296,10 @@ namespace System {
}
// Get all the attributes that have Attribute as the base class
- Attribute [] attributes = CreateAttributeArrayHelper(type,count);
-
+ Attribute[] attributes = CreateAttributeArrayHelper(type, count);
+
count = 0;
- for (int i =0;i < objAttr.Length;i++)
+ for (int i = 0; i < objAttr.Length; i++)
{
if (objAttr[i] != null)
{
@@ -306,18 +307,18 @@ namespace System {
count++;
}
}
-
- Attribute [] temp = ret;
- ret = CreateAttributeArrayHelper(type,temp.Length + count);
- Array.Copy(temp,ret,temp.Length);
-
+
+ Attribute[] temp = ret;
+ ret = CreateAttributeArrayHelper(type, temp.Length + count);
+ Array.Copy(temp, ret, temp.Length);
+
int offset = temp.Length;
- for (int i =0;i < attributes.Length;i++)
+ for (int i = 0; i < attributes.Length; i++)
ret[offset + i] = attributes[i];
baseParam = GetParentDefinition(baseParam);
- }
+ }
return ret;
}
@@ -335,7 +336,7 @@ namespace System {
if (param.IsDefined(type, false))
return true;
-
+
if (param.Member.DeclaringType == null || !inherit) // This is an interface so we are done.
return false;
@@ -343,9 +344,9 @@ namespace System {
while (baseParam != null)
{
- Object[] objAttr = baseParam.GetCustomAttributes(type, false);
-
- for (int i =0; i < objAttr.Length; i++)
+ Object[] objAttr = baseParam.GetCustomAttributes(type, false);
+
+ for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
@@ -355,7 +356,7 @@ namespace System {
}
baseParam = GetParentDefinition(baseParam);
- }
+ }
return false;
}
@@ -363,15 +364,15 @@ namespace System {
#endregion
#region Utility
- private static void CopyToArrayList(List<Attribute> attributeList,Attribute[] attributes,Dictionary<Type, AttributeUsageAttribute> types)
+ private static void CopyToArrayList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
- for (int i = 0; i < attributes.Length; i++)
+ for (int i = 0; i < attributes.Length; i++)
{
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
- if (!types.ContainsKey(attrType))
+ if (!types.ContainsKey(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
@@ -393,21 +394,21 @@ namespace System {
return Array.Empty<Type>();
}
- private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
+ private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
- for (int i = 0; i < attributes.Length; i++)
+ for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
AttributeUsageAttribute usage = null;
types.TryGetValue(attrType, out usage);
- if (usage == null)
+ if (usage == null)
{
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
- if (usage.Inherited)
+ if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
@@ -421,7 +422,7 @@ namespace System {
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
// Check if the custom attributes is Inheritable
- Object [] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
+ Object[] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
if (obj.Length == 1)
return (AttributeUsageAttribute)obj[0];
@@ -430,7 +431,7 @@ namespace System {
return AttributeUsageAttribute.Default;
throw new FormatException(
- Environment.GetResourceString("Format_AttributeUsage", type));
+ SR.Format(SR.Format_AttributeUsage, type));
}
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
@@ -448,7 +449,7 @@ namespace System {
{
return GetCustomAttributes(element, type, true);
}
-
+
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
@@ -456,17 +457,17 @@ namespace System {
if (type == null)
throw new ArgumentNullException(nameof(type));
-
+
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
switch (element.MemberType)
{
- case MemberTypes.Property:
+ case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, type, inherit);
- case MemberTypes.Event:
+ case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, type, inherit);
default:
@@ -487,17 +488,17 @@ namespace System {
switch (element.MemberType)
{
- case MemberTypes.Property:
+ case MemberTypes.Property:
return InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit);
- case MemberTypes.Event:
+ case MemberTypes.Event:
return InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit);
default:
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
}
-
+
public static bool IsDefined(MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
@@ -511,23 +512,22 @@ namespace System {
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
-
+
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
- switch(element.MemberType)
+ switch (element.MemberType)
{
- case MemberTypes.Property:
+ case MemberTypes.Property:
return InternalIsDefined((PropertyInfo)element, attributeType, inherit);
- case MemberTypes.Event:
+ case MemberTypes.Event:
return InternalIsDefined((EventInfo)element, attributeType, inherit);
default:
return element.IsDefined(attributeType, inherit);
}
-
}
public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType)
@@ -545,7 +545,7 @@ namespace System {
if (attrib.Length == 1)
return attrib[0];
- throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
+ throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
@@ -555,7 +555,7 @@ namespace System {
{
return GetCustomAttributes(element, true);
}
-
+
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
return (Attribute[])GetCustomAttributes(element, attributeType, true);
@@ -568,17 +568,17 @@ namespace System {
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
-
+
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
if (element.Member == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element));
+ throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
Contract.EndContractBlock();
MemberInfo member = element.Member;
- if (member.MemberType == MemberTypes.Method && inherit)
+ if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, attributeType, inherit) as Attribute[];
return element.GetCustomAttributes(attributeType, inherit) as Attribute[];
@@ -590,14 +590,14 @@ namespace System {
throw new ArgumentNullException(nameof(element));
if (element.Member == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParameterInfo"), nameof(element));
+ throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
Contract.EndContractBlock();
MemberInfo member = element.Member;
- if (member.MemberType == MemberTypes.Method && inherit)
+ if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, null, inherit) as Attribute[];
-
+
return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[];
}
@@ -614,14 +614,14 @@ namespace System {
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
-
+
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
MemberInfo member = element.Member;
- switch(member.MemberType)
+ switch (member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
@@ -632,9 +632,9 @@ namespace System {
case MemberTypes.Property:
return element.IsDefined(attributeType, false);
- default:
+ default:
Debug.Assert(false, "Invalid type for ParameterInfo member in Attribute class");
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidParamInfo"));
+ throw new ArgumentException(SR.Argument_InvalidParamInfo);
}
}
@@ -658,7 +658,7 @@ namespace System {
if (attrib.Length == 1)
return attrib[0];
- throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
+ throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
@@ -666,7 +666,7 @@ namespace System {
#region Module
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
{
- return GetCustomAttributes (element, attributeType, true);
+ return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Module element)
@@ -692,7 +692,7 @@ namespace System {
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
@@ -713,10 +713,10 @@ namespace System {
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
- return element.IsDefined(attributeType,false);
+ return element.IsDefined(attributeType, false);
}
public static Attribute GetCustomAttribute(Module element, Type attributeType)
@@ -728,7 +728,7 @@ namespace System {
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
- Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
+ Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
@@ -736,7 +736,7 @@ namespace System {
if (attrib.Length == 1)
return attrib[0];
- throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
+ throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
@@ -756,7 +756,7 @@ namespace System {
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
@@ -776,12 +776,12 @@ namespace System {
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
- public static bool IsDefined (Assembly element, Type attributeType)
+ public static bool IsDefined(Assembly element, Type attributeType)
{
- return IsDefined (element, attributeType, true);
+ return IsDefined(element, attributeType, true);
}
- public static bool IsDefined (Assembly element, Type attributeType, bool inherit)
+ public static bool IsDefined(Assembly element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
@@ -791,7 +791,7 @@ namespace System {
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustHaveAttributeBaseClass"));
+ throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
Contract.EndContractBlock();
return element.IsDefined(attributeType, false);
@@ -799,14 +799,14 @@ namespace System {
public static Attribute GetCustomAttribute(Assembly element, Type attributeType)
{
- return GetCustomAttribute (element, attributeType, true);
+ return GetCustomAttribute(element, attributeType, true);
}
public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
- Attribute[] attrib = GetCustomAttributes(element,attributeType,inherit);
+ Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
@@ -814,7 +814,7 @@ namespace System {
if (attrib.Length == 1)
return attrib[0];
- throw new AmbiguousMatchException(Environment.GetResourceString("RFLCT.AmbigCust"));
+ throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
@@ -945,7 +945,7 @@ namespace System {
#region Public Virtual Members
public virtual Object TypeId { get { return GetType(); } }
-
+
public virtual bool Match(Object obj) { return Equals(obj); }
#endregion
diff --git a/src/mscorlib/src/System/AttributeTargets.cs b/src/mscorlib/src/System/AttributeTargets.cs
deleted file mode 100644
index fdfa4ab730..0000000000
--- a/src/mscorlib/src/System/AttributeTargets.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-
-namespace System
-{
- // Enum used to indicate all the elements of the
- // VOS it is valid to attach this element to.
- [Flags]
- [Serializable]
- public enum AttributeTargets
- {
- Assembly = 0x0001,
- Module = 0x0002,
- Class = 0x0004,
- Struct = 0x0008,
- Enum = 0x0010,
- Constructor = 0x0020,
- Method = 0x0040,
- Property = 0x0080,
- Field = 0x0100,
- Event = 0x0200,
- Interface = 0x0400,
- Parameter = 0x0800,
- Delegate = 0x1000,
- ReturnValue = 0x2000,
- GenericParameter = 0x4000,
-
- All = Assembly | Module | Class | Struct | Enum | Constructor |
- Method | Property | Field | Event | Interface | Parameter |
- Delegate | ReturnValue | GenericParameter
- }
-}
diff --git a/src/mscorlib/src/System/AttributeUsageAttribute.cs b/src/mscorlib/src/System/AttributeUsageAttribute.cs
deleted file mode 100644
index 33f7fd805e..0000000000
--- a/src/mscorlib/src/System/AttributeUsageAttribute.cs
+++ /dev/null
@@ -1,56 +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 class denotes how to specify the usage of an attribute
-**
-**
-===========================================================*/
-namespace System {
-
- using System.Reflection;
- /* By default, attributes are inherited and multiple attributes are not allowed */
-[Serializable]
- [AttributeUsage(AttributeTargets.Class, Inherited = true)]
- public sealed class AttributeUsageAttribute : Attribute
- {
- internal AttributeTargets m_attributeTarget = AttributeTargets.All; // Defaults to all
- internal bool m_allowMultiple = false; // Defaults to false
- internal bool m_inherited = true; // Defaults to true
-
- internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All);
-
- //Constructors
- public AttributeUsageAttribute(AttributeTargets validOn) {
- m_attributeTarget = validOn;
- }
- internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) {
- m_attributeTarget = validOn;
- m_allowMultiple = allowMultiple;
- m_inherited = inherited;
- }
-
-
- //Properties
- public AttributeTargets ValidOn
- {
- get{ return m_attributeTarget; }
- }
-
- public bool AllowMultiple
- {
- get { return m_allowMultiple; }
- set { m_allowMultiple = value; }
- }
-
- public bool Inherited
- {
- get { return m_inherited; }
- set { m_inherited = value; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/BCLDebug.cs b/src/mscorlib/src/System/BCLDebug.cs
index 7556b85789..67f7c9a0f7 100644
--- a/src/mscorlib/src/System/BCLDebug.cs
+++ b/src/mscorlib/src/System/BCLDebug.cs
@@ -11,8 +11,8 @@
**
============================================================*/
-namespace System {
-
+namespace System
+{
using System.IO;
using System.Text;
using System.Runtime.Remoting;
@@ -24,28 +24,32 @@ namespace System {
using System.Diagnostics.Contracts;
[Serializable]
- internal enum LogLevel {
- Trace = 0,
+ internal enum LogLevel
+ {
+ Trace = 0,
Status = 20,
- Warning= 40,
- Error = 50,
- Panic = 100,
+ Warning = 40,
+ Error = 50,
+ Panic = 100,
}
- internal struct SwitchStructure {
+ internal struct SwitchStructure
+ {
internal String name;
- internal int value;
-
- internal SwitchStructure (String n, int v) {
+ internal int value;
+
+ internal SwitchStructure(String n, int v)
+ {
name = n;
value = v;
}
}
-
+
// Only statics, does not need to be marked with the serializable attribute
- internal static class BCLDebug {
- internal static volatile bool m_registryChecked=false;
+ internal static class BCLDebug
+ {
+ internal static volatile bool m_registryChecked = false;
internal static volatile bool m_loggingNotEnabled = false;
internal static bool m_perfWarnings;
internal static bool m_correctnessWarnings;
@@ -54,7 +58,7 @@ namespace System {
internal static volatile bool m_domainUnloadAdded;
#endif
- static readonly SwitchStructure[] switches = {
+ private static readonly SwitchStructure[] switches = {
new SwitchStructure("NLS", 0x00000001),
new SwitchStructure("SER", 0x00000002),
new SwitchStructure("DYNIL",0x00000004),
@@ -64,14 +68,14 @@ namespace System {
new SwitchStructure("REMOTINGCHANNELS",0x00000040),
new SwitchStructure("CACHE",0x00000080),
new SwitchStructure("RESMGRFILEFORMAT", 0x00000100), // .resources files
- new SwitchStructure("PERF", 0x00000200),
- new SwitchStructure("CORRECTNESS", 0x00000400),
- new SwitchStructure("MEMORYFAILPOINT", 0x00000800),
+ new SwitchStructure("PERF", 0x00000200),
+ new SwitchStructure("CORRECTNESS", 0x00000400),
+ new SwitchStructure("MEMORYFAILPOINT", 0x00000800),
new SwitchStructure("DATETIME", 0x00001000), // System.DateTime managed tracing
new SwitchStructure("INTEROP", 0x00002000), // Interop tracing
};
- static readonly LogLevel[] levelConversions = {
+ private static readonly LogLevel[] levelConversions = {
LogLevel.Panic,
LogLevel.Error,
LogLevel.Error,
@@ -89,24 +93,28 @@ namespace System {
#if _DEBUG
internal static void WaitForFinalizers(Object sender, EventArgs e)
{
- if (!m_registryChecked) {
+ if (!m_registryChecked)
+ {
CheckRegistry();
}
- if (m_correctnessWarnings) {
+ if (m_correctnessWarnings)
+ {
GC.GetTotalMemory(true);
GC.WaitForPendingFinalizers();
}
}
#endif
[Conditional("_DEBUG")]
- static public void Assert(bool condition) {
+ static public void Assert(bool condition)
+ {
#if _DEBUG
Assert(condition, "Assert failed.");
#endif
}
[Conditional("_DEBUG")]
- static public void Assert(bool condition, String message) {
+ static public void Assert(bool condition, String message)
+ {
#if _DEBUG
// Speed up debug builds marginally by avoiding the garbage from
// concatinating "BCL Assert: " and the message.
@@ -114,13 +122,15 @@ namespace System {
System.Diagnostics.Assert.Check(condition, "BCL Assert", message);
#endif
}
-
+
[Pure]
[Conditional("_LOGGING")]
- static public void Log(String message) {
+ static public void Log(String message)
+ {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
- if (!m_registryChecked) {
+ if (!m_registryChecked)
+ {
CheckRegistry();
}
System.Diagnostics.Log.Trace(message);
@@ -129,23 +139,29 @@ namespace System {
[Pure]
[Conditional("_LOGGING")]
- static public void Log(String switchName, String message) {
+ static public void Log(String switchName, String message)
+ {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
- if (!m_registryChecked) {
+ if (!m_registryChecked)
+ {
CheckRegistry();
}
- try {
+ try
+ {
LogSwitch ls;
ls = LogSwitch.GetSwitch(switchName);
- if (ls!=null) {
- System.Diagnostics.Log.Trace(ls,message);
- System.Diagnostics.Log.Trace(ls,Environment.NewLine);
+ if (ls != null)
+ {
+ System.Diagnostics.Log.Trace(ls, message);
+ System.Diagnostics.Log.Trace(ls, Environment.NewLine);
}
- } catch {
+ }
+ catch
+ {
System.Diagnostics.Log.Trace("Exception thrown in logging." + Environment.NewLine);
- System.Diagnostics.Log.Trace("Switch was: " + ((switchName==null)?"<null>":switchName) + Environment.NewLine);
- System.Diagnostics.Log.Trace("Message was: " + ((message==null)?"<null>":message) + Environment.NewLine);
+ System.Diagnostics.Log.Trace("Switch was: " + ((switchName == null) ? "<null>" : switchName) + Environment.NewLine);
+ System.Diagnostics.Log.Trace("Message was: " + ((message == null) ? "<null>" : message) + Environment.NewLine);
}
}
@@ -156,38 +172,46 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel, out bool perfWarnings, out bool correctnessWarnings, out bool safeHandleStackTraces);
- private static void CheckRegistry() {
+ private static void CheckRegistry()
+ {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
- if (m_registryChecked) {
+ if (m_registryChecked)
+ {
return;
}
-
+
m_registryChecked = true;
bool loggingEnabled;
bool logToConsole;
- int logLevel;
- int facilityValue;
+ int logLevel;
+ int facilityValue;
facilityValue = GetRegistryLoggingValues(out loggingEnabled, out logToConsole, out logLevel, out m_perfWarnings, out m_correctnessWarnings, out m_safeHandleStackTraces);
// Note we can get into some recursive situations where we call
// ourseves recursively through the .cctor. That's why we have the
// check for levelConversions == null.
- if (!loggingEnabled) {
+ if (!loggingEnabled)
+ {
m_loggingNotEnabled = true;
}
- if (loggingEnabled && levelConversions!=null) {
- try {
+ if (loggingEnabled && levelConversions != null)
+ {
+ try
+ {
//The values returned for the logging levels in the registry don't map nicely onto the
//values which we support internally (which are an approximation of the ones that
//the System.Diagnostics namespace uses) so we have a quick map.
- Assert(logLevel>=0 && logLevel<=10, "logLevel>=0 && logLevel<=10");
+ Assert(logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10");
logLevel = (int)levelConversions[logLevel];
-
- if (facilityValue>0) {
- for (int i=0; i<switches.Length; i++) {
- if ((switches[i].value & facilityValue)!=0) {
+
+ if (facilityValue > 0)
+ {
+ for (int i = 0; i < switches.Length; i++)
+ {
+ if ((switches[i].value & facilityValue) != 0)
+ {
LogSwitch L = new LogSwitch(switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch);
L.MinimumLevel = (LoggingLevels)logLevel;
}
@@ -195,65 +219,80 @@ namespace System {
System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel;
System.Diagnostics.Log.IsConsoleEnabled = logToConsole;
}
-
- } catch {
+ }
+ catch
+ {
//Silently eat any exceptions.
}
}
}
- internal static bool CheckEnabled(String switchName) {
+ internal static bool CheckEnabled(String switchName)
+ {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return false;
if (!m_registryChecked)
CheckRegistry();
LogSwitch logSwitch = LogSwitch.GetSwitch(switchName);
- if (logSwitch==null) {
+ if (logSwitch == null)
+ {
return false;
}
- return ((int)logSwitch.MinimumLevel<=(int)LogLevel.Trace);
+ return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace);
}
- private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch) {
+ private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch)
+ {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
{
logSwitch = null;
return false;
}
logSwitch = LogSwitch.GetSwitch(switchName);
- if (logSwitch==null) {
+ if (logSwitch == null)
+ {
return false;
}
- return ((int)logSwitch.MinimumLevel<=(int)level);
+ return ((int)logSwitch.MinimumLevel <= (int)level);
}
[Pure]
[Conditional("_LOGGING")]
- public static void Log(String switchName, LogLevel level, params Object[]messages) {
+ public static void Log(String switchName, LogLevel level, params Object[] messages)
+ {
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
//Add code to check if logging is enabled in the registry.
LogSwitch logSwitch;
- if (!m_registryChecked) {
+ if (!m_registryChecked)
+ {
CheckRegistry();
}
- if (!CheckEnabled(switchName, level, out logSwitch)) {
+ if (!CheckEnabled(switchName, level, out logSwitch))
+ {
return;
}
StringBuilder sb = StringBuilderCache.Acquire();
- for (int i=0; i<messages.Length; i++) {
+ for (int i = 0; i < messages.Length; i++)
+ {
String s;
- try {
- if (messages[i]==null) {
+ try
+ {
+ if (messages[i] == null)
+ {
s = "<null>";
- } else {
+ }
+ else
+ {
s = messages[i].ToString();
}
- } catch {
+ }
+ catch
+ {
s = "<unable to convert>";
}
sb.Append(s);
@@ -263,13 +302,16 @@ namespace System {
[Pure]
[Conditional("_LOGGING")]
- public static void Trace(String switchName, String format, params Object[] messages) {
- if (m_loggingNotEnabled) {
+ public static void Trace(String switchName, String format, params Object[] messages)
+ {
+ if (m_loggingNotEnabled)
+ {
return;
}
LogSwitch logSwitch;
- if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch)) {
+ if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch))
+ {
return;
}
@@ -292,8 +334,9 @@ namespace System {
if (!m_perfWarnings)
return;
- if (!expr) {
- Log("PERF", "BCL Perf Warning: "+msg);
+ if (!expr)
+ {
+ Log("PERF", "BCL Perf Warning: " + msg);
}
System.Diagnostics.Assert.Check(expr, "BCL Perf Warning: Your perf may be less than perfect because...", msg);
}
@@ -313,13 +356,15 @@ namespace System {
if (!m_correctnessWarnings)
return;
- if (!m_domainUnloadAdded) {
+ if (!m_domainUnloadAdded)
+ {
m_domainUnloadAdded = true;
AppDomain.CurrentDomain.DomainUnload += new EventHandler(WaitForFinalizers);
}
- if (!expr) {
- Log("CORRECTNESS", "BCL Correctness Warning: "+msg);
+ if (!expr)
+ {
+ Log("CORRECTNESS", "BCL Correctness Warning: " + msg);
}
System.Diagnostics.Assert.Check(expr, "BCL Correctness Warning: Your program may not work because...", msg);
#endif
@@ -327,8 +372,10 @@ namespace System {
// Whether SafeHandles include a stack trace showing where they
// were allocated. Only useful in checked & debug builds.
- internal static bool SafeHandleStackTracesEnabled {
- get {
+ internal static bool SafeHandleStackTracesEnabled
+ {
+ get
+ {
#if _DEBUG
if (!m_registryChecked)
CheckRegistry();
diff --git a/src/mscorlib/src/System/BadImageFormatException.cs b/src/mscorlib/src/System/BadImageFormatException.cs
index 51a6c40771..42005cccce 100644
--- a/src/mscorlib/src/System/BadImageFormatException.cs
+++ b/src/mscorlib/src/System/BadImageFormatException.cs
@@ -11,8 +11,8 @@
**
===========================================================*/
-namespace System {
-
+namespace System
+{
using System;
using System.Runtime.Serialization;
using FileLoadException = System.IO.FileLoadException;
@@ -20,41 +20,46 @@ namespace System {
using System.Globalization;
[Serializable]
- public class BadImageFormatException : SystemException {
-
+ public class BadImageFormatException : SystemException
+ {
private String _fileName; // The name of the corrupt PE file.
private String _fusionLog; // fusion log (when applicable)
- public BadImageFormatException()
- : base(Environment.GetResourceString("Arg_BadImageFormatException")) {
- SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
+ public BadImageFormatException()
+ : base(SR.Arg_BadImageFormatException)
+ {
+ HResult = __HResults.COR_E_BADIMAGEFORMAT;
}
-
- public BadImageFormatException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
+
+ public BadImageFormatException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_BADIMAGEFORMAT;
}
-
- public BadImageFormatException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
+
+ public BadImageFormatException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_BADIMAGEFORMAT;
}
public BadImageFormatException(String message, String fileName) : base(message)
{
- SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
+ HResult = __HResults.COR_E_BADIMAGEFORMAT;
_fileName = fileName;
}
- public BadImageFormatException(String message, String fileName, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_BADIMAGEFORMAT);
+ public BadImageFormatException(String message, String fileName, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_BADIMAGEFORMAT;
_fileName = fileName;
}
public override String Message
{
- get {
+ get
+ {
SetMessageField();
return _message;
}
@@ -62,17 +67,19 @@ namespace System {
private void SetMessageField()
{
- if (_message == null) {
+ if (_message == null)
+ {
if ((_fileName == null) &&
(HResult == System.__HResults.COR_E_EXCEPTION))
- _message = Environment.GetResourceString("Arg_BadImageFormatException");
+ _message = SR.Arg_BadImageFormatException;
else
_message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult);
}
}
- public String FileName {
+ public String FileName
+ {
get { return _fileName; }
}
@@ -81,8 +88,8 @@ namespace System {
String s = GetType().FullName + ": " + Message;
if (_fileName != null && _fileName.Length != 0)
- s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
+ s += Environment.NewLine + SR.Format(SR.IO_FileName_Name, _fileName);
+
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
@@ -90,23 +97,23 @@ namespace System {
s += Environment.NewLine + StackTrace;
try
{
- if(FusionLog!=null)
+ if (FusionLog != null)
{
- if (s==null)
- s=" ";
- s+=Environment.NewLine;
- s+=Environment.NewLine;
- s+=FusionLog;
+ if (s == null)
+ s = " ";
+ s += Environment.NewLine;
+ s += Environment.NewLine;
+ s += FusionLog;
}
}
- catch(SecurityException)
+ catch (SecurityException)
{
-
}
return s;
}
- protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
// Base class constructor will check info != null.
_fileName = info.GetString("BadImageFormat_FileName");
@@ -114,7 +121,7 @@ namespace System {
{
_fusionLog = info.GetString("BadImageFormat_FusionLog");
}
- catch
+ catch
{
_fusionLog = null;
}
@@ -123,19 +130,21 @@ namespace System {
private BadImageFormatException(String fileName, String fusionLog, int hResult)
: base(null)
{
- SetErrorCode(hResult);
+ HResult = hResult;
_fileName = fileName;
- _fusionLog=fusionLog;
+ _fusionLog = fusionLog;
SetMessageField();
}
- public String FusionLog {
+ public String FusionLog
+ {
#pragma warning disable CS0618 // Type or member is obsolete
#pragma warning restore CS0618 // Type or member is obsolete
get { return _fusionLog; }
}
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
diff --git a/src/mscorlib/src/System/BitConverter.cs b/src/mscorlib/src/System/BitConverter.cs
index 07af5a8178..a17a067bec 100644
--- a/src/mscorlib/src/System/BitConverter.cs
+++ b/src/mscorlib/src/System/BitConverter.cs
@@ -2,31 +2,19 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-** Purpose: Allows developers to view the base data types as
-** an arbitrary array of bits.
-**
-**
-===========================================================*/
-namespace System {
-
- using System;
- using System.Runtime.CompilerServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Security;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+using System.Security;
+namespace System
+{
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
- //
- // Only statics, does not need to be marked with the serializable attribute
- public static class BitConverter {
-
+ public static class BitConverter
+ {
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
@@ -36,378 +24,299 @@ namespace System {
public static readonly bool IsLittleEndian = true;
#endif
- // Converts a byte into an array of bytes with length one.
- public static byte[] GetBytes(bool value) {
+ // Converts a Boolean into an array of bytes with length one.
+ public static byte[] GetBytes(bool value)
+ {
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == 1);
byte[] r = new byte[1];
- r[0] = (value ? (byte)Boolean.True : (byte)Boolean.False );
+ r[0] = (value ? (byte)1 : (byte)0);
return r;
}
-
+
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 2);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(char));
- return GetBytes((short)value);
+ byte[] bytes = new byte[sizeof(char)];
+ Unsafe.As<byte, char>(ref bytes[0]) = value;
+ return bytes;
}
-
+
// Converts a short into an array of bytes with length
// two.
- public unsafe static byte[] GetBytes(short value)
+ public static byte[] GetBytes(short value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 2);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(short));
- byte[] bytes = new byte[2];
- fixed(byte* b = &bytes[0])
- *((short*)b) = value;
+ byte[] bytes = new byte[sizeof(short)];
+ Unsafe.As<byte, short>(ref bytes[0]) = value;
return bytes;
}
// Converts an int into an array of bytes with length
// four.
- public unsafe static byte[] GetBytes(int value)
+ public static byte[] GetBytes(int value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 4);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(int));
- byte[] bytes = new byte[4];
- fixed(byte* b = &bytes[0])
- *((int*)b) = value;
+ byte[] bytes = new byte[sizeof(int)];
+ Unsafe.As<byte, int>(ref bytes[0]) = value;
return bytes;
}
-
+
// Converts a long into an array of bytes with length
// eight.
- public unsafe static byte[] GetBytes(long value)
+ public static byte[] GetBytes(long value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 8);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(long));
- byte[] bytes = new byte[8];
- fixed(byte* b = &bytes[0])
- *((long*)b) = value;
+ byte[] bytes = new byte[sizeof(long)];
+ Unsafe.As<byte, long>(ref bytes[0]) = value;
return bytes;
}
-
+
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
- public static byte[] GetBytes(ushort value) {
+ public static byte[] GetBytes(ushort value)
+ {
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 2);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(ushort));
- return GetBytes((short)value);
+ byte[] bytes = new byte[sizeof(ushort)];
+ Unsafe.As<byte, ushort>(ref bytes[0]) = value;
+ return bytes;
}
-
+
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
- public static byte[] GetBytes(uint value) {
+ public static byte[] GetBytes(uint value)
+ {
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 4);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(uint));
- return GetBytes((int)value);
+ byte[] bytes = new byte[sizeof(uint)];
+ Unsafe.As<byte, uint>(ref bytes[0]) = value;
+ return bytes;
}
-
+
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
- public static byte[] GetBytes(ulong value) {
+ public static byte[] GetBytes(ulong value)
+ {
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 8);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(ulong));
- return GetBytes((long)value);
+ byte[] bytes = new byte[sizeof(ulong)];
+ Unsafe.As<byte, ulong>(ref bytes[0]) = value;
+ return bytes;
}
-
+
// Converts a float into an array of bytes with length
// four.
- public unsafe static byte[] GetBytes(float value)
+ public static byte[] GetBytes(float value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 4);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(float));
- return GetBytes(*(int*)&value);
+ byte[] bytes = new byte[sizeof(float)];
+ Unsafe.As<byte, float>(ref bytes[0]) = value;
+ return bytes;
}
-
+
// Converts a double into an array of bytes with length
// eight.
- public unsafe static byte[] GetBytes(double value)
+ public static byte[] GetBytes(double value)
{
Contract.Ensures(Contract.Result<byte[]>() != null);
- Contract.Ensures(Contract.Result<byte[]>().Length == 8);
+ Contract.Ensures(Contract.Result<byte[]>().Length == sizeof(double));
- return GetBytes(*(long*)&value);
+ byte[] bytes = new byte[sizeof(double)];
+ Unsafe.As<byte, double>(ref bytes[0]) = value;
+ return bytes;
}
// Converts an array of bytes into a char.
- public static char ToChar(byte[] value, int startIndex)
+ public static char ToChar(byte[] value, int startIndex) => unchecked((char)ReadInt16(value, startIndex));
+
+ private static short ReadInt16(byte[] value, int startIndex)
{
- if (value == null) {
+ if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- }
-
- if ((uint)startIndex >= value.Length) {
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- }
-
- if (startIndex > value.Length - 2) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- }
+ if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ if (startIndex > value.Length - sizeof(short))
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
- return (char)ToInt16(value, startIndex);
+ return Unsafe.ReadUnaligned<short>(ref value[startIndex]);
}
-
- // Converts an array of bytes into a short.
- public static unsafe short ToInt16(byte[] value, int startIndex) {
- if( value == null) {
+
+ private static int ReadInt32(byte[] value, int startIndex)
+ {
+ if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- }
-
- if ((uint) startIndex >= value.Length) {
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- }
-
- if (startIndex > value.Length -2) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- }
+ if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ if (startIndex > value.Length - sizeof(int))
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
- fixed( byte * pbyte = &value[startIndex]) {
- if( startIndex % 2 == 0) { // data is aligned
- return *((short *) pbyte);
- }
- else {
- if( IsLittleEndian) {
- return (short)((*pbyte) | (*(pbyte + 1) << 8)) ;
- }
- else {
- return (short)((*pbyte << 8) | (*(pbyte + 1)));
- }
- }
- }
-
+ return Unsafe.ReadUnaligned<int>(ref value[startIndex]);
}
-
- // Converts an array of bytes into an int.
- public static unsafe int ToInt32 (byte[] value, int startIndex) {
- if( value == null) {
+
+ private static long ReadInt64(byte[] value, int startIndex)
+ {
+ if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- }
-
- if ((uint) startIndex >= value.Length) {
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- }
-
- if (startIndex > value.Length -4) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- }
+ if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
+ if (startIndex > value.Length - sizeof(long))
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
- fixed( byte * pbyte = &value[startIndex]) {
- if( startIndex % 4 == 0) { // data is aligned
- return *((int *) pbyte);
- }
- else {
- if( IsLittleEndian) {
- return (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
- }
- else {
- return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
- }
- }
- }
+ return Unsafe.ReadUnaligned<long>(ref value[startIndex]);
}
-
+
+ // Converts an array of bytes into a short.
+ public static short ToInt16(byte[] value, int startIndex) => ReadInt16(value, startIndex);
+
+ // Converts an array of bytes into an int.
+ public static int ToInt32(byte[] value, int startIndex) => ReadInt32(value, startIndex);
+
// Converts an array of bytes into a long.
- public static unsafe long ToInt64 (byte[] value, int startIndex) {
- if (value == null) {
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- }
-
- if ((uint) startIndex >= value.Length) {
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- }
-
- if (startIndex > value.Length -8) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- }
- Contract.EndContractBlock();
+ public static long ToInt64(byte[] value, int startIndex) => ReadInt64(value, startIndex);
- fixed( byte * pbyte = &value[startIndex]) {
- if( startIndex % 8 == 0) { // data is aligned
- return *((long *) pbyte);
- }
- else {
- if( IsLittleEndian) {
- int i1 = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
- int i2 = (*(pbyte+4)) | (*(pbyte + 5) << 8) | (*(pbyte + 6) << 16) | (*(pbyte + 7) << 24);
- return (uint)i1 | ((long)i2 << 32);
- }
- else {
- int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3));
- int i2 = (*(pbyte+4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7));
- return (uint)i2 | ((long)i1 << 32);
- }
- }
- }
- }
-
-
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
- public static ushort ToUInt16(byte[] value, int startIndex)
- {
- if (value == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- if (startIndex > value.Length - 2)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- Contract.EndContractBlock();
+ public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ReadInt16(value, startIndex));
- return (ushort)ToInt16(value, startIndex);
- }
-
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
- public static uint ToUInt32(byte[] value, int startIndex)
- {
- if (value == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- if (startIndex > value.Length - 4)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- Contract.EndContractBlock();
+ public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ReadInt32(value, startIndex));
- return (uint)ToInt32(value, startIndex);
- }
-
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
- public static ulong ToUInt64(byte[] value, int startIndex)
- {
- if (value == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- if (startIndex > value.Length - 8)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- Contract.EndContractBlock();
+ public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ReadInt64(value, startIndex));
- return (ulong)ToInt64(value, startIndex);
- }
-
// Converts an array of bytes into a float.
- unsafe public static float ToSingle (byte[] value, int startIndex)
+ public static unsafe float ToSingle(byte[] value, int startIndex)
{
- if (value == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- if (startIndex > value.Length - 4)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- Contract.EndContractBlock();
-
- int val = ToInt32(value, startIndex);
+ int val = ReadInt32(value, startIndex);
return *(float*)&val;
}
-
+
// Converts an array of bytes into a double.
- unsafe public static double ToDouble (byte[] value, int startIndex)
+ public static unsafe double ToDouble(byte[] value, int startIndex)
{
- if (value == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
- if ((uint)startIndex >= value.Length)
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
- if (startIndex > value.Length - 8)
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
- Contract.EndContractBlock();
-
- long val = ToInt64(value, startIndex);
+ long val = ReadInt64(value, startIndex);
return *(double*)&val;
}
-
- private static char GetHexValue(int i) {
- Debug.Assert( i >=0 && i <16, "i is out of range.");
- if (i<10) {
+
+ private static char GetHexValue(int i)
+ {
+ Debug.Assert(i >= 0 && i < 16, "i is out of range.");
+ if (i < 10)
+ {
return (char)(i + '0');
}
-
+
return (char)(i - 10 + 'A');
}
// Converts an array of bytes into a String.
- public static String ToString (byte[] value, int startIndex, int length) {
- if (value == null) {
- throw new ArgumentNullException(nameof(value));
- }
-
- if (startIndex < 0 || startIndex >= value.Length && startIndex > 0) { // Don't throw for a 0 length array.
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- }
-
- if (length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- }
-
- if (startIndex > value.Length - length) {
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
- }
+ public static string ToString(byte[] value, int startIndex, int length)
+ {
+ if (value == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
+ if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);;
+ if (length < 0)
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
+ if (startIndex > value.Length - length)
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
Contract.EndContractBlock();
- if (length == 0) {
+ if (length == 0)
+ {
return string.Empty;
}
- if (length > (Int32.MaxValue / 3)) {
+ if (length > (int.MaxValue / 3))
+ {
// (Int32.MaxValue / 3) == 715,827,882 Bytes == 699 MB
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthTooLarge", (Int32.MaxValue / 3)));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
}
int chArrayLength = length * 3;
-
- char[] chArray = new char[chArrayLength];
- int i = 0;
- int index = startIndex;
- for (i = 0; i < chArrayLength; i += 3) {
- byte b = value[index++];
- chArray[i]= GetHexValue(b/16);
- chArray[i+1] = GetHexValue(b%16);
- chArray[i+2] = '-';
+ const int StackLimit = 512; // arbitrary limit to switch from stack to heap allocation
+ unsafe
+ {
+ if (chArrayLength < StackLimit)
+ {
+ char* chArrayPtr = stackalloc char[chArrayLength];
+ return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
+ }
+ else
+ {
+ char[] chArray = new char[chArrayLength];
+ fixed (char* chArrayPtr = &chArray[0])
+ return ToString(value, startIndex, length, chArrayPtr, chArrayLength);
+ }
+ }
+ }
+
+ private static unsafe string ToString(byte[] value, int startIndex, int length, char* chArray, int chArrayLength)
+ {
+ Debug.Assert(length > 0);
+ Debug.Assert(chArrayLength == length * 3);
+
+ char* p = chArray;
+ int endIndex = startIndex + length;
+ for (int i = startIndex; i < endIndex; i++)
+ {
+ byte b = value[i];
+ *p++ = GetHexValue(b >> 4);
+ *p++ = GetHexValue(b & 0xF);
+ *p++ = '-';
}
// We don't need the last '-' character
- return new String(chArray, 0, chArray.Length - 1);
+ return new string(chArray, 0, chArrayLength - 1);
}
-
+
// Converts an array of bytes into a String.
- public static String ToString(byte [] value) {
+ public static string ToString(byte[] value)
+ {
if (value == null)
- throw new ArgumentNullException(nameof(value));
- Contract.Ensures(Contract.Result<String>() != null);
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
+ Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
return ToString(value, 0, value.Length);
}
-
+
// Converts an array of bytes into a String.
- public static String ToString (byte [] value, int startIndex) {
+ public static string ToString(byte[] value, int startIndex)
+ {
if (value == null)
- throw new ArgumentNullException(nameof(value));
- Contract.Ensures(Contract.Result<String>() != null);
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
+ Contract.Ensures(Contract.Result<string>() != null);
Contract.EndContractBlock();
return ToString(value, startIndex, value.Length - startIndex);
}
-
+
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
@@ -417,31 +326,36 @@ namespace System {
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
- public static bool ToBoolean(byte[] value, int startIndex) {
- if (value==null)
- throw new ArgumentNullException(nameof(value));
+ public static bool ToBoolean(byte[] value, int startIndex)
+ {
+ if (value == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);;
if (startIndex > value.Length - 1)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);; // differs from other overloads, which throw base ArgumentException
Contract.EndContractBlock();
-
- return (value[startIndex]==0)?false:true;
+
+ return value[startIndex] != 0;
}
- public static unsafe long DoubleToInt64Bits(double value) {
- return *((long *)&value);
+ public static unsafe long DoubleToInt64Bits(double value)
+ {
+ return *((long*)&value);
}
- public static unsafe double Int64BitsToDouble(long value) {
+ public static unsafe double Int64BitsToDouble(long value)
+ {
return *((double*)&value);
}
- public static unsafe int SingleToInt32Bits(float value) {
+ public static unsafe int SingleToInt32Bits(float value)
+ {
return *((int*)&value);
}
- public static unsafe float Int32BitsToSingle(int value) {
+ public static unsafe float Int32BitsToSingle(int value)
+ {
return *((float*)&value);
}
}
diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/src/System/Boolean.cs
index c085b0a020..fe25e22920 100644
--- a/src/mscorlib/src/System/Boolean.cs
+++ b/src/mscorlib/src/System/Boolean.cs
@@ -11,105 +11,113 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Diagnostics.Contracts;
+
+using System;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// The Boolean class provides the
// object representation of the boolean primitive type.
[Serializable]
- public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean>
+ public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean>
{
-
- //
- // Member Variables
- //
- private bool m_value;
-
- // The true value.
- //
- internal const int True = 1;
-
- // The false value.
- //
- internal const int False = 0;
-
-
- //
- // Internal Constants are real consts for performance.
- //
-
- // The internal string representation of true.
- //
- internal const String TrueLiteral = "True";
-
- // The internal string representation of false.
- //
- internal const String FalseLiteral = "False";
-
-
- //
- // Public Constants
- //
-
- // The public string representation of true.
- //
- public static readonly String TrueString = TrueLiteral;
-
- // The public string representation of false.
- //
- public static readonly String FalseString = FalseLiteral;
-
- //
- // Overriden Instance Methods
- //
- /*=================================GetHashCode==================================
- **Args: None
- **Returns: 1 or 0 depending on whether this instance represents true or false.
- **Exceptions: None
- **Overriden From: Value
- ==============================================================================*/
- // Provides a hash code for this instance.
- public override int GetHashCode() {
- return (m_value)?True:False;
- }
-
- /*===================================ToString===================================
- **Args: None
- **Returns: "True" or "False" depending on the state of the boolean.
- **Exceptions: None.
- ==============================================================================*/
- // Converts the boolean value of this instance to a String.
- public override String ToString() {
- if (false == m_value) {
- return FalseLiteral;
+ //
+ // Member Variables
+ //
+ private bool m_value;
+
+ // The true value.
+ //
+ internal const int True = 1;
+
+ // The false value.
+ //
+ internal const int False = 0;
+
+
+ //
+ // Internal Constants are real consts for performance.
+ //
+
+ // The internal string representation of true.
+ //
+ internal const String TrueLiteral = "True";
+
+ // The internal string representation of false.
+ //
+ internal const String FalseLiteral = "False";
+
+
+ //
+ // Public Constants
+ //
+
+ // The public string representation of true.
+ //
+ public static readonly String TrueString = TrueLiteral;
+
+ // The public string representation of false.
+ //
+ public static readonly String FalseString = FalseLiteral;
+
+ //
+ // Overriden Instance Methods
+ //
+ /*=================================GetHashCode==================================
+ **Args: None
+ **Returns: 1 or 0 depending on whether this instance represents true or false.
+ **Exceptions: None
+ **Overriden From: Value
+ ==============================================================================*/
+ // Provides a hash code for this instance.
+ public override int GetHashCode()
+ {
+ return (m_value) ? True : False;
}
- return TrueLiteral;
- }
- public String ToString(IFormatProvider provider) {
- if (false == m_value) {
- return FalseLiteral;
+ /*===================================ToString===================================
+ **Args: None
+ **Returns: "True" or "False" depending on the state of the boolean.
+ **Exceptions: None.
+ ==============================================================================*/
+ // Converts the boolean value of this instance to a String.
+ public override String ToString()
+ {
+ if (false == m_value)
+ {
+ return FalseLiteral;
+ }
+ return TrueLiteral;
}
- return TrueLiteral;
- }
-
- // Determines whether two Boolean objects are equal.
- public override bool Equals (Object obj) {
- //If it's not a boolean, we're definitely not equal
- if (!(obj is Boolean)) {
- return false;
+
+ public String ToString(IFormatProvider provider)
+ {
+ if (false == m_value)
+ {
+ return FalseLiteral;
+ }
+ return TrueLiteral;
}
-
- return (m_value==((Boolean)obj).m_value);
- }
- [System.Runtime.Versioning.NonVersionable]
- public bool Equals(Boolean obj)
- {
- return m_value == obj;
- }
+ // Determines whether two Boolean objects are equal.
+ public override bool Equals(Object obj)
+ {
+ //If it's not a boolean, we're definitely not equal
+ if (!(obj is Boolean))
+ {
+ return false;
+ }
+
+ return (m_value == ((Boolean)obj).m_value);
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public bool Equals(Boolean obj)
+ {
+ return m_value == obj;
+ }
// Compares this object to another object, returning an integer that
// indicates the relationship. For booleans, false sorts before true.
@@ -118,63 +126,80 @@ namespace System {
//
// Returns a value less than zero if this object
//
- public int CompareTo(Object obj) {
- if (obj==null) {
+ public int CompareTo(Object obj)
+ {
+ if (obj == null)
+ {
return 1;
}
- if (!(obj is Boolean)) {
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeBoolean"));
+ if (!(obj is Boolean))
+ {
+ throw new ArgumentException(SR.Arg_MustBeBoolean);
}
-
- if (m_value==((Boolean)obj).m_value) {
+
+ if (m_value == ((Boolean)obj).m_value)
+ {
return 0;
- } else if (m_value==false) {
+ }
+ else if (m_value == false)
+ {
return -1;
}
return 1;
}
- public int CompareTo(Boolean value) {
- if (m_value==value) {
+ public int CompareTo(Boolean value)
+ {
+ if (m_value == value)
+ {
return 0;
- } else if (m_value==false) {
+ }
+ else if (m_value == false)
+ {
return -1;
}
- return 1;
+ return 1;
}
-
+
//
// Static Methods
//
-
+
// Determines whether a String represents true or false.
//
- public static Boolean Parse (String value) {
- if (value==null) throw new ArgumentNullException(nameof(value));
+ 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(Environment.GetResourceString("Format_BadBoolean"));
+ if (!TryParse(value, out result))
+ {
+ throw new FormatException(SR.Format_BadBoolean);
}
- else {
+ else
+ {
return result;
}
}
// Determines whether a String represents true or false.
//
- public static Boolean TryParse (String value, out Boolean result) {
+ public static Boolean TryParse(String value, out Boolean result)
+ {
result = false;
- if (value==null) {
+ if (value == null)
+ {
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)) {
+ if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+ {
result = true;
return true;
}
- if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
+ if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+ {
result = false;
return true;
}
@@ -182,122 +207,130 @@ namespace System {
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
- if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase)) {
+ if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+ {
result = true;
return true;
}
-
- if (FalseLiteral.Equals(value,StringComparison.OrdinalIgnoreCase)) {
+
+ if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+ {
result = false;
return true;
}
-
+
return false;
}
- private static String TrimWhiteSpaceAndNull(String value) {
+ private static String TrimWhiteSpaceAndNull(String value)
+ {
int start = 0;
- int end = value.Length-1;
- char nullChar = (char) 0x0000;
+ int end = value.Length - 1;
+ char nullChar = (char)0x0000;
- while (start < value.Length) {
- if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar) {
+ while (start < value.Length)
+ {
+ if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar)
+ {
break;
}
start++;
}
- while (end >= start) {
- if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar) {
+ while (end >= start)
+ {
+ if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar)
+ {
break;
}
- end--;
+ end--;
}
return value.Substring(start, end - start + 1);
- }
+ }
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Boolean;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "Char"));
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char"));
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Boolean", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs
index 662b240b34..92b938df8c 100644
--- a/src/mscorlib/src/System/Buffer.cs
+++ b/src/mscorlib/src/System/Buffer.cs
@@ -2,10 +2,14 @@
// 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 {
-
+#if AMD64 || (BIT32 && !ARM)
+#define HAS_CUSTOM_BLOCKS
+#endif
+
+namespace System
+{
//Only contains static methods. Does not require serialization
-
+
using System;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
@@ -57,7 +61,7 @@ namespace System {
if (count == 0)
return -1;
else if (*pByte == value)
- return (int) (pByte - src);
+ return (int)(pByte - src);
count--;
pByte++;
@@ -87,7 +91,7 @@ namespace System {
if (t1 != 0)
{
// We've found a match for value, figure out which position it's in.
- int foundIndex = (int) (pByte - src);
+ int foundIndex = (int)(pByte - src);
if (pByte[0] == value)
return foundIndex;
else if (pByte[1] == value)
@@ -100,14 +104,13 @@ namespace System {
count -= 4;
pByte += 4;
-
}
// Catch any bytes that might be left at the tail of the buffer
while (count > 0)
{
if (*pByte == value)
- return (int) (pByte - src);
+ return (int)(pByte - src);
count--;
pByte++;
@@ -116,7 +119,7 @@ namespace System {
// If we don't have a match return -1;
return -1;
}
-
+
// Returns a bool to indicate if the array is of primitive data types
// or not.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -139,7 +142,7 @@ namespace System {
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array));
+ throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array));
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
@@ -165,7 +168,7 @@ namespace System {
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array));
+ throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array));
// Is the index in valid range of the array?
if (index < 0 || index >= _ByteLength(array))
@@ -175,7 +178,7 @@ namespace System {
_SetByte(array, index, value);
}
-
+
// Gets a particular byte out of the array. The array must be an
// array of primitives.
//
@@ -193,38 +196,41 @@ namespace System {
// Is it of primitive types?
if (!IsPrimitiveTypeArray(array))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePrimArray"), nameof(array));
+ throw new ArgumentException(SR.Arg_MustBePrimArray, nameof(array));
return _ByteLength(array);
}
internal unsafe static void ZeroMemory(byte* src, long len)
{
- while(len-- > 0)
+ while (len-- > 0)
*(src + len) = 0;
}
- internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len) {
- Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+ internal unsafe static void Memcpy(byte[] dest, int destIndex, byte* src, int srcIndex, int len)
+ {
+ Debug.Assert((srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
Debug.Assert(dest.Length - destIndex >= len, "not enough bytes in dest");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
- if (len==0)
+ if (len == 0)
return;
- fixed(byte* pDest = dest) {
+ fixed (byte* pDest = dest)
+ {
Memcpy(pDest + destIndex, src + srcIndex, len);
}
}
internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len)
{
- Debug.Assert( (srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
+ Debug.Assert((srcIndex >= 0) && (destIndex >= 0) && (len >= 0), "Index and length must be non-negative!");
Debug.Assert(src.Length - srcIndex >= len, "not enough bytes in src");
// If dest has 0 elements, the fixed statement will throw an
// IndexOutOfRangeException. Special-case 0-byte copies.
- if (len==0)
+ if (len == 0)
return;
- fixed(byte* pSrc = src) {
+ fixed (byte* pSrc = src)
+ {
Memcpy(pDest + destIndex, pSrc + srcIndex, len);
}
}
@@ -244,7 +250,8 @@ namespace System {
internal unsafe static extern void Memcpy(byte* dest, byte* src, int len);
#else // ARM
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
- internal unsafe static void Memcpy(byte* dest, byte* src, int len) {
+ internal unsafe static void Memcpy(byte* dest, byte* src, int len)
+ {
Debug.Assert(len >= 0, "Negative length in memcopy!");
Memmove(dest, src, (uint)len);
}
@@ -253,327 +260,175 @@ namespace System {
// This method has different signature for x64 and other platforms and is done for performance reasons.
internal unsafe static void Memmove(byte* dest, byte* src, nuint len)
{
- // P/Invoke into the native version when the buffers are overlapping and the copy needs to be performed backwards
- // This check can produce false positives for lengths greater than Int32.MaxInt. It is fine because we want to use PInvoke path for the large lengths anyway.
+#if AMD64 || (BIT32 && !ARM)
+ const nuint CopyThreshold = 2048;
+#else
+ const nuint CopyThreshold = 512;
+#endif // AMD64 || (BIT32 && !ARM)
- if ((nuint)dest - (nuint)src < len) goto PInvoke;
+ // P/Invoke into the native version when the buffers are overlapping.
- // This is portable version of memcpy. It mirrors what the hand optimized assembly versions of memcpy typically do.
- //
- // Ideally, we would just use the cpblk IL instruction here. Unfortunately, cpblk IL instruction is not as efficient as
- // possible yet and so we have this implementation here for now.
+ if (((nuint)dest - (nuint)src < len) || ((nuint)src - (nuint)dest < len)) goto PInvoke;
- // Note: It's important that this switch handles lengths at least up to 22.
- // See notes below near the main loop for why.
+ byte* srcEnd = src + len;
+ byte* destEnd = dest + len;
- // The switch will be very fast since it can be implemented using a jump
- // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info.
+ if (len <= 16) goto MCPY02;
+ if (len > 64) goto MCPY05;
- switch (len)
- {
- case 0:
- return;
- case 1:
- *dest = *src;
- return;
- case 2:
- *(short*)dest = *(short*)src;
- return;
- case 3:
- *(short*)dest = *(short*)src;
- *(dest + 2) = *(src + 2);
- return;
- case 4:
- *(int*)dest = *(int*)src;
- return;
- case 5:
- *(int*)dest = *(int*)src;
- *(dest + 4) = *(src + 4);
- return;
- case 6:
- *(int*)dest = *(int*)src;
- *(short*)(dest + 4) = *(short*)(src + 4);
- return;
- case 7:
- *(int*)dest = *(int*)src;
- *(short*)(dest + 4) = *(short*)(src + 4);
- *(dest + 6) = *(src + 6);
- return;
- case 8:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- return;
- case 9:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(dest + 8) = *(src + 8);
- return;
- case 10:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(short*)(dest + 8) = *(short*)(src + 8);
- return;
- case 11:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(short*)(dest + 8) = *(short*)(src + 8);
- *(dest + 10) = *(src + 10);
- return;
- case 12:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(int*)(dest + 8) = *(int*)(src + 8);
- return;
- case 13:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(dest + 12) = *(src + 12);
- return;
- case 14:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(short*)(dest + 12) = *(short*)(src + 12);
- return;
- case 15:
-#if BIT64
- *(long*)dest = *(long*)src;
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
-#endif
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(short*)(dest + 12) = *(short*)(src + 12);
- *(dest + 14) = *(src + 14);
- return;
- case 16:
-#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
-#endif
- return;
- case 17:
-#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
-#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
-#endif
- *(dest + 16) = *(src + 16);
- return;
- case 18:
-#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ MCPY00:
+ // Copy bytes which are multiples of 16 and leave the remainder for MCPY01 to handle.
+ Debug.Assert(len > 16 && len <= 64);
+#if HAS_CUSTOM_BLOCKS
+ *(Block16*)dest = *(Block16*)src; // [0,16]
+#elif BIT64
+ *(long*)dest = *(long*)src;
+ *(long*)(dest + 8) = *(long*)(src + 8); // [0,16]
#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
+ *(int*)dest = *(int*)src;
+ *(int*)(dest + 4) = *(int*)(src + 4);
+ *(int*)(dest + 8) = *(int*)(src + 8);
+ *(int*)(dest + 12) = *(int*)(src + 12); // [0,16]
#endif
- *(short*)(dest + 16) = *(short*)(src + 16);
- return;
- case 19:
-#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ if (len <= 32) goto MCPY01;
+#if HAS_CUSTOM_BLOCKS
+ *(Block16*)(dest + 16) = *(Block16*)(src + 16); // [0,32]
+#elif BIT64
+ *(long*)(dest + 16) = *(long*)(src + 16);
+ *(long*)(dest + 24) = *(long*)(src + 24); // [0,32]
#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
+ *(int*)(dest + 16) = *(int*)(src + 16);
+ *(int*)(dest + 20) = *(int*)(src + 20);
+ *(int*)(dest + 24) = *(int*)(src + 24);
+ *(int*)(dest + 28) = *(int*)(src + 28); // [0,32]
#endif
- *(short*)(dest + 16) = *(short*)(src + 16);
- *(dest + 18) = *(src + 18);
- return;
- case 20:
-#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ if (len <= 48) goto MCPY01;
+#if HAS_CUSTOM_BLOCKS
+ *(Block16*)(dest + 32) = *(Block16*)(src + 32); // [0,48]
+#elif BIT64
+ *(long*)(dest + 32) = *(long*)(src + 32);
+ *(long*)(dest + 40) = *(long*)(src + 40); // [0,48]
#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
+ *(int*)(dest + 32) = *(int*)(src + 32);
+ *(int*)(dest + 36) = *(int*)(src + 36);
+ *(int*)(dest + 40) = *(int*)(src + 40);
+ *(int*)(dest + 44) = *(int*)(src + 44); // [0,48]
#endif
- *(int*)(dest + 16) = *(int*)(src + 16);
- return;
- case 21:
-#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+
+ MCPY01:
+ // Unconditionally copy the last 16 bytes using destEnd and srcEnd and return.
+ Debug.Assert(len > 16 && len <= 64);
+#if HAS_CUSTOM_BLOCKS
+ *(Block16*)(destEnd - 16) = *(Block16*)(srcEnd - 16);
+#elif BIT64
+ *(long*)(destEnd - 16) = *(long*)(srcEnd - 16);
+ *(long*)(destEnd - 8) = *(long*)(srcEnd - 8);
#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
+ *(int*)(destEnd - 16) = *(int*)(srcEnd - 16);
+ *(int*)(destEnd - 12) = *(int*)(srcEnd - 12);
+ *(int*)(destEnd - 8) = *(int*)(srcEnd - 8);
+ *(int*)(destEnd - 4) = *(int*)(srcEnd - 4);
#endif
- *(int*)(dest + 16) = *(int*)(src + 16);
- *(dest + 20) = *(src + 20);
- return;
- case 22:
+ return;
+
+ MCPY02:
+ // Copy the first 8 bytes and then unconditionally copy the last 8 bytes and return.
+ if ((len & 24) == 0) goto MCPY03;
+ Debug.Assert(len >= 8 && len <= 16);
#if BIT64
- *(long*)dest = *(long*)src;
- *(long*)(dest + 8) = *(long*)(src + 8);
+ *(long*)dest = *(long*)src;
+ *(long*)(destEnd - 8) = *(long*)(srcEnd - 8);
#else
- *(int*)dest = *(int*)src;
- *(int*)(dest + 4) = *(int*)(src + 4);
- *(int*)(dest + 8) = *(int*)(src + 8);
- *(int*)(dest + 12) = *(int*)(src + 12);
+ *(int*)dest = *(int*)src;
+ *(int*)(dest + 4) = *(int*)(src + 4);
+ *(int*)(destEnd - 8) = *(int*)(srcEnd - 8);
+ *(int*)(destEnd - 4) = *(int*)(srcEnd - 4);
#endif
- *(int*)(dest + 16) = *(int*)(src + 16);
- *(short*)(dest + 20) = *(short*)(src + 20);
- return;
- }
-
- // P/Invoke into the native version for large lengths
- if (len >= 512) goto PInvoke;
-
- nuint i = 0; // byte offset at which we're copying
+ return;
- if (((int)dest & 3) != 0)
- {
- if (((int)dest & 1) != 0)
- {
- *(dest + i) = *(src + i);
- i += 1;
- if (((int)dest & 2) != 0)
- goto IntAligned;
- }
- *(short*)(dest + i) = *(short*)(src + i);
- i += 2;
- }
+ MCPY03:
+ // Copy the first 4 bytes and then unconditionally copy the last 4 bytes and return.
+ if ((len & 4) == 0) goto MCPY04;
+ Debug.Assert(len >= 4 && len < 8);
+ *(int*)dest = *(int*)src;
+ *(int*)(destEnd - 4) = *(int*)(srcEnd - 4);
+ return;
- IntAligned:
+ MCPY04:
+ // Copy the first byte. For pending bytes, do an unconditionally copy of the last 2 bytes and return.
+ Debug.Assert(len < 4);
+ if (len == 0) return;
+ *dest = *src;
+ if ((len & 2) == 0) return;
+ *(short*)(destEnd - 2) = *(short*)(srcEnd - 2);
+ return;
-#if BIT64
- // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If
- // (int)dest % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1
- // bytes to the next aligned address (respectively), so do nothing. On the other hand,
- // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until
- // we're aligned.
- // The thing 1, 2, 3, and 4 have in common that the others don't is that if you
- // subtract one from them, their 3rd lsb will not be set. Hence, the below check.
-
- if ((((int)dest - 1) & 4) == 0)
+ MCPY05:
+ // PInvoke to the native version when the copy length exceeds the threshold.
+ if (len > CopyThreshold)
{
- *(int*)(dest + i) = *(int*)(src + i);
- i += 4;
+ goto PInvoke;
}
-#endif // BIT64
-
- nuint end = len - 16;
- len -= i; // lower 4 bits of len represent how many bytes are left *after* the unrolled loop
-
- // We know due to the above switch-case that this loop will always run 1 iteration; max
- // bytes we copy before checking is 23 (7 to align the pointers, 16 for 1 iteration) so
- // the switch handles lengths 0-22.
- Debug.Assert(end >= 7 && i <= end);
-
- // This is separated out into a different variable, so the i + 16 addition can be
- // performed at the start of the pipeline and the loop condition does not have
- // a dependency on the writes.
- nuint counter;
-
- do
- {
- counter = i + 16;
- // This loop looks very costly since there appear to be a bunch of temporary values
- // being created with the adds, but the jit (for x86 anyways) will convert each of
- // these to use memory addressing operands.
-
- // So the only cost is a bit of code size, which is made up for by the fact that
- // we save on writes to dest/src.
-
-#if BIT64
- *(long*)(dest + i) = *(long*)(src + i);
- *(long*)(dest + i + 8) = *(long*)(src + i + 8);
+ // 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);
+ nuint n = len >> 6;
+
+ MCPY06:
+#if HAS_CUSTOM_BLOCKS
+ *(Block64*)dest = *(Block64*)src;
+#elif BIT64
+ *(long*)dest = *(long*)src;
+ *(long*)(dest + 8) = *(long*)(src + 8);
+ *(long*)(dest + 16) = *(long*)(src + 16);
+ *(long*)(dest + 24) = *(long*)(src + 24);
+ *(long*)(dest + 32) = *(long*)(src + 32);
+ *(long*)(dest + 40) = *(long*)(src + 40);
+ *(long*)(dest + 48) = *(long*)(src + 48);
+ *(long*)(dest + 56) = *(long*)(src + 56);
#else
- *(int*)(dest + i) = *(int*)(src + i);
- *(int*)(dest + i + 4) = *(int*)(src + i + 4);
- *(int*)(dest + i + 8) = *(int*)(src + i + 8);
- *(int*)(dest + i + 12) = *(int*)(src + i + 12);
+ *(int*)dest = *(int*)src;
+ *(int*)(dest + 4) = *(int*)(src + 4);
+ *(int*)(dest + 8) = *(int*)(src + 8);
+ *(int*)(dest + 12) = *(int*)(src + 12);
+ *(int*)(dest + 16) = *(int*)(src + 16);
+ *(int*)(dest + 20) = *(int*)(src + 20);
+ *(int*)(dest + 24) = *(int*)(src + 24);
+ *(int*)(dest + 28) = *(int*)(src + 28);
+ *(int*)(dest + 32) = *(int*)(src + 32);
+ *(int*)(dest + 36) = *(int*)(src + 36);
+ *(int*)(dest + 40) = *(int*)(src + 40);
+ *(int*)(dest + 44) = *(int*)(src + 44);
+ *(int*)(dest + 48) = *(int*)(src + 48);
+ *(int*)(dest + 52) = *(int*)(src + 52);
+ *(int*)(dest + 56) = *(int*)(src + 56);
+ *(int*)(dest + 60) = *(int*)(src + 60);
#endif
-
- i = counter;
-
- // See notes above for why this wasn't used instead
- // i += 16;
- }
- while (counter <= end);
-
- if ((len & 8) != 0)
- {
-#if BIT64
- *(long*)(dest + i) = *(long*)(src + i);
+ dest += 64;
+ src += 64;
+ n--;
+ if (n != 0) goto MCPY06;
+
+ len %= 64;
+ if (len > 16) goto MCPY00;
+#if HAS_CUSTOM_BLOCKS
+ *(Block16*)(destEnd - 16) = *(Block16*)(srcEnd - 16);
+#elif BIT64
+ *(long*)(destEnd - 16) = *(long*)(srcEnd - 16);
+ *(long*)(destEnd - 8) = *(long*)(srcEnd - 8);
#else
- *(int*)(dest + i) = *(int*)(src + i);
- *(int*)(dest + i + 4) = *(int*)(src + i + 4);
+ *(int*)(destEnd - 16) = *(int*)(srcEnd - 16);
+ *(int*)(destEnd - 12) = *(int*)(srcEnd - 12);
+ *(int*)(destEnd - 8) = *(int*)(srcEnd - 8);
+ *(int*)(destEnd - 4) = *(int*)(srcEnd - 4);
#endif
- i += 8;
- }
- if ((len & 4) != 0)
- {
- *(int*)(dest + i) = *(int*)(src + i);
- i += 4;
- }
- if ((len & 2) != 0)
- {
- *(short*)(dest + i) = *(short*)(src + i);
- i += 2;
- }
- if ((len & 1) != 0)
- {
- *(dest + i) = *(src + i);
- // We're not using i after this, so not needed
- // i += 1;
- }
-
return;
PInvoke:
_Memmove(dest, src, len);
-
}
-
+
// Non-inlinable wrapper around the QCall that avoids poluting the fast path
// with P/Invoke prolog/epilog.
[MethodImplAttribute(MethodImplOptions.NoInlining)]
@@ -616,5 +471,13 @@ namespace System {
Memmove((byte*)destination, (byte*)source, checked((uint)sourceBytesToCopy));
#endif // BIT64
}
+
+#if HAS_CUSTOM_BLOCKS
+ [StructLayout(LayoutKind.Sequential, Size = 16)]
+ private struct Block16 { }
+
+ [StructLayout(LayoutKind.Sequential, Size = 64)]
+ private struct Block64 { }
+#endif // HAS_CUSTOM_BLOCKS
}
}
diff --git a/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs b/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs
new file mode 100644
index 0000000000..9482744144
--- /dev/null
+++ b/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.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.Diagnostics.Tracing;
+
+namespace System.Buffers
+{
+ [EventSource(Name = "System.Buffers.ArrayPoolEventSource")]
+ internal sealed class ArrayPoolEventSource : EventSource
+ {
+ internal readonly static ArrayPoolEventSource Log = new ArrayPoolEventSource();
+
+ /// <summary>The reason for a BufferAllocated event.</summary>
+ internal enum BufferAllocatedReason : int
+ {
+ /// <summary>The pool is allocating a buffer to be pooled in a bucket.</summary>
+ Pooled,
+ /// <summary>The requested buffer size was too large to be pooled.</summary>
+ OverMaximumSize,
+ /// <summary>The pool has already allocated for pooling as many buffers of a particular size as it's allowed.</summary>
+ PoolExhausted
+ }
+
+ /// <summary>
+ /// Event for when a buffer is rented. This is invoked once for every successful call to Rent,
+ /// regardless of whether a buffer is allocated or a buffer is taken from the pool. In a
+ /// perfect situation where all rented buffers are returned, we expect to see the number
+ /// of BufferRented events exactly match the number of BuferReturned events, with the number
+ /// of BufferAllocated events being less than or equal to those numbers (ideally significantly
+ /// less than).
+ /// </summary>
+ [Event(1, Level = EventLevel.Verbose)]
+ internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId)
+ {
+ EventData* payload = stackalloc EventData[4];
+ payload[0].Size = sizeof(int);
+ payload[0].DataPointer = ((IntPtr)(&bufferId));
+ payload[1].Size = sizeof(int);
+ payload[1].DataPointer = ((IntPtr)(&bufferSize));
+ payload[2].Size = sizeof(int);
+ payload[2].DataPointer = ((IntPtr)(&poolId));
+ payload[3].Size = sizeof(int);
+ payload[3].DataPointer = ((IntPtr)(&bucketId));
+ WriteEventCore(1, 4, payload);
+ }
+
+ /// <summary>
+ /// Event for when a buffer is allocated by the pool. In an ideal situation, the number
+ /// of BufferAllocated events is significantly smaller than the number of BufferRented and
+ /// BufferReturned events.
+ /// </summary>
+ [Event(2, Level = EventLevel.Informational)]
+ internal unsafe void BufferAllocated(int bufferId, int bufferSize, int poolId, int bucketId, BufferAllocatedReason reason)
+ {
+ EventData* payload = stackalloc EventData[5];
+ payload[0].Size = sizeof(int);
+ payload[0].DataPointer = ((IntPtr)(&bufferId));
+ payload[1].Size = sizeof(int);
+ payload[1].DataPointer = ((IntPtr)(&bufferSize));
+ payload[2].Size = sizeof(int);
+ payload[2].DataPointer = ((IntPtr)(&poolId));
+ payload[3].Size = sizeof(int);
+ payload[3].DataPointer = ((IntPtr)(&bucketId));
+ payload[4].Size = sizeof(BufferAllocatedReason);
+ payload[4].DataPointer = ((IntPtr)(&reason));
+ WriteEventCore(2, 5, payload);
+ }
+
+ /// <summary>
+ /// Event raised when a buffer is returned to the pool. This event is raised regardless of whether
+ /// the returned buffer is stored or dropped. In an ideal situation, the number of BufferReturned
+ /// events exactly matches the number of BufferRented events.
+ /// </summary>
+ [Event(3, Level = EventLevel.Verbose)]
+ internal void BufferReturned(int bufferId, int bufferSize, int poolId) => WriteEvent(3, bufferId, bufferSize, poolId);
+ }
+}
diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/src/System/Byte.cs
index 666fdda75b..27fdcd7a64 100644
--- a/src/mscorlib/src/System/Byte.cs
+++ b/src/mscorlib/src/System/Byte.cs
@@ -12,54 +12,61 @@
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+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)]
+ [Serializable]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Byte : IComparable, IFormattable, IConvertible
- , IComparable<Byte>, IEquatable<Byte>
+ , IComparable<Byte>, IEquatable<Byte>
{
private byte m_value;
-
+
// The maximum value that a Byte may represent: 255.
public const byte MaxValue = (byte)0xFF;
-
+
// The minimum value that a Byte may represent: 0.
public const byte MinValue = 0;
-
-
+
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type byte, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (!(value is Byte)) {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeByte"));
+ if (!(value is Byte))
+ {
+ throw new ArgumentException(SR.Arg_MustBeByte);
}
-
+
return m_value - (((Byte)value).m_value);
}
- public int CompareTo(Byte value) {
+ public int CompareTo(Byte value)
+ {
return m_value - value;
}
-
+
// Determines whether two Byte objects are equal.
- public override bool Equals(Object obj) {
- if (!(obj is Byte)) {
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Byte))
+ {
return false;
}
return m_value == ((Byte)obj).m_value;
@@ -72,176 +79,194 @@ namespace System {
}
// Gets a hash code for this instance.
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return m_value;
}
-
+
[Pure]
- public static byte Parse(String s) {
+ public static byte Parse(String s)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
+
[Pure]
- public static byte Parse(String s, NumberStyles style) {
+ public static byte Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
[Pure]
- public static byte Parse(String s, IFormatProvider provider) {
+ public static byte Parse(String s, IFormatProvider provider)
+ {
return Parse(s, 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.
[Pure]
- public static byte Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static byte Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
-
- private static byte Parse(String s, NumberStyles style, NumberFormatInfo info) {
+
+ private static byte Parse(String s, NumberStyles style, NumberFormatInfo info)
+ {
int i = 0;
- try {
+ try
+ {
i = Number.ParseInt32(s, style, info);
}
- catch(OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Byte"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_Byte, e);
}
- if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte"));
+ if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte);
return (byte)i;
}
- public static bool TryParse(String s, out Byte result) {
+ public static bool TryParse(String s, out Byte result)
+ {
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result) {
+ public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result)
+ {
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(String s, NumberStyles style, NumberFormatInfo info, out Byte result)
+ {
result = 0;
int i;
- if (!Number.TryParseInt32(s, style, info, out i)) {
+ if (!Number.TryParseInt32(s, style, info, out i))
+ {
return false;
}
- if (i < MinValue || i > MaxValue) {
+ if (i < MinValue || i > MaxValue)
+ {
return false;
}
- result = (byte) i;
+ result = (byte)i;
return true;
}
[Pure]
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
[Pure]
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
-
+
//
// IConvertible implementation
//
[Pure]
- public TypeCode GetTypeCode() {
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Byte;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Byte", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/CLRConfig.cs b/src/mscorlib/src/System/CLRConfig.cs
index 16c610b82b..d97922f9b9 100644
--- a/src/mscorlib/src/System/CLRConfig.cs
+++ b/src/mscorlib/src/System/CLRConfig.cs
@@ -7,8 +7,23 @@ using System.Runtime.Versioning;
using System.Runtime.InteropServices;
using System.Security;
-namespace System {
+namespace System
+{
+ // CLRConfig is mainly reading the config switch values. this is used when we cannot use the AppContext class
+ // one example, is using the context switch in the globalization code which require to read the switch very
+ // early even before the appdomain get initialized.
+ // In general AppContext should be used instead of CLRConfig if there is no reason prevent that.
+ internal class CLRConfig
+ {
+ internal static bool GetBoolValue(string switchName)
+ {
+ return GetConfigBoolValue(switchName);
+ }
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private extern static bool GetConfigBoolValue(string configSwitchName);
+ }
} // namespace System
// file CLRConfig
diff --git a/src/mscorlib/src/System/CLSCompliantAttribute.cs b/src/mscorlib/src/System/CLSCompliantAttribute.cs
deleted file mode 100644
index e03600d132..0000000000
--- a/src/mscorlib/src/System/CLSCompliantAttribute.cs
+++ /dev/null
@@ -1,34 +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: Container for assemblies.
-**
-**
-=============================================================================*/
-
-namespace System
-{
- [Serializable]
- [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
- public sealed class CLSCompliantAttribute : Attribute
- {
- private bool _compliant;
-
- public CLSCompliantAttribute(bool isCompliant)
- {
- _compliant = isCompliant;
- }
- public bool IsCompliant
- {
- get
- {
- return _compliant;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Char.cs b/src/mscorlib/src/System/Char.cs
deleted file mode 100644
index 7fe1c08715..0000000000
--- a/src/mscorlib/src/System/Char.cs
+++ /dev/null
@@ -1,1000 +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 is the value class representing a Unicode character
-** Char methods until we create this functionality.
-**
-**
-===========================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct Char : IComparable, IConvertible
- , IComparable<Char>, IEquatable<Char>
- {
- //
- // Member Variables
- //
- internal char m_value;
-
- //
- // Public Constants
- //
- // The maximum character value.
- public const char MaxValue = (char) 0xFFFF;
- // The minimum character value.
- public const char MinValue = (char) 0x00;
-
- // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space.
- private readonly static byte[] categoryForLatin1 = {
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F
- (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027
- (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F
- (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
- (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F
- (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
- (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097
- (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F
- (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7
- (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
- (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
- (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7
- (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7
- (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
- };
-
- // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement.
- private static bool IsLatin1(char ch) {
- return (ch <= '\x00ff');
- }
-
- // Return true for all characters below or equal U+007f, which is ASCII.
- private static bool IsAscii(char ch) {
- return (ch <= '\x007f');
- }
-
- // Return the Unicode category for Unicode character <= 0x00ff.
- private static UnicodeCategory GetLatin1UnicodeCategory(char ch) {
- Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
- return (UnicodeCategory)(categoryForLatin1[(int)ch]);
- }
-
- //
- // Private Constants
- //
-
- //
- // Overriden Instance Methods
- //
-
- // Calculate a hashcode for a 2 byte Unicode character.
- public override int GetHashCode() {
- return (int)m_value | ((int)m_value << 16);
- }
-
- // Used for comparing two boxed Char objects.
- //
- public override bool Equals(Object obj) {
- if (!(obj is Char)) {
- return false;
- }
- return (m_value==((Char)obj).m_value);
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public bool Equals(Char obj)
- {
- return m_value == obj;
- }
-
- // Compares this object to another object, returning an integer that
- // indicates the relationship.
- // Returns a value less than zero if this object
- // null is considered to be less than any instance.
- // If object is not of type Char, this method throws an ArgumentException.
- //
- [Pure]
- public int CompareTo(Object value) {
- if (value==null) {
- return 1;
- }
- if (!(value is Char)) {
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeChar"));
- }
-
- return (m_value-((Char)value).m_value);
- }
-
- [Pure]
- public int CompareTo(Char value) {
- return (m_value-value);
- }
-
- // Overrides System.Object.ToString.
- [Pure]
- public override String ToString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return Char.ToString(m_value);
- }
-
- [Pure]
- public String ToString(IFormatProvider provider) {
- Contract.Ensures(Contract.Result<String>() != null);
- return Char.ToString(m_value);
- }
-
- //
- // Formatting Methods
- //
-
- /*===================================ToString===================================
- **This static methods takes a character and returns the String representation of it.
- ==============================================================================*/
- // Provides a string representation of a character.
- [Pure]
- public static string ToString(char c) => string.CreateFromChar(c);
-
- public static char Parse(String s) {
- if (s==null) {
- throw new ArgumentNullException(nameof(s));
- }
- Contract.EndContractBlock();
-
- if (s.Length!=1) {
- throw new FormatException(Environment.GetResourceString("Format_NeedSingleChar"));
- }
- return s[0];
- }
-
- public static bool TryParse(String s, out Char result) {
- result = '\0';
- if (s == null) {
- return false;
- }
- if (s.Length != 1) {
- return false;
- }
- result = s[0];
- return true;
- }
-
- //
- // Static Methods
- //
- /*=================================ISDIGIT======================================
- **A wrapper for Char. Returns a boolean indicating whether **
- **character c is considered to be a digit. **
- ==============================================================================*/
- // Determines whether a character is a digit.
- [Pure]
- public static bool IsDigit(char c) {
- if (IsLatin1(c)) {
- return (c >= '0' && c <= '9');
- }
- return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber);
- }
-
-
- /*=================================CheckLetter=====================================
- ** Check if the specified UnicodeCategory belongs to the letter categories.
- ==============================================================================*/
- internal static bool CheckLetter(UnicodeCategory uc) {
- switch(uc) {
- case (UnicodeCategory.UppercaseLetter):
- case (UnicodeCategory.LowercaseLetter):
- case (UnicodeCategory.TitlecaseLetter):
- case (UnicodeCategory.ModifierLetter):
- case (UnicodeCategory.OtherLetter):
- return (true);
- }
- return (false);
- }
-
- /*=================================ISLETTER=====================================
- **A wrapper for Char. Returns a boolean indicating whether **
- **character c is considered to be a letter. **
- ==============================================================================*/
- // Determines whether a character is a letter.
- [Pure]
- public static bool IsLetter(char c) {
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- c |=(char)0x20;
- return ((c >= 'a' && c <= 'z'));
- }
- return (CheckLetter(GetLatin1UnicodeCategory(c)));
- }
- return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c)));
- }
-
- private static bool IsWhiteSpaceLatin1(char c) {
-
- // There are characters which belong to UnicodeCategory.Control but are considered as white spaces.
- // We use code point comparisons for these characters here as a temporary fix.
-
- // U+0009 = <control> HORIZONTAL TAB
- // U+000a = <control> LINE FEED
- // U+000b = <control> VERTICAL TAB
- // U+000c = <contorl> FORM FEED
- // U+000d = <control> CARRIAGE RETURN
- // U+0085 = <control> NEXT LINE
- // U+00a0 = NO-BREAK SPACE
- if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085') {
- return (true);
- }
- return (false);
- }
-
- /*===============================ISWHITESPACE===================================
- **A wrapper for Char. Returns a boolean indicating whether **
- **character c is considered to be a whitespace character. **
- ==============================================================================*/
- // Determines whether a character is whitespace.
- [Pure]
- public static bool IsWhiteSpace(char c) {
-
- if (IsLatin1(c)) {
- return (IsWhiteSpaceLatin1(c));
- }
- return CharUnicodeInfo.IsWhiteSpace(c);
- }
-
-
- /*===================================IsUpper====================================
- **Arguments: c -- the characater to be checked.
- **Returns: True if c is an uppercase character.
- ==============================================================================*/
- // Determines whether a character is upper-case.
- [Pure]
- public static bool IsUpper(char c) {
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- return (c >= 'A' && c <= 'Z');
- }
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter);
- }
- return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
- }
-
- /*===================================IsLower====================================
- **Arguments: c -- the characater to be checked.
- **Returns: True if c is an lowercase character.
- ==============================================================================*/
- // Determines whether a character is lower-case.
- [Pure]
- public static bool IsLower(char c) {
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- return (c >= 'a' && c <= 'z');
- }
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter);
- }
- return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
- }
-
- internal static bool CheckPunctuation(UnicodeCategory uc)
- {
- switch (uc) {
- case UnicodeCategory.ConnectorPunctuation:
- case UnicodeCategory.DashPunctuation:
- case UnicodeCategory.OpenPunctuation:
- case UnicodeCategory.ClosePunctuation:
- case UnicodeCategory.InitialQuotePunctuation:
- case UnicodeCategory.FinalQuotePunctuation:
- case UnicodeCategory.OtherPunctuation:
- return (true);
- }
- return (false);
- }
-
-
- /*================================IsPunctuation=================================
- **Arguments: c -- the characater to be checked.
- **Returns: True if c is an punctuation mark
- ==============================================================================*/
- // Determines whether a character is a punctuation mark.
- [Pure]
- public static bool IsPunctuation(char c){
- if (IsLatin1(c)) {
- return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
- }
- return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c)));
- }
-
- /*=================================CheckLetterOrDigit=====================================
- ** Check if the specified UnicodeCategory belongs to the letter or digit categories.
- ==============================================================================*/
- internal static bool CheckLetterOrDigit(UnicodeCategory uc) {
- switch (uc) {
- case UnicodeCategory.UppercaseLetter:
- case UnicodeCategory.LowercaseLetter:
- case UnicodeCategory.TitlecaseLetter:
- case UnicodeCategory.ModifierLetter:
- case UnicodeCategory.OtherLetter:
- case UnicodeCategory.DecimalDigitNumber:
- return (true);
- }
- return (false);
- }
-
- // Determines whether a character is a letter or a digit.
- [Pure]
- public static bool IsLetterOrDigit(char c) {
- if (IsLatin1(c)) {
- return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c)));
- }
- return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c)));
- }
-
- /*===================================ToUpper====================================
- **
- ==============================================================================*/
- // Converts a character to upper-case for the specified culture.
- // <;<;Not fully implemented>;>;
- public static char ToUpper(char c, CultureInfo culture) {
- if (culture==null)
- throw new ArgumentNullException(nameof(culture));
- Contract.EndContractBlock();
- return culture.TextInfo.ToUpper(c);
- }
-
- /*=================================TOUPPER======================================
- **A wrapper for Char.toUpperCase. Converts character c to its **
- **uppercase equivalent. If c is already an uppercase character or is not an **
- **alphabetic, nothing happens. **
- ==============================================================================*/
- // Converts a character to upper-case for the default culture.
- //
- public static char ToUpper(char c) {
- return ToUpper(c, CultureInfo.CurrentCulture);
- }
-
-
- // Converts a character to upper-case for invariant culture.
- public static char ToUpperInvariant(char c) {
- return ToUpper(c, CultureInfo.InvariantCulture);
- }
-
- /*===================================ToLower====================================
- **
- ==============================================================================*/
- // Converts a character to lower-case for the specified culture.
- // <;<;Not fully implemented>;>;
- public static char ToLower(char c, CultureInfo culture) {
- if (culture==null)
- throw new ArgumentNullException(nameof(culture));
- Contract.EndContractBlock();
- return culture.TextInfo.ToLower(c);
- }
-
- /*=================================TOLOWER======================================
- **A wrapper for Char.toLowerCase. Converts character c to its **
- **lowercase equivalent. If c is already a lowercase character or is not an **
- **alphabetic, nothing happens. **
- ==============================================================================*/
- // Converts a character to lower-case for the default culture.
- public static char ToLower(char c) {
- return ToLower(c, CultureInfo.CurrentCulture);
- }
-
-
- // Converts a character to lower-case for invariant culture.
- public static char ToLowerInvariant(char c) {
- return ToLower(c, CultureInfo.InvariantCulture);
- }
-
- //
- // IConvertible implementation
- //
- [Pure]
- public TypeCode GetTypeCode() {
- return TypeCode.Char;
- }
-
-
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Boolean"));
- }
-
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- return m_value;
- }
-
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
- return Convert.ToSByte(m_value);
- }
-
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
- return Convert.ToByte(m_value);
- }
-
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
- return Convert.ToInt16(m_value);
- }
-
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
- return Convert.ToUInt16(m_value);
- }
-
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
- return Convert.ToInt32(m_value);
- }
-
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
- return Convert.ToUInt32(m_value);
- }
-
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
- return Convert.ToInt64(m_value);
- }
-
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
- return Convert.ToUInt64(m_value);
- }
-
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Single"));
- }
-
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Double"));
- }
-
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "Decimal"));
- }
-
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Char", "DateTime"));
- }
-
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
- return Convert.DefaultToType((IConvertible)this, type, provider);
- }
-
- public static bool IsControl(char c)
- {
- if (IsLatin1(c)) {
- return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
- }
- return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control);
- }
-
- public static bool IsControl(String s, int index) {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
- }
- return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control);
- }
-
-
- public static bool IsDigit(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- return (c >= '0' && c <= '9');
- }
- return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
- }
-
- public static bool IsLetter(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- c |=(char)0x20;
- return ((c >= 'a' && c <= 'z'));
- }
- return (CheckLetter(GetLatin1UnicodeCategory(c)));
- }
- return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index)));
- }
-
- public static bool IsLetterOrDigit(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
- }
- return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index));
- }
-
- public static bool IsLower(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- return (c >= 'a' && c <= 'z');
- }
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.LowercaseLetter);
- }
-
- return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter);
- }
-
- /*=================================CheckNumber=====================================
- ** Check if the specified UnicodeCategory belongs to the number categories.
- ==============================================================================*/
-
- internal static bool CheckNumber(UnicodeCategory uc) {
- switch (uc) {
- case (UnicodeCategory.DecimalDigitNumber):
- case (UnicodeCategory.LetterNumber):
- case (UnicodeCategory.OtherNumber):
- return (true);
- }
- return (false);
- }
-
- public static bool IsNumber(char c)
- {
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- return (c >= '0' && c <= '9');
- }
- return (CheckNumber(GetLatin1UnicodeCategory(c)));
- }
- return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c)));
- }
-
- public static bool IsNumber(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- return (c >= '0' && c <= '9');
- }
- return (CheckNumber(GetLatin1UnicodeCategory(c)));
- }
- return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index)));
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // IsPunctuation
- //
- // Determines if the given character is a punctuation character.
- //
- ////////////////////////////////////////////////////////////////////////
-
- public static bool IsPunctuation (String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
- }
- return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index)));
- }
-
-
- /*================================= CheckSeparator ============================
- ** Check if the specified UnicodeCategory belongs to the seprator categories.
- ==============================================================================*/
-
- internal static bool CheckSeparator(UnicodeCategory uc)
- {
- switch (uc) {
- case UnicodeCategory.SpaceSeparator:
- case UnicodeCategory.LineSeparator:
- case UnicodeCategory.ParagraphSeparator:
- return (true);
- }
- return (false);
- }
-
- private static bool IsSeparatorLatin1(char c) {
- // U+00a0 = NO-BREAK SPACE
- // There is no LineSeparator or ParagraphSeparator in Latin 1 range.
- return (c == '\x0020' || c == '\x00a0');
- }
-
- public static bool IsSeparator(char c)
- {
- if (IsLatin1(c)) {
- return (IsSeparatorLatin1(c));
- }
- return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c)));
- }
-
- public static bool IsSeparator(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- return (IsSeparatorLatin1(c));
- }
- return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index)));
- }
-
- [Pure]
- public static bool IsSurrogate(char c)
- {
- return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END);
- }
-
- [Pure]
- public static bool IsSurrogate(String s, int index)
- {
- if (s==null) {
- throw new ArgumentNullException(nameof(s));
- }
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- return (IsSurrogate(s[index]));
- }
-
- /*================================= CheckSymbol ============================
- ** Check if the specified UnicodeCategory belongs to the symbol categories.
- ==============================================================================*/
-
- internal static bool CheckSymbol(UnicodeCategory uc) {
- switch (uc) {
- case (UnicodeCategory.MathSymbol):
- case (UnicodeCategory.CurrencySymbol):
- case (UnicodeCategory.ModifierSymbol):
- case (UnicodeCategory.OtherSymbol):
- return (true);
- }
- return (false);
- }
-
- public static bool IsSymbol(char c)
- {
- if (IsLatin1(c)) {
- return (CheckSymbol(GetLatin1UnicodeCategory(c)));
- }
- return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c)));
- }
-
- public static bool IsSymbol(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- if (IsLatin1(s[index])) {
- return (CheckSymbol(GetLatin1UnicodeCategory(s[index])));
- }
- return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index)));
- }
-
-
- public static bool IsUpper(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- char c = s[index];
- if (IsLatin1(c)) {
- if (IsAscii(c)) {
- return (c >= 'A' && c <= 'Z');
- }
- return (GetLatin1UnicodeCategory(c)== UnicodeCategory.UppercaseLetter);
- }
-
- return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter);
- }
-
- public static bool IsWhiteSpace(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
-
- if (IsLatin1(s[index])) {
- return IsWhiteSpaceLatin1(s[index]);
- }
-
- return CharUnicodeInfo.IsWhiteSpace(s, index);
- }
-
- public static UnicodeCategory GetUnicodeCategory(char c)
- {
- if (IsLatin1(c)) {
- return (GetLatin1UnicodeCategory(c));
- }
- return CharUnicodeInfo.InternalGetUnicodeCategory(c);
- }
-
- public static UnicodeCategory GetUnicodeCategory(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- if (IsLatin1(s[index])) {
- return (GetLatin1UnicodeCategory(s[index]));
- }
- return CharUnicodeInfo.InternalGetUnicodeCategory(s, index);
- }
-
- public static double GetNumericValue(char c)
- {
- return CharUnicodeInfo.GetNumericValue(c);
- }
-
- public static double GetNumericValue(String s, int index)
- {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- return CharUnicodeInfo.GetNumericValue(s, index);
- }
-
-
- /*================================= IsHighSurrogate ============================
- ** Check if a char is a high surrogate.
- ==============================================================================*/
- [Pure]
- public static bool IsHighSurrogate(char c) {
- return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END));
- }
-
- [Pure]
- public static bool IsHighSurrogate(String s, int index) {
- if (s == null) {
- throw new ArgumentNullException(nameof(s));
- }
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- return (IsHighSurrogate(s[index]));
- }
-
- /*================================= IsLowSurrogate ============================
- ** Check if a char is a low surrogate.
- ==============================================================================*/
- [Pure]
- public static bool IsLowSurrogate(char c) {
- return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END));
- }
-
- [Pure]
- public static bool IsLowSurrogate(String s, int index) {
- if (s == null) {
- throw new ArgumentNullException(nameof(s));
- }
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- return (IsLowSurrogate(s[index]));
- }
-
- /*================================= IsSurrogatePair ============================
- ** Check if the string specified by the index starts with a surrogate pair.
- ==============================================================================*/
- [Pure]
- public static bool IsSurrogatePair(String s, int index) {
- if (s == null) {
- throw new ArgumentNullException(nameof(s));
- }
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index));
- }
- Contract.EndContractBlock();
- if (index + 1 < s.Length) {
- return (IsSurrogatePair(s[index], s[index+1]));
- }
- return (false);
- }
-
- [Pure]
- public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) {
- return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) &&
- (lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END));
- }
-
- internal const int UNICODE_PLANE00_END = 0x00ffff;
- // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
- internal const int UNICODE_PLANE01_START = 0x10000;
- // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode.
- // Plane 16 contains 0x100000 ~ 0x10ffff.
- internal const int UNICODE_PLANE16_END = 0x10ffff;
-
- internal const int HIGH_SURROGATE_START = 0x00d800;
- internal const int LOW_SURROGATE_END = 0x00dfff;
-
-
-
- /*================================= ConvertFromUtf32 ============================
- ** Convert an UTF32 value into a surrogate pair.
- ==============================================================================*/
-
- public static String ConvertFromUtf32(int utf32)
- {
- // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They
- // are considered as irregular code unit sequence, but they are not illegal.
- if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END)) {
- throw new ArgumentOutOfRangeException(nameof(utf32), Environment.GetResourceString("ArgumentOutOfRange_InvalidUTF32"));
- }
- Contract.EndContractBlock();
-
- if (utf32 < UNICODE_PLANE01_START) {
- // This is a BMP character.
- return (Char.ToString((char)utf32));
- }
-
- unsafe
- {
- // This is a supplementary character. Convert it to a surrogate pair in UTF-16.
- utf32 -= UNICODE_PLANE01_START;
- uint surrogate = 0; // allocate 2 chars worth of stack space
- char* address = (char*)&surrogate;
- address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START);
- address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START);
- return new string(address, 0, 2);
- }
- }
-
-
- /*=============================ConvertToUtf32===================================
- ** Convert a surrogate pair to UTF32 value
- ==============================================================================*/
-
- public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) {
- if (!IsHighSurrogate(highSurrogate)) {
- throw new ArgumentOutOfRangeException(nameof(highSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"));
- }
- if (!IsLowSurrogate(lowSurrogate)) {
- throw new ArgumentOutOfRangeException(nameof(lowSurrogate), Environment.GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"));
- }
- Contract.EndContractBlock();
- return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START);
- }
-
- /*=============================ConvertToUtf32===================================
- ** Convert a character or a surrogate pair starting at index of the specified string
- ** to UTF32 value.
- ** The char pointed by index should be a surrogate pair or a BMP character.
- ** This method throws if a high-surrogate is not followed by a low surrogate.
- ** This method throws if a low surrogate is seen without preceding a high-surrogate.
- ==============================================================================*/
-
- public static int ConvertToUtf32(String s, int index) {
- if (s == null) {
- throw new ArgumentNullException(nameof(s));
- }
-
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.EndContractBlock();
- // Check if the character at index is a high surrogate.
- int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START;
- if (temp1 >= 0 && temp1 <= 0x7ff) {
- // Found a surrogate char.
- if (temp1 <= 0x3ff) {
- // Found a high surrogate.
- if (index < s.Length - 1) {
- int temp2 = (int)s[index+1] - CharUnicodeInfo.LOW_SURROGATE_START;
- if (temp2 >= 0 && temp2 <= 0x3ff) {
- // Found a low surrogate.
- return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
- } else {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
- }
- } else {
- // Found a high surrogate at the end of the string.
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHighSurrogate", index), nameof(s));
- }
- } else {
- // Find a low surrogate at the character pointed by index.
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidLowSurrogate", index), nameof(s));
- }
- }
- // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
- return ((int)s[index]);
- }
- }
-}
diff --git a/src/mscorlib/src/System/CharEnumerator.cs b/src/mscorlib/src/System/CharEnumerator.cs
deleted file mode 100644
index 689ed7e488..0000000000
--- a/src/mscorlib/src/System/CharEnumerator.cs
+++ /dev/null
@@ -1,81 +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: Enumerates the characters on a string. skips range
-** checks.
-**
-**
-============================================================*/
-
-using System.Collections;
-using System.Collections.Generic;
-
-namespace System
-{
- public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
- {
- private String _str;
- private int _index;
- private char _currentElement;
-
- internal CharEnumerator(String str)
- {
- _str = str;
- _index = -1;
- }
-
- public object Clone()
- {
- return MemberwiseClone();
- }
-
- public bool MoveNext()
- {
- if (_index < (_str.Length - 1))
- {
- _index++;
- _currentElement = _str[_index];
- return true;
- }
- else
- _index = _str.Length;
- return false;
- }
-
- public void Dispose()
- {
- if (_str != null)
- _index = _str.Length;
- _str = null;
- }
-
- /// <internalonly/>
- Object IEnumerator.Current
- {
- get { return Current; }
- }
-
- public char Current
- {
- get
- {
- if (_index == -1)
- throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
- if (_index >= _str.Length)
- throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
- return _currentElement;
- }
- }
-
- public void Reset()
- {
- _currentElement = (char)0;
- _index = -1;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/ArrayList.cs b/src/mscorlib/src/System/Collections/ArrayList.cs
index 53746e224e..cee7be726a 100644
--- a/src/mscorlib/src/System/Collections/ArrayList.cs
+++ b/src/mscorlib/src/System/Collections/ArrayList.cs
@@ -14,16 +14,18 @@
**
**
===========================================================*/
-namespace System.Collections {
- using System;
- using System.Runtime;
- using System.Security;
- using System.Diagnostics;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime;
+using System.Security;
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Diagnostics.CodeAnalysis;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
// Implements a variable-size List that uses an array of objects to store the
// elements. A ArrayList has a capacity, which is the allocated length
// of the internal array. As elements are added to a ArrayList, the capacity
@@ -31,7 +33,7 @@ namespace System.Collections {
// internal array.
//
[FriendAccessAllowed]
- [DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))]
+ [DebuggerTypeProxy(typeof(System.Collections.ArrayList.ArrayListDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
internal class ArrayList : IList, ICloneable
@@ -42,38 +44,41 @@ namespace System.Collections {
private int _version;
[NonSerialized]
private Object _syncRoot;
-
+
private const int _defaultCapacity = 4;
- private static readonly Object[] emptyArray = EmptyArray<Object>.Value;
+ private static readonly Object[] emptyArray = Array.Empty<Object>();
// Constructs a ArrayList. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to _defaultCapacity, and then increased in multiples of two as required.
- public ArrayList() {
- _items = emptyArray;
+ public ArrayList()
+ {
+ _items = emptyArray;
}
-
+
// Constructs a ArrayList with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
- public ArrayList(int capacity) {
- if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(capacity)));
- Contract.EndContractBlock();
-
- if (capacity == 0)
- _items = emptyArray;
- else
- _items = new Object[capacity];
+ public ArrayList(int capacity)
+ {
+ if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(capacity)));
+ Contract.EndContractBlock();
+
+ if (capacity == 0)
+ _items = emptyArray;
+ else
+ _items = new Object[capacity];
}
-
+
// Constructs a ArrayList, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
- public ArrayList(ICollection c) {
- if (c==null)
- throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
+ public ArrayList(ICollection c)
+ {
+ if (c == null)
+ throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection);
Contract.EndContractBlock();
int count = c.Count;
@@ -81,124 +86,147 @@ namespace System.Collections {
{
_items = emptyArray;
}
- else {
+ else
+ {
_items = new Object[count];
AddRange(c);
}
}
-
+
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
- public virtual int Capacity {
- get {
+ public virtual int Capacity
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= Count);
return _items.Length;
}
- set {
- if (value < _size) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ set
+ {
+ if (value < _size)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
}
Contract.Ensures(Capacity >= 0);
Contract.EndContractBlock();
// We don't want to update the version number when we change the capacity.
// Some existing applications have dependency on this.
- if (value != _items.Length) {
- if (value > 0) {
+ if (value != _items.Length)
+ {
+ if (value > 0)
+ {
Object[] newItems = new Object[value];
- if (_size > 0) {
+ if (_size > 0)
+ {
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
- else {
+ else
+ {
_items = new Object[_defaultCapacity];
}
- }
+ }
}
}
// Read-only property describing how many elements are in the List.
- public virtual int Count {
- get {
+ public virtual int Count
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
return _size;
}
}
- public virtual bool IsFixedSize {
+ public virtual bool IsFixedSize
+ {
get { return false; }
}
-
+
// Is this ArrayList read-only?
- public virtual bool IsReadOnly {
+ public virtual bool IsReadOnly
+ {
get { return false; }
}
// Is this ArrayList synchronized (thread-safe)?
- public virtual bool IsSynchronized {
+ public virtual bool IsSynchronized
+ {
get { return false; }
}
-
+
// Synchronization root for this object.
- public virtual Object SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ public virtual Object SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
- return _syncRoot;
+ return _syncRoot;
}
}
-
+
// Sets or Gets the element at the given index.
//
- public virtual Object this[int index] {
- get {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ public virtual Object this[int index]
+ {
+ get
+ {
+ if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
return _items[index];
}
- set {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ set
+ {
+ if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
_items[index] = value;
_version++;
}
}
-
+
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
//
- public virtual int Add(Object value) {
+ public virtual int Add(Object value)
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
if (_size == _items.Length) EnsureCapacity(_size + 1);
_items[_size] = value;
_version++;
return _size++;
}
-
+
// Adds the elements of the given collection to the end of this list. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
- public virtual void AddRange(ICollection c) {
+ public virtual void AddRange(ICollection c)
+ {
InsertRange(_size, c);
}
-
+
// Clears the contents of ArrayList.
- public virtual void Clear() {
+ public virtual void Clear()
+ {
if (_size > 0)
{
- Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
- _size = 0;
+ Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
+ _size = 0;
}
_version++;
}
-
+
// Clones this ArrayList, doing a shallow copy. (A copy is made of all
// Object references in the ArrayList, but the Objects pointed to
// are not cloned).
@@ -211,22 +239,25 @@ namespace System.Collections {
Array.Copy(_items, 0, la._items, 0, _size);
return la;
}
-
-
+
+
// Contains returns true if the specified element is in the ArrayList.
// It does a linear, O(n) search. Equality is determined by calling
// item.Equals().
//
- public virtual bool Contains(Object item) {
- if (item==null) {
- for(int i=0; i<_size; i++)
- if (_items[i]==null)
+ public virtual bool Contains(Object item)
+ {
+ if (item == null)
+ {
+ for (int i = 0; i < _size; i++)
+ if (_items[i] == null)
return true;
return false;
}
- else {
- for(int i=0; i<_size; i++)
- if ( (_items[i] != null) && (_items[i].Equals(item)) )
+ else
+ {
+ for (int i = 0; i < _size; i++)
+ if ((_items[i] != null) && (_items[i].Equals(item)))
return true;
return false;
}
@@ -235,9 +266,10 @@ namespace System.Collections {
// Copies this ArrayList into array, which must be of a
// compatible array type.
//
- public virtual void CopyTo(Array array, int arrayIndex) {
+ public virtual void CopyTo(Array array, int arrayIndex)
+ {
if ((array != null) && (array.Rank != 1))
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
Contract.EndContractBlock();
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
@@ -247,9 +279,11 @@ namespace System.Collections {
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
- private void EnsureCapacity(int min) {
- if (_items.Length < min) {
- int newCapacity = _items.Length == 0? _defaultCapacity: _items.Length * 2;
+ private void EnsureCapacity(int min)
+ {
+ if (_items.Length < min)
+ {
+ int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
@@ -257,17 +291,18 @@ namespace System.Collections {
Capacity = newCapacity;
}
}
-
+
// Returns an enumerator for this list with the given
// permission for removal of elements. If modifications made to the list
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
//
- public virtual IEnumerator GetEnumerator() {
+ public virtual IEnumerator GetEnumerator()
+ {
Contract.Ensures(Contract.Result<IEnumerator>() != null);
return new ArrayListEnumeratorSimple(this);
}
-
+
// Returns the index of the first occurrence of a given value in a range of
// this list. The list is searched forwards from beginning to end.
// The elements of the list are compared to the given value using the
@@ -276,47 +311,53 @@ namespace System.Collections {
// This method uses the Array.IndexOf method to perform the
// search.
//
- public virtual int IndexOf(Object value) {
+ public virtual int IndexOf(Object value)
+ {
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf((Array)_items, value, 0, _size);
}
-
+
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
- public virtual void Insert(int index, Object value) {
+ public virtual void Insert(int index, Object value)
+ {
// Note that insertions at the end are legal.
- if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_ArrayListInsert"));
+ if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_ArrayListInsert);
//Contract.Ensures(Count == Contract.OldValue(Count) + 1);
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = value;
_size++;
_version++;
}
-
+
// Inserts the elements of the given collection at a given index. If
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the ArrayList's size.
//
- public virtual void InsertRange(int index, ICollection c) {
- if (c==null)
- throw new ArgumentNullException(nameof(c), Environment.GetResourceString("ArgumentNull_Collection"));
- if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ public virtual void InsertRange(int index, ICollection c)
+ {
+ if (c == null)
+ throw new ArgumentNullException(nameof(c), SR.ArgumentNull_Collection);
+ if (index < 0 || index > _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
//Contract.Ensures(Count == Contract.OldValue(Count) + c.Count);
Contract.EndContractBlock();
int count = c.Count;
- if (count > 0) {
- EnsureCapacity(_size + count);
+ if (count > 0)
+ {
+ EnsureCapacity(_size + count);
// shift existing items
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index, _items, index + count, _size - index);
}
@@ -327,54 +368,59 @@ namespace System.Collections {
_version++;
}
}
-
+
// Returns a read-only IList wrapper for the given IList.
//
[FriendAccessAllowed]
- public static IList ReadOnly(IList list) {
- if (list==null)
+ public static IList ReadOnly(IList list)
+ {
+ if (list == null)
throw new ArgumentNullException(nameof(list));
Contract.Ensures(Contract.Result<IList>() != null);
Contract.EndContractBlock();
return new ReadOnlyList(list);
}
-
+
// Removes the element at the given index. The size of the list is
// decreased by one.
//
- public virtual void Remove(Object obj) {
+ public virtual void Remove(Object obj)
+ {
Contract.Ensures(Count >= 0);
int index = IndexOf(obj);
- BCLDebug.Correctness(index >= 0 || !(obj is Int32), "You passed an Int32 to Remove that wasn't in the ArrayList." + Environment.NewLine + "Did you mean RemoveAt? int: "+obj+" Count: "+Count);
- if (index >=0)
+ BCLDebug.Correctness(index >= 0 || !(obj is Int32), "You passed an Int32 to Remove that wasn't in the ArrayList." + Environment.NewLine + "Did you mean RemoveAt? int: " + obj + " Count: " + Count);
+ if (index >= 0)
RemoveAt(index);
}
-
+
// Removes the element at the given index. The size of the list is
// decreased by one.
//
- public virtual void RemoveAt(int index) {
- if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ public virtual void RemoveAt(int index)
+ {
+ if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
Contract.Ensures(Count >= 0);
//Contract.Ensures(Count == Contract.OldValue(Count) - 1);
Contract.EndContractBlock();
_size--;
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index + 1, _items, index, _size - index);
}
_items[_size] = null;
_version++;
}
-
+
// ToArray returns a new array of a particular type containing the contents
// of the ArrayList. This requires copying the ArrayList and potentially
// downcasting all elements. This copy may fail and is an O(n) operation.
// Internally, this implementation calls Array.Copy.
//
- public virtual Array ToArray(Type type) {
- if (type==null)
+ public virtual Array ToArray(Type type)
+ {
+ if (type == null)
throw new ArgumentNullException(nameof(type));
Contract.Ensures(Contract.Result<Array>() != null);
Contract.EndContractBlock();
@@ -382,84 +428,103 @@ namespace System.Collections {
Array.Copy(_items, 0, array, 0, _size);
return array;
}
-
+
[Serializable]
private class ReadOnlyList : IList
{
private IList _list;
-
- internal ReadOnlyList(IList l) {
+
+ internal ReadOnlyList(IList l)
+ {
_list = l;
}
-
- public virtual int Count {
+
+ public virtual int Count
+ {
get { return _list.Count; }
}
-
- public virtual bool IsReadOnly {
+
+ public virtual bool IsReadOnly
+ {
get { return true; }
}
- public virtual bool IsFixedSize {
+ public virtual bool IsFixedSize
+ {
get { return true; }
}
- public virtual bool IsSynchronized {
+ public virtual bool IsSynchronized
+ {
get { return _list.IsSynchronized; }
}
-
- public virtual Object this[int index] {
- get {
+
+ public virtual Object this[int index]
+ {
+ get
+ {
return _list[index];
}
- set {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
+ set
+ {
+ throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
}
-
- public virtual Object SyncRoot {
+
+ public virtual Object SyncRoot
+ {
get { return _list.SyncRoot; }
}
-
- public virtual int Add(Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
+
+ public virtual int Add(Object obj)
+ {
+ throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
-
- public virtual void Clear() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
+
+ public virtual void Clear()
+ {
+ throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
-
- public virtual bool Contains(Object obj) {
+
+ public virtual bool Contains(Object obj)
+ {
return _list.Contains(obj);
}
-
- public virtual void CopyTo(Array array, int index) {
+
+ public virtual void CopyTo(Array array, int index)
+ {
_list.CopyTo(array, index);
}
-
- public virtual IEnumerator GetEnumerator() {
+
+ public virtual IEnumerator GetEnumerator()
+ {
return _list.GetEnumerator();
}
-
- public virtual int IndexOf(Object value) {
+
+ public virtual int IndexOf(Object value)
+ {
return _list.IndexOf(value);
}
-
- public virtual void Insert(int index, Object obj) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
+
+ public virtual void Insert(int index, Object obj)
+ {
+ throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
- public virtual void Remove(Object value) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
+ public virtual void Remove(Object value)
+ {
+ throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
-
- public virtual void RemoveAt(int index) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReadOnlyCollection"));
+
+ public virtual void RemoveAt(int index)
+ {
+ throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
}
[Serializable]
- private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable {
+ private sealed class ArrayListEnumeratorSimple : IEnumerator, ICloneable
+ {
private ArrayList list;
private int index;
private int version;
@@ -467,77 +532,95 @@ namespace System.Collections {
[NonSerialized]
private bool isArrayList;
// this object is used to indicate enumeration has not started or has terminated
- static Object dummyObject = new Object();
-
- internal ArrayListEnumeratorSimple(ArrayList list) {
+ private static Object dummyObject = new Object();
+
+ internal ArrayListEnumeratorSimple(ArrayList list)
+ {
this.list = list;
- this.index = -1;
+ index = -1;
version = list._version;
isArrayList = (list.GetType() == typeof(ArrayList));
- currentElement = dummyObject;
+ currentElement = dummyObject;
}
-
- public Object Clone() {
+
+ public Object Clone()
+ {
return MemberwiseClone();
}
-
- public bool MoveNext() {
- if (version != list._version) {
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
+
+ public bool MoveNext()
+ {
+ if (version != list._version)
+ {
+ throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
}
- if( isArrayList) { // avoid calling virtual methods if we are operating on ArrayList to improve performance
- if (index < list._size - 1) {
+ if (isArrayList)
+ { // avoid calling virtual methods if we are operating on ArrayList to improve performance
+ if (index < list._size - 1)
+ {
currentElement = list._items[++index];
return true;
}
- else {
+ else
+ {
currentElement = dummyObject;
- index =list._size;
+ index = list._size;
return false;
- }
+ }
}
- else {
- if (index < list.Count - 1) {
+ else
+ {
+ if (index < list.Count - 1)
+ {
currentElement = list[++index];
return true;
}
- else {
+ else
+ {
index = list.Count;
currentElement = dummyObject;
return false;
}
}
}
-
- public Object Current {
- get {
+
+ public Object Current
+ {
+ get
+ {
object temp = currentElement;
- if(dummyObject == temp) { // check if enumeration has not started or has terminated
- if (index == -1) {
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
+ if (dummyObject == temp)
+ { // check if enumeration has not started or has terminated
+ if (index == -1)
+ {
+ throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
}
- else {
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
+ else
+ {
+ throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded));
}
}
return temp;
}
}
-
- public void Reset() {
- if (version != list._version) {
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- }
-
+
+ public void Reset()
+ {
+ if (version != list._version)
+ {
+ throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
+ }
+
currentElement = dummyObject;
index = -1;
}
}
- internal class ArrayListDebugView {
- private ArrayList arrayList;
+ internal class ArrayListDebugView
+ {
+ private ArrayList arrayList;
}
- }
+ }
}
diff --git a/src/mscorlib/src/System/Collections/CollectionBase.cs b/src/mscorlib/src/System/Collections/CollectionBase.cs
deleted file mode 100644
index a3dd88a7b3..0000000000
--- a/src/mscorlib/src/System/Collections/CollectionBase.cs
+++ /dev/null
@@ -1,199 +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.
-
-//------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
-//
-
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
-
- // Useful base class for typed read/write collections where items derive from object
- [Serializable]
- public abstract class CollectionBase : IList {
- private ArrayList list;
-
- protected CollectionBase() {
- list = new ArrayList();
- }
-
- internal ArrayList InnerList {
- get {
- if (list == null)
- list = new ArrayList();
- return list;
- }
- }
-
- protected IList List {
- get { return (IList)this; }
- }
-
-
- public int Count {
- get {
- return list == null ? 0 : list.Count;
- }
- }
-
- public void Clear() {
- OnClear();
- InnerList.Clear();
- OnClearComplete();
- }
-
- public void RemoveAt(int index) {
- if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- Object temp = InnerList[index];
- OnValidate(temp);
- OnRemove(index, temp);
- InnerList.RemoveAt(index);
- try {
- OnRemoveComplete(index, temp);
- }
- catch {
- InnerList.Insert(index, temp);
- throw;
- }
-
- }
-
- bool IList.IsReadOnly {
- get { return InnerList.IsReadOnly; }
- }
-
- bool IList.IsFixedSize {
- get { return InnerList.IsFixedSize; }
- }
-
- bool ICollection.IsSynchronized {
- get { return InnerList.IsSynchronized; }
- }
-
- Object ICollection.SyncRoot {
- get { return InnerList.SyncRoot; }
- }
-
- void ICollection.CopyTo(Array array, int index) {
- InnerList.CopyTo(array, index);
- }
-
- Object IList.this[int index] {
- get {
- if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- return InnerList[index];
- }
- set {
- if (index < 0 || index >= Count)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- OnValidate(value);
- Object temp = InnerList[index];
- OnSet(index, temp, value);
- InnerList[index] = value;
- try {
- OnSetComplete(index, temp, value);
- }
- catch {
- InnerList[index] = temp;
- throw;
- }
- }
- }
-
- bool IList.Contains(Object value) {
- return InnerList.Contains(value);
- }
-
- int IList.Add(Object value) {
- OnValidate(value);
- OnInsert(InnerList.Count, value);
- int index = InnerList.Add(value);
- try {
- OnInsertComplete(index, value);
- }
- catch {
- InnerList.RemoveAt(index);
- throw;
- }
- return index;
- }
-
-
- void IList.Remove(Object value) {
- OnValidate(value);
- int index = InnerList.IndexOf(value);
- if (index < 0) throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
- OnRemove(index, value);
- InnerList.RemoveAt(index);
- try{
- OnRemoveComplete(index, value);
- }
- catch {
- InnerList.Insert(index, value);
- throw;
- }
- }
-
- int IList.IndexOf(Object value) {
- return InnerList.IndexOf(value);
- }
-
- void IList.Insert(int index, Object value) {
- if (index < 0 || index > Count)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- Contract.EndContractBlock();
- OnValidate(value);
- OnInsert(index, value);
- InnerList.Insert(index, value);
- try {
- OnInsertComplete(index, value);
- }
- catch {
- InnerList.RemoveAt(index);
- throw;
- }
- }
-
- public IEnumerator GetEnumerator() {
- return InnerList.GetEnumerator();
- }
-
- protected virtual void OnSet(int index, Object oldValue, Object newValue) {
- }
-
- protected virtual void OnInsert(int index, Object value) {
- }
-
- protected virtual void OnClear() {
- }
-
- protected virtual void OnRemove(int index, Object value) {
- }
-
- protected virtual void OnValidate(Object value) {
- if (value == null) throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
- }
-
- protected virtual void OnSetComplete(int index, Object oldValue, Object newValue) {
- }
-
- protected virtual void OnInsertComplete(int index, Object value) {
- }
-
- protected virtual void OnClearComplete() {
- }
-
- protected virtual void OnRemoveComplete(int index, Object value) {
- }
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Collections/Comparer.cs b/src/mscorlib/src/System/Collections/Comparer.cs
index 928b0f9f9a..7f4f9f0a07 100644
--- a/src/mscorlib/src/System/Collections/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Comparer.cs
@@ -12,46 +12,53 @@
**
**
===========================================================*/
-namespace System.Collections {
-
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
+using System;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
[Serializable]
- internal sealed class Comparer : IComparer , ISerializable
+ internal sealed class Comparer : IComparer, ISerializable
{
- private CompareInfo m_compareInfo;
+ private CompareInfo m_compareInfo;
public static readonly Comparer Default = new Comparer(CultureInfo.CurrentCulture);
public static readonly Comparer DefaultInvariant = new Comparer(CultureInfo.InvariantCulture);
-
+
private const String CompareInfoName = "CompareInfo";
- private Comparer() {
+ private Comparer()
+ {
m_compareInfo = null;
}
- public Comparer(CultureInfo culture) {
- if (culture==null) {
+ public Comparer(CultureInfo culture)
+ {
+ if (culture == null)
+ {
throw new ArgumentNullException(nameof(culture));
}
Contract.EndContractBlock();
m_compareInfo = culture.CompareInfo;
}
-
- private Comparer(SerializationInfo info, StreamingContext context) {
+
+ private Comparer(SerializationInfo info, StreamingContext context)
+ {
m_compareInfo = null;
- SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while( enumerator.MoveNext()) {
- switch( enumerator.Name) {
+ SerializationInfoEnumerator enumerator = info.GetEnumerator();
+ while (enumerator.MoveNext())
+ {
+ switch (enumerator.Name)
+ {
case CompareInfoName:
- m_compareInfo = (CompareInfo) info.GetValue(CompareInfoName, typeof(CompareInfo));
+ m_compareInfo = (CompareInfo)info.GetValue(CompareInfoName, typeof(CompareInfo));
break;
}
}
}
-
+
// Compares two Objects by calling CompareTo. If a ==
// b,0 is returned. If a implements
// IComparable, a.CompareTo(b) is returned. If a
@@ -59,11 +66,13 @@ namespace System.Collections {
// -(b.CompareTo(a)) is returned, otherwise an
// exception is thrown.
//
- public int Compare(Object a, Object b) {
+ public int Compare(Object a, Object b)
+ {
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
- if (m_compareInfo != null) {
+ if (m_compareInfo != null)
+ {
String sa = a as String;
String sb = b as String;
if (sa != null && sb != null)
@@ -78,18 +87,21 @@ namespace System.Collections {
if (ib != null)
return -ib.CompareTo(a);
- throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
+ throw new ArgumentException(SR.Argument_ImplementIComparable);
}
- public void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
- if( m_compareInfo != null) {
+ if (m_compareInfo != null)
+ {
info.AddValue(CompareInfoName, m_compareInfo);
}
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Collections/CompatibleComparer.cs b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
index e5d3961245..1c90707184 100644
--- a/src/mscorlib/src/System/Collections/CompatibleComparer.cs
+++ b/src/mscorlib/src/System/Collections/CompatibleComparer.cs
@@ -6,39 +6,45 @@
using System.Diagnostics.Contracts;
-namespace System.Collections {
-
+namespace System.Collections
+{
[Serializable]
- internal class CompatibleComparer: IEqualityComparer {
- IComparer _comparer;
+ internal class CompatibleComparer : IEqualityComparer
+ {
+ private IComparer _comparer;
#pragma warning disable 618
- IHashCodeProvider _hcp;
+ private IHashCodeProvider _hcp;
- internal CompatibleComparer(IComparer comparer, IHashCodeProvider hashCodeProvider) {
+ internal CompatibleComparer(IComparer comparer, IHashCodeProvider hashCodeProvider)
+ {
_comparer = comparer;
_hcp = hashCodeProvider;
}
#pragma warning restore 618
- public int Compare(Object a, Object b) {
+ public int Compare(Object a, Object b)
+ {
if (a == b) return 0;
if (a == null) return -1;
if (b == null) return 1;
if (_comparer != null)
- return _comparer.Compare(a,b);
+ return _comparer.Compare(a, b);
IComparable ia = a as IComparable;
if (ia != null)
return ia.CompareTo(b);
- throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
+ throw new ArgumentException(SR.Argument_ImplementIComparable);
}
- public new bool Equals(Object a, Object b) {
- return Compare(a, b) == 0;
+ public new bool Equals(Object a, Object b)
+ {
+ return Compare(a, b) == 0;
}
- public int GetHashCode(Object obj) {
- if( obj == null) {
+ public int GetHashCode(Object obj)
+ {
+ if (obj == null)
+ {
throw new ArgumentNullException(nameof(obj));
}
Contract.EndContractBlock();
@@ -49,16 +55,20 @@ namespace System.Collections {
}
// These are helpers for the Hashtable to query the IKeyComparer infrastructure.
- internal IComparer Comparer {
- get {
+ internal IComparer Comparer
+ {
+ get
+ {
return _comparer;
}
}
// These are helpers for the Hashtable to query the IKeyComparer infrastructure.
#pragma warning disable 618
- internal IHashCodeProvider HashCodeProvider {
- get {
+ internal IHashCodeProvider HashCodeProvider
+ {
+ get
+ {
return _hcp;
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
index 8b9014a103..436808c439 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
@@ -65,7 +65,7 @@ namespace System.Collections.Concurrent
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;
+ 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.
@@ -102,6 +102,10 @@ namespace System.Collections.Concurrent
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
@@ -705,7 +709,6 @@ namespace System.Collections.Concurrent
{
count += m_tables.m_countPerLock[i];
}
-
}
finally
{
@@ -1404,7 +1407,6 @@ namespace System.Collections.Concurrent
/// </summary>
private static int DefaultConcurrencyLevel
{
-
get { return DEFAULT_CONCURRENCY_MULTIPLIER * PlatformHelper.ProcessorCount; }
}
@@ -1559,7 +1561,7 @@ namespace System.Collections.Concurrent
/// </summary>
private class DictionaryEnumerator : IDictionaryEnumerator
{
- IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; // Enumerator over the dictionary.
+ private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; // Enumerator over the dictionary.
internal DictionaryEnumerator(ConcurrentDictionary<TKey, TValue> dictionary)
{
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
index 90ada007dd..c6211dadd3 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -205,7 +205,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(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported")); } }
+ object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } }
/// <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>
@@ -443,7 +443,7 @@ namespace System.Collections.Concurrent
long count = GetCount(head, headHead, tail, tailTail);
if (index > array.Length - count)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
+ throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
// Copy the items to the target array
@@ -1115,7 +1115,7 @@ namespace System.Collections.Concurrent
[StructLayout(LayoutKind.Explicit, Size = 192)] // padding before/between/after fields based on typical cache line size of 64
internal struct PaddedHeadAndTail
{
- [FieldOffset(64)] public int Head;
+ [FieldOffset(64)] public int Head;
[FieldOffset(128)] public int Tail;
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
index 10a5201f6c..82bc4f9f5c 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
@@ -135,7 +135,7 @@ namespace System.Collections.Concurrent
{
get
{
- throw new NotSupportedException(Environment.GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"));
+ throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported);
}
}
@@ -306,7 +306,6 @@ namespace System.Collections.Concurrent
result = default(T);
return false;
-
}
/// <summary>
@@ -328,7 +327,7 @@ namespace System.Collections.Concurrent
Node head;
Node next;
int backoff = 1;
- Random r = new Random(Environment.TickCount & Int32.MaxValue); // avoid the case where TickCount could return Int32.MinValue
+ Random r = null;
while (true)
{
head = m_head;
@@ -359,7 +358,18 @@ namespace System.Collections.Concurrent
spin.SpinOnce();
}
- backoff = spin.NextSpinWillYield ? r.Next(1, BACKOFF_MAX_YIELDS) : backoff * 2;
+ if (spin.NextSpinWillYield)
+ {
+ if (r == null)
+ {
+ r = new Random();
+ }
+ backoff = r.Next(1, BACKOFF_MAX_YIELDS);
+ }
+ else
+ {
+ backoff *= 2;
+ }
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs b/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
index 0347ece0ec..7c585d8b98 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/IProducerConsumerCollection.cs
@@ -16,7 +16,6 @@ using System.Diagnostics;
namespace System.Collections.Concurrent
{
-
/// <summary>
/// Defines methods to manipulate thread-safe collections intended for producer/consumer usage.
/// </summary>
@@ -64,6 +63,5 @@ namespace System.Collections.Concurrent
internal sealed class SystemCollectionsConcurrent_ProducerConsumerCollectionDebugView<T>
{
private IProducerConsumerCollection<T> m_collection; // The collection being viewed.
-
}
}
diff --git a/src/mscorlib/src/System/Collections/DictionaryEntry.cs b/src/mscorlib/src/System/Collections/DictionaryEntry.cs
deleted file mode 100644
index 0c5d8b2387..0000000000
--- a/src/mscorlib/src/System/Collections/DictionaryEntry.cs
+++ /dev/null
@@ -1,62 +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.
-
-/*============================================================
-**
-** Interface: DictionaryEntry
-**
-**
-**
-**
-** Purpose: Return Value for IDictionaryEnumerator::GetEntry
-**
-**
-===========================================================*/
-namespace System.Collections {
-
- using System;
- using System.ComponentModel;
- // A DictionaryEntry holds a key and a value from a dictionary.
- // It is returned by IDictionaryEnumerator::GetEntry().
- [Serializable]
- public struct DictionaryEntry
- {
- private Object _key;
- private Object _value;
-
- // Constructs a new DictionaryEnumerator by setting the Key
- // and Value fields appropriately.
- public DictionaryEntry(Object key, Object value) {
- _key = key;
- _value = value;
- }
-
- public Object Key {
- get {
- return _key;
- }
-
- set {
- _key = value;
- }
- }
-
- public Object Value {
- get {
- return _value;
- }
-
- set {
- _value = value;
- }
- }
-
- [EditorBrowsable(EditorBrowsableState.Never)]
- public void Deconstruct(out object key, out object value)
- {
- key = Key;
- value = Value;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
index a610fce016..63e0d47c75 100644
--- a/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/EmptyReadOnlyDictionaryInternal.cs
@@ -15,178 +15,218 @@
using System.Diagnostics.Contracts;
-namespace System.Collections {
+namespace System.Collections
+{
/// This is a simple implementation of IDictionary that is empty and readonly.
[Serializable]
- internal sealed class EmptyReadOnlyDictionaryInternal: IDictionary {
-
+ internal sealed class EmptyReadOnlyDictionaryInternal : IDictionary
+ {
// Note that this class must be agile with respect to AppDomains. See its usage in
// System.Exception to understand why this is the case.
- public EmptyReadOnlyDictionaryInternal() {
+ public EmptyReadOnlyDictionaryInternal()
+ {
}
// IEnumerable members
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return new NodeEnumerator();
}
// ICollection members
- public void CopyTo(Array array, int index) {
- if (array==null)
+ public void CopyTo(Array array, int index)
+ {
+ if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
- if ( array.Length - index < this.Count )
- throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
+ if (array.Length - index < this.Count)
+ throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
Contract.EndContractBlock();
// the actual copy is a NOP
}
- public int Count {
- get {
+ public int Count
+ {
+ get
+ {
return 0;
}
- }
+ }
- public Object SyncRoot {
- get {
+ public Object SyncRoot
+ {
+ get
+ {
return this;
}
}
- public bool IsSynchronized {
- get {
+ public bool IsSynchronized
+ {
+ get
+ {
return false;
}
}
// IDictionary members
- public Object this[Object key] {
- get {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public Object this[Object key]
+ {
+ get
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
return null;
}
- set {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ set
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key));
+ if (!key.GetType().IsSerializable)
+ throw new ArgumentException(SR.Argument_NotSerializable, nameof(key));
- if( (value != null) && (!value.GetType().IsSerializable ) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
+ if ((value != null) && (!value.GetType().IsSerializable))
+ throw new ArgumentException(SR.Argument_NotSerializable, nameof(value));
Contract.EndContractBlock();
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
- public ICollection Keys {
- get {
- return EmptyArray<Object>.Value;
+ public ICollection Keys
+ {
+ get
+ {
+ return Array.Empty<Object>();
}
}
- public ICollection Values {
- get {
- return EmptyArray<Object>.Value;
+ public ICollection Values
+ {
+ get
+ {
+ return Array.Empty<Object>();
}
}
- public bool Contains(Object key) {
+ public bool Contains(Object key)
+ {
return false;
}
- public void Add(Object key, Object value) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public void Add(Object key, Object value)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
- if (!key.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key) );
+ if (!key.GetType().IsSerializable)
+ throw new ArgumentException(SR.Argument_NotSerializable, nameof(key));
- if( (value != null) && (!value.GetType().IsSerializable) )
- throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value));
+ if ((value != null) && (!value.GetType().IsSerializable))
+ throw new ArgumentException(SR.Argument_NotSerializable, nameof(value));
Contract.EndContractBlock();
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- public void Clear() {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ public void Clear()
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- public bool IsReadOnly {
- get {
+ public bool IsReadOnly
+ {
+ get
+ {
return true;
}
}
- public bool IsFixedSize {
- get {
+ public bool IsFixedSize
+ {
+ get
+ {
return true;
}
}
- public IDictionaryEnumerator GetEnumerator() {
+ public IDictionaryEnumerator GetEnumerator()
+ {
return new NodeEnumerator();
}
- public void Remove(Object key) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ public void Remove(Object key)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- private sealed class NodeEnumerator : IDictionaryEnumerator {
-
- public NodeEnumerator() {
+ private sealed class NodeEnumerator : IDictionaryEnumerator
+ {
+ public NodeEnumerator()
+ {
}
// IEnumerator members
- public bool MoveNext() {
+ public bool MoveNext()
+ {
return false;
}
- public Object Current {
- get {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public Object Current
+ {
+ get
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
}
- public void Reset() {
+ public void Reset()
+ {
}
// IDictionaryEnumerator members
- public Object Key {
- get {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public Object Key
+ {
+ get
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
}
- public Object Value {
- get {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public Object Value
+ {
+ get
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
}
- public DictionaryEntry Entry {
- get {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public DictionaryEntry Entry
+ {
+ get
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
index 298ac3e177..e313cda0fb 100644
--- a/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
+++ b/src/mscorlib/src/System/Collections/Generic/ArraySortHelper.cs
@@ -12,15 +12,16 @@
**
**
===========================================================*/
+
+using System;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
+
namespace System.Collections.Generic
{
- using System;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Runtime.Versioning;
-
#region ArraySortHelper for single arrays
internal interface IArraySortHelper<TKey>
@@ -36,8 +37,6 @@ namespace System.Collections.Generic
// Large value types may benefit from a smaller number.
internal const int IntrosortSizeThreshold = 16;
- internal const int QuickSortDepthThreshold = 32;
-
internal static int FloorLog2(int n)
{
int result = 0;
@@ -49,18 +48,18 @@ namespace System.Collections.Generic
return result;
}
- internal static void ThrowOrIgnoreBadComparer(Object comparer) {
- throw new ArgumentException(Environment.GetResourceString("Arg_BogusIComparer", comparer));
+ internal static void ThrowOrIgnoreBadComparer(Object comparer)
+ {
+ throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer));
}
-
}
- [TypeDependencyAttribute("System.Collections.Generic.GenericArraySortHelper`1")]
- internal class ArraySortHelper<T>
+ [TypeDependencyAttribute("System.Collections.Generic.GenericArraySortHelper`1")]
+ internal class ArraySortHelper<T>
: IArraySortHelper<T>
{
- static volatile IArraySortHelper<T> defaultArraySortHelper;
-
+ private static volatile IArraySortHelper<T> defaultArraySortHelper;
+
public static IArraySortHelper<T> Default
{
get
@@ -71,8 +70,8 @@ namespace System.Collections.Generic
return sorter;
}
- }
-
+ }
+
private static IArraySortHelper<T> CreateArraySortHelper()
{
if (typeof(IComparable<T>).IsAssignableFrom(typeof(T)))
@@ -81,7 +80,7 @@ namespace System.Collections.Generic
}
else
{
- defaultArraySortHelper = new ArraySortHelper<T>();
+ defaultArraySortHelper = new ArraySortHelper<T>();
}
return defaultArraySortHelper;
}
@@ -91,7 +90,7 @@ namespace System.Collections.Generic
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
- Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
@@ -110,7 +109,7 @@ namespace System.Collections.Generic
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -127,7 +126,7 @@ namespace System.Collections.Generic
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -150,7 +149,7 @@ namespace System.Collections.Generic
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -241,9 +240,9 @@ namespace System.Collections.Generic
}
if (partitionSize == 3)
{
- SwapIfGreater(keys, comparer, lo, hi-1);
+ SwapIfGreater(keys, comparer, lo, hi - 1);
SwapIfGreater(keys, comparer, lo, hi);
- SwapIfGreater(keys, comparer, hi-1, hi);
+ SwapIfGreater(keys, comparer, hi - 1, hi);
return;
}
@@ -375,7 +374,7 @@ namespace System.Collections.Generic
where T : IComparable<T>
{
// Do not add a constructor to this class because ArraySortHelper<T>.CreateSortHelper will not execute it
-
+
#region IArraySortHelper<T> Members
public void Sort(T[] keys, int index, int length, IComparer<T> comparer)
@@ -400,7 +399,7 @@ namespace System.Collections.Generic
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -422,7 +421,7 @@ namespace System.Collections.Generic
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -485,7 +484,7 @@ namespace System.Collections.Generic
private static void Swap(T[] a, int i, int j)
{
- if(i!=j)
+ if (i != j)
{
T t = a[i];
a[i] = a[j];
@@ -529,9 +528,9 @@ namespace System.Collections.Generic
}
if (partitionSize == 3)
{
- SwapIfGreaterWithItems(keys, lo, hi-1);
+ SwapIfGreaterWithItems(keys, lo, hi - 1);
SwapIfGreaterWithItems(keys, lo, hi);
- SwapIfGreaterWithItems(keys, hi-1, hi);
+ SwapIfGreaterWithItems(keys, hi - 1, hi);
return;
}
@@ -662,7 +661,7 @@ namespace System.Collections.Generic
}
}
-#endregion
+ #endregion
#region ArraySortHelper for paired key and value arrays
@@ -675,7 +674,7 @@ namespace System.Collections.Generic
internal class ArraySortHelper<TKey, TValue>
: IArraySortHelper<TKey, TValue>
{
- static volatile IArraySortHelper<TKey, TValue> defaultArraySortHelper;
+ private static volatile IArraySortHelper<TKey, TValue> defaultArraySortHelper;
public static IArraySortHelper<TKey, TValue> Default
{
@@ -724,7 +723,7 @@ namespace System.Collections.Generic
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -755,12 +754,12 @@ namespace System.Collections.Generic
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
- if(i!=j)
+ if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
- if(values != null)
+ if (values != null)
{
TValue v = values[i];
values[i] = values[j];
@@ -810,9 +809,9 @@ namespace System.Collections.Generic
}
if (partitionSize == 3)
{
- SwapIfGreaterWithItems(keys, values, comparer, lo, hi-1);
+ SwapIfGreaterWithItems(keys, values, comparer, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, comparer, lo, hi);
- SwapIfGreaterWithItems(keys, values, comparer, hi-1, hi);
+ SwapIfGreaterWithItems(keys, values, comparer, hi - 1, hi);
return;
}
@@ -913,12 +912,12 @@ namespace System.Collections.Generic
if (!(comparer.Compare(d, keys[lo + child - 1]) < 0))
break;
keys[lo + i - 1] = keys[lo + child - 1];
- if(values != null)
+ if (values != null)
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
- if(values != null)
+ if (values != null)
values[lo + i - 1] = dValue;
}
@@ -942,12 +941,12 @@ namespace System.Collections.Generic
while (j >= lo && comparer.Compare(t, keys[j]) < 0)
{
keys[j + 1] = keys[j];
- if(values != null)
+ if (values != null)
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
- if(values != null)
+ if (values != null)
values[j + 1] = tValue;
}
}
@@ -960,8 +959,8 @@ namespace System.Collections.Generic
public void Sort(TKey[] keys, TValue[] values, int index, int length, IComparer<TKey> comparer)
{
Debug.Assert(keys != null, "Check the arguments in the caller!");
- Debug.Assert( index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
-
+ Debug.Assert(index >= 0 && length >= 0 && (keys.Length - index >= length), "Check the arguments in the caller!");
+
// Add a try block here to detect IComparers (or their
// underlying IComparables, etc) that are bogus.
try
@@ -974,14 +973,14 @@ namespace System.Collections.Generic
{
ArraySortHelper<TKey, TValue>.IntrospectiveSort(keys, values, index, length, comparer);
}
- }
+ }
catch (IndexOutOfRangeException)
{
IntrospectiveSortUtilities.ThrowOrIgnoreBadComparer(comparer);
}
catch (Exception e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_IComparerFailed"), e);
+ throw new InvalidOperationException(SR.InvalidOperation_IComparerFailed, e);
}
}
@@ -1006,12 +1005,12 @@ namespace System.Collections.Generic
private static void Swap(TKey[] keys, TValue[] values, int i, int j)
{
- if(i != j)
+ if (i != j)
{
TKey k = keys[i];
keys[i] = keys[j];
keys[j] = k;
- if(values != null)
+ if (values != null)
{
TValue v = values[i];
values[i] = values[j];
@@ -1059,9 +1058,9 @@ namespace System.Collections.Generic
}
if (partitionSize == 3)
{
- SwapIfGreaterWithItems(keys, values, lo, hi-1);
+ SwapIfGreaterWithItems(keys, values, lo, hi - 1);
SwapIfGreaterWithItems(keys, values, lo, hi);
- SwapIfGreaterWithItems(keys, values, hi-1, hi);
+ SwapIfGreaterWithItems(keys, values, hi - 1, hi);
return;
}
@@ -1106,10 +1105,10 @@ namespace System.Collections.Generic
while (left < right)
{
- if(pivot == null)
+ if (pivot == null)
{
while (left < (hi - 1) && keys[++left] == null) ;
- while (right > lo && keys[--right] != null);
+ while (right > lo && keys[--right] != null) ;
}
else
{
@@ -1167,12 +1166,12 @@ namespace System.Collections.Generic
if (keys[lo + child - 1] == null || keys[lo + child - 1].CompareTo(d) < 0)
break;
keys[lo + i - 1] = keys[lo + child - 1];
- if(values != null)
+ if (values != null)
values[lo + i - 1] = values[lo + child - 1];
i = child;
}
keys[lo + i - 1] = d;
- if(values != null)
+ if (values != null)
values[lo + i - 1] = dValue;
}
@@ -1191,16 +1190,16 @@ namespace System.Collections.Generic
{
j = i;
t = keys[i + 1];
- tValue = (values != null)? values[i + 1] : default(TValue);
+ tValue = (values != null) ? values[i + 1] : default(TValue);
while (j >= lo && (t == null || t.CompareTo(keys[j]) < 0))
{
keys[j + 1] = keys[j];
- if(values != null)
+ if (values != null)
values[j + 1] = values[j];
j--;
}
keys[j + 1] = t;
- if(values != null)
+ if (values != null)
values[j + 1] = tValue;
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/Comparer.cs b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
index 056843a606..a9b4b3f0dd 100644
--- a/src/mscorlib/src/System/Collections/Generic/Comparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Comparer.cs
@@ -15,19 +15,14 @@ using System.Security;
using System.Runtime.Serialization;
namespace System.Collections.Generic
-{
+{
[Serializable]
- [TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
+ [TypeDependencyAttribute("System.Collections.Generic.ObjectComparer`1")]
public abstract class Comparer<T> : IComparer, IComparer<T>
{
- static readonly Comparer<T> defaultComparer = CreateComparer();
-
- public static Comparer<T> Default {
- get {
- Contract.Ensures(Contract.Result<Comparer<T>>() != null);
- return defaultComparer;
- }
- }
+ // To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small
+ // as possible and define most of the creation logic in a non-generic class.
+ public static Comparer<T> Default { get; } = (Comparer<T>)ComparerHelpers.CreateDefaultComparer(typeof(T));
public static Comparer<T> Create(Comparison<T> comparison)
{
@@ -39,69 +34,10 @@ namespace System.Collections.Generic
return new ComparisonComparer<T>(comparison);
}
- //
- // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
- // saves the right instantiations
- //
- private static Comparer<T> CreateComparer()
- {
- object result = null;
- RuntimeType t = (RuntimeType)typeof(T);
-
- // If T implements IComparable<T> return a GenericComparer<T>
- if (typeof(IComparable<T>).IsAssignableFrom(t))
- {
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), t);
- }
- else if (default(T) == null)
- {
- // If T is a Nullable<U> where U implements IComparable<U> return a NullableComparer<U>
- if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
- RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
- if (typeof(IComparable<>).MakeGenericType(u).IsAssignableFrom(u)) {
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), u);
- }
- }
- }
- else if (t.IsEnum)
- {
- // Explicitly call Enum.GetUnderlyingType here. Although GetTypeCode
- // ends up doing this anyway, we end up avoiding an unnecessary P/Invoke
- // and virtual method call.
- TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t));
-
- // Depending on the enum type, we need to special case the comparers so that we avoid boxing
- // Specialize differently for signed/unsigned types so we avoid problems with large numbers
- switch (underlyingTypeCode)
- {
- case TypeCode.SByte:
- case TypeCode.Int16:
- case TypeCode.Int32:
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int32EnumComparer<int>), t);
- break;
- case TypeCode.Byte:
- case TypeCode.UInt16:
- case TypeCode.UInt32:
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt32EnumComparer<uint>), t);
- break;
- // 64-bit enums: use UnsafeEnumCastLong
- case TypeCode.Int64:
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int64EnumComparer<long>), t);
- break;
- case TypeCode.UInt64:
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt64EnumComparer<ulong>), t);
- break;
- }
- }
-
- return result != null ?
- (Comparer<T>)result :
- new ObjectComparer<T>(); // Fallback to ObjectComparer, which uses boxing
- }
-
public abstract int Compare(T x, T y);
- int IComparer.Compare(object x, object y) {
+ int IComparer.Compare(object x, object y)
+ {
if (x == null) return y == null ? 0 : -1;
if (y == null) return 1;
if (x is T && y is T) return Compare((T)x, (T)y);
@@ -109,18 +45,20 @@ namespace System.Collections.Generic
return 0;
}
}
-
+
// Note: although there is a lot of shared code in the following
// comparers, we do not incorporate it into a base class for perf
// reasons. Adding another base class (even one with no fields)
// means another generic instantiation, which can be costly esp.
// for value types.
-
+
[Serializable]
internal sealed class GenericComparer<T> : Comparer<T> where T : IComparable<T>
- {
- public override int Compare(T x, T y) {
- if (x != null) {
+ {
+ public override int Compare(T x, T y)
+ {
+ if (x != null)
+ {
if (y != null) return x.CompareTo(y);
return 1;
}
@@ -139,8 +77,10 @@ namespace System.Collections.Generic
[Serializable]
internal sealed class NullableComparer<T> : Comparer<T?> where T : struct, IComparable<T>
{
- public override int Compare(T? x, T? y) {
- if (x.HasValue) {
+ public override int Compare(T? x, T? y)
+ {
+ if (x.HasValue)
+ {
if (y.HasValue) return x.value.CompareTo(y.value);
return 1;
}
@@ -159,7 +99,8 @@ namespace System.Collections.Generic
[Serializable]
internal sealed class ObjectComparer<T> : Comparer<T>
{
- public override int Compare(T x, T y) {
+ public override int Compare(T x, T y)
+ {
return System.Collections.Comparer.Default.Compare(x, y);
}
@@ -176,11 +117,13 @@ namespace System.Collections.Generic
{
private readonly Comparison<T> _comparison;
- public ComparisonComparer(Comparison<T> comparison) {
+ public ComparisonComparer(Comparison<T> comparison)
+ {
_comparison = comparison;
}
- public override int Compare(T x, T y) {
+ public override int Compare(T x, T y)
+ {
return _comparison(x, y);
}
}
@@ -196,12 +139,12 @@ namespace System.Collections.Generic
{
public Int32EnumComparer()
{
- Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum);
}
-
+
// Used by the serialization engine.
private Int32EnumComparer(SerializationInfo info, StreamingContext context) { }
-
+
public override int Compare(T x, T y)
{
int ix = JitHelpers.UnsafeEnumCast(x);
@@ -231,12 +174,12 @@ namespace System.Collections.Generic
{
public UInt32EnumComparer()
{
- Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum);
}
-
+
// Used by the serialization engine.
private UInt32EnumComparer(SerializationInfo info, StreamingContext context) { }
-
+
public override int Compare(T x, T y)
{
uint ix = (uint)JitHelpers.UnsafeEnumCast(x);
@@ -262,9 +205,9 @@ namespace System.Collections.Generic
{
public Int64EnumComparer()
{
- Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum);
}
-
+
public override int Compare(T x, T y)
{
long lx = JitHelpers.UnsafeEnumCastLong(x);
@@ -290,12 +233,12 @@ namespace System.Collections.Generic
{
public UInt64EnumComparer()
{
- Debug.Assert(typeof(T).IsEnum, "This type is only intended to be used to compare enums!");
+ Debug.Assert(typeof(T).IsEnum);
}
-
+
// Used by the serialization engine.
private UInt64EnumComparer(SerializationInfo info, StreamingContext context) { }
-
+
public override int Compare(T x, T y)
{
ulong lx = (ulong)JitHelpers.UnsafeEnumCastLong(x);
diff --git a/src/mscorlib/src/System/Collections/Generic/ComparerHelpers.cs b/src/mscorlib/src/System/Collections/Generic/ComparerHelpers.cs
new file mode 100644
index 0000000000..3e428413d4
--- /dev/null
+++ b/src/mscorlib/src/System/Collections/Generic/ComparerHelpers.cs
@@ -0,0 +1,210 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using static System.RuntimeTypeHandle;
+
+namespace System.Collections.Generic
+{
+ /// <summary>
+ /// Helper class for creating the default <see cref="Comparer{T}"/> and <see cref="EqualityComparer{T}"/>.
+ /// </summary>
+ /// <remarks>
+ /// This class is intentionally type-unsafe and non-generic to minimize the generic instantiation overhead of creating
+ /// the default comparer/equality comparer for a new type parameter. Efficiency of the methods in here does not matter too
+ /// much since they will only be run once per type parameter, but generic code involved in creating the comparers needs to be
+ /// kept to a minimum.
+ /// </remarks>
+ internal static class ComparerHelpers
+ {
+ /// <summary>
+ /// Creates the default <see cref="Comparer{T}"/>.
+ /// </summary>
+ /// <param name="type">The type to create the default comparer for.</param>
+ /// <remarks>
+ /// The logic in this method is replicated in vm/compile.cpp to ensure that NGen saves the right instantiations.
+ /// </remarks>
+ internal static object CreateDefaultComparer(Type type)
+ {
+ Debug.Assert(type != null && type is RuntimeType);
+
+ object result = null;
+ var runtimeType = (RuntimeType)type;
+
+ // If T implements IComparable<T> return a GenericComparer<T>
+ if (typeof(IComparable<>).MakeGenericType(type).IsAssignableFrom(type))
+ {
+ result = CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericComparer<int>), runtimeType);
+ }
+ // Nullable does not implement IComparable<T?> directly because that would add an extra interface call per comparison.
+ // Instead, it relies on Comparer<T?>.Default to specialize for nullables and do the lifted comparisons if T implements IComparable.
+ else if (type.IsGenericType)
+ {
+ if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
+ {
+ result = TryCreateNullableComparer(runtimeType);
+ }
+ }
+ // The comparer for enums is specialized to avoid boxing.
+ else if (type.IsEnum)
+ {
+ result = TryCreateEnumComparer(runtimeType);
+ }
+
+ return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectComparer<object>), runtimeType);
+ }
+
+ /// <summary>
+ /// Creates the default <see cref="Comparer{T}"/> for a nullable type.
+ /// </summary>
+ /// <param name="nullableType">The nullable type to create the default comparer for.</param>
+ private static object TryCreateNullableComparer(RuntimeType nullableType)
+ {
+ Debug.Assert(nullableType != null);
+ Debug.Assert(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>));
+
+ var embeddedType = (RuntimeType)nullableType.GetGenericArguments()[0];
+
+ if (typeof(IComparable<>).MakeGenericType(embeddedType).IsAssignableFrom(embeddedType))
+ {
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableComparer<int>), embeddedType);
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Creates the default <see cref="Comparer{T}"/> for an enum type.
+ /// </summary>
+ /// <param name="enumType">The enum type to create the default comparer for.</param>
+ private static object TryCreateEnumComparer(RuntimeType enumType)
+ {
+ Debug.Assert(enumType != null);
+ Debug.Assert(enumType.IsEnum);
+
+ // Explicitly call Enum.GetUnderlyingType here. Although GetTypeCode
+ // ends up doing this anyway, we end up avoiding an unnecessary P/Invoke
+ // and virtual method call.
+ TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(enumType));
+
+ // Depending on the enum type, we need to special case the comparers so that we avoid boxing.
+ // Specialize differently for signed/unsigned types so we avoid problems with large numbers.
+ switch (underlyingTypeCode)
+ {
+ case TypeCode.SByte:
+ case TypeCode.Int16:
+ case TypeCode.Int32:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int32EnumComparer<int>), enumType);
+ case TypeCode.Byte:
+ case TypeCode.UInt16:
+ case TypeCode.UInt32:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt32EnumComparer<uint>), enumType);
+ // 64-bit enums: Use `UnsafeEnumCastLong`
+ case TypeCode.Int64:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(Int64EnumComparer<long>), enumType);
+ case TypeCode.UInt64:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(UInt64EnumComparer<ulong>), enumType);
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Creates the default <see cref="EqualityComparer{T}"/>.
+ /// </summary>
+ /// <param name="type">The type to create the default equality comparer for.</param>
+ /// <remarks>
+ /// The logic in this method is replicated in vm/compile.cpp to ensure that NGen saves the right instantiations.
+ /// </remarks>
+ internal static object CreateDefaultEqualityComparer(Type type)
+ {
+ Debug.Assert(type != null && type is RuntimeType);
+
+ object result = null;
+ var runtimeType = (RuntimeType)type;
+
+ // Specialize for byte so Array.IndexOf is faster.
+ if (type == typeof(byte))
+ {
+ result = new ByteEqualityComparer();
+ }
+ // If T implements IEquatable<T> return a GenericEqualityComparer<T>
+ else if (typeof(IEquatable<>).MakeGenericType(type).IsAssignableFrom(type))
+ {
+ result = CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer<int>), runtimeType);
+ }
+ // Nullable does not implement IEquatable<T?> directly because that would add an extra interface call per comparison.
+ // Instead, it relies on EqualityComparer<T?>.Default to specialize for nullables and do the lifted comparisons if T implements IEquatable.
+ else if (type.IsGenericType)
+ {
+ if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
+ {
+ result = TryCreateNullableEqualityComparer(runtimeType);
+ }
+ }
+ // The equality comparer for enums is specialized to avoid boxing.
+ else if (type.IsEnum)
+ {
+ result = TryCreateEnumEqualityComparer(runtimeType);
+ }
+
+ return result ?? CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ObjectEqualityComparer<object>), runtimeType);
+ }
+
+ /// <summary>
+ /// Creates the default <see cref="EqualityComparer{T}"/> for a nullable type.
+ /// </summary>
+ /// <param name="nullableType">The nullable type to create the default equality comparer for.</param>
+ private static object TryCreateNullableEqualityComparer(RuntimeType nullableType)
+ {
+ Debug.Assert(nullableType != null);
+ Debug.Assert(nullableType.IsGenericType && nullableType.GetGenericTypeDefinition() == typeof(Nullable<>));
+
+ var embeddedType = (RuntimeType)nullableType.GetGenericArguments()[0];
+
+ if (typeof(IEquatable<>).MakeGenericType(embeddedType).IsAssignableFrom(embeddedType))
+ {
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer<int>), embeddedType);
+ }
+
+ return null;
+ }
+
+ /// <summary>
+ /// Creates the default <see cref="EqualityComparer{T}"/> for an enum type.
+ /// </summary>
+ /// <param name="enumType">The enum type to create the default equality comparer for.</param>
+ private static object TryCreateEnumEqualityComparer(RuntimeType enumType)
+ {
+ Debug.Assert(enumType != null);
+ Debug.Assert(enumType.IsEnum);
+
+ // See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation
+ // for how we cast the enum types to integral values in the comparer without boxing.
+
+ TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(enumType));
+
+ // Depending on the enum type, we need to special case the comparers so that we avoid boxing.
+ // Note: We have different comparers for short and sbyte, since for those types GetHashCode does not simply return the value.
+ // We need to preserve what they would return.
+ switch (underlyingTypeCode)
+ {
+ case TypeCode.Int16:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ShortEnumEqualityComparer<short>), enumType);
+ case TypeCode.SByte:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(SByteEnumEqualityComparer<sbyte>), enumType);
+ case TypeCode.Int32:
+ case TypeCode.UInt32:
+ case TypeCode.Byte:
+ case TypeCode.UInt16:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<int>), enumType);
+ case TypeCode.Int64:
+ case TypeCode.UInt64:
+ return RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(LongEnumEqualityComparer<long>), enumType);
+ }
+
+ return null;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Collections/Generic/DebugView.cs b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
index 27c5011147..dc487c1411 100644
--- a/src/mscorlib/src/System/Collections/Generic/DebugView.cs
+++ b/src/mscorlib/src/System/Collections/Generic/DebugView.cs
@@ -13,116 +13,112 @@
**
=============================================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Collections.ObjectModel;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Collections.Generic
+{
//
// VS IDE can't differentiate between types with the same name from different
// assembly. So we need to use different names for collection debug view for
// collections in mscorlib.dll and system.dll.
//
- internal sealed class Mscorlib_CollectionDebugView<T> {
- private ICollection<T> collection;
-
- public Mscorlib_CollectionDebugView(ICollection<T> collection) {
+ internal sealed class Mscorlib_CollectionDebugView<T>
+ {
+ private ICollection<T> collection;
+
+ public Mscorlib_CollectionDebugView(ICollection<T> collection)
+ {
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
- this.collection = collection;
+ this.collection = collection;
}
-
+
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public T[] Items {
- get {
+ public T[] Items
+ {
+ get
+ {
T[] items = new T[collection.Count];
collection.CopyTo(items, 0);
return items;
}
}
- }
+ }
- internal sealed class Mscorlib_DictionaryKeyCollectionDebugView<TKey, TValue> {
- private ICollection<TKey> collection;
-
- public Mscorlib_DictionaryKeyCollectionDebugView(ICollection<TKey> collection) {
+ internal sealed class Mscorlib_DictionaryKeyCollectionDebugView<TKey, TValue>
+ {
+ private ICollection<TKey> collection;
+
+ public Mscorlib_DictionaryKeyCollectionDebugView(ICollection<TKey> collection)
+ {
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
- this.collection = collection;
+ this.collection = collection;
}
-
+
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public TKey[] Items {
- get {
+ public TKey[] Items
+ {
+ get
+ {
TKey[] items = new TKey[collection.Count];
collection.CopyTo(items, 0);
return items;
}
}
- }
+ }
- internal sealed class Mscorlib_DictionaryValueCollectionDebugView<TKey, TValue> {
- private ICollection<TValue> collection;
-
- public Mscorlib_DictionaryValueCollectionDebugView(ICollection<TValue> collection) {
+ internal sealed class Mscorlib_DictionaryValueCollectionDebugView<TKey, TValue>
+ {
+ private ICollection<TValue> collection;
+
+ public Mscorlib_DictionaryValueCollectionDebugView(ICollection<TValue> collection)
+ {
if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
- this.collection = collection;
+ this.collection = collection;
}
-
+
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public TValue[] Items {
- get {
+ public TValue[] Items
+ {
+ get
+ {
TValue[] items = new TValue[collection.Count];
collection.CopyTo(items, 0);
return items;
}
}
- }
+ }
+
+ internal sealed class Mscorlib_DictionaryDebugView<K, V>
+ {
+ private IDictionary<K, V> dict;
- internal sealed class Mscorlib_DictionaryDebugView<K, V> {
- private IDictionary<K, V> dict;
-
- public Mscorlib_DictionaryDebugView(IDictionary<K, V> dictionary) {
+ public Mscorlib_DictionaryDebugView(IDictionary<K, V> dictionary)
+ {
if (dictionary == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
- this.dict = dictionary;
+ dict = dictionary;
}
-
+
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public KeyValuePair<K, V>[] Items {
- get {
+ public KeyValuePair<K, V>[] Items
+ {
+ get
+ {
KeyValuePair<K, V>[] items = new KeyValuePair<K, V>[dict.Count];
dict.CopyTo(items, 0);
return items;
}
}
- }
-
- internal sealed class Mscorlib_KeyedCollectionDebugView<K, T> {
- private KeyedCollection<K, T> kc;
-
- public Mscorlib_KeyedCollectionDebugView(KeyedCollection<K, T> keyedCollection) {
- if (keyedCollection == null) {
- throw new ArgumentNullException(nameof(keyedCollection));
- }
- Contract.EndContractBlock();
+ }
- kc = keyedCollection;
- }
-
- [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
- public T[] Items {
- get {
- T[] items = new T[kc.Count];
- kc.CopyTo(items, 0);
- return items;
- }
- }
- }
}
diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
index 7b60e31031..409b23b541 100644
--- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
@@ -41,20 +41,43 @@
** to serialization such that this code doesn't need to build in
** silverlight.
===========================================================*/
-namespace System.Collections.Generic {
+namespace System.Collections.Generic
+{
using System;
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.Serialization;
+ /// <summary>
+ /// Used internally to control behavior of insertion into a <see cref="Dictionary{TKey, TValue}"/>.
+ /// </summary>
+ internal enum InsertionBehavior : byte
+ {
+ /// <summary>
+ /// The default insertion behavior.
+ /// </summary>
+ None = 0,
+
+ /// <summary>
+ /// Specifies that an existing entry with the same key should be overwritten if encountered.
+ /// </summary>
+ OverwriteExisting = 1,
+
+ /// <summary>
+ /// Specifies that if an existing entry with the same key is encountered, an exception should be thrown.
+ /// </summary>
+ ThrowOnExisting = 2
+ }
+
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- public class Dictionary<TKey,TValue>: IDictionary<TKey,TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback {
-
- private struct Entry {
+ public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>, ISerializable, IDeserializationCallback
+ {
+ private struct Entry
+ {
public int hashCode; // Lower 31 bits of hash code, -1 if unused
public int next; // Index of next entry, -1 if last
public TKey key; // Key of entry
@@ -71,38 +94,40 @@ namespace System.Collections.Generic {
private KeyCollection keys;
private ValueCollection values;
private Object _syncRoot;
-
+
// constants for serialization
private const String VersionName = "Version";
private const String HashSizeName = "HashSize"; // Must save buckets.Length
private const String KeyValuePairsName = "KeyValuePairs";
private const String ComparerName = "Comparer";
- public Dictionary(): this(0, null) {}
+ public Dictionary() : this(0, null) { }
- public Dictionary(int capacity): this(capacity, null) {}
+ public Dictionary(int capacity) : this(capacity, null) { }
- public Dictionary(IEqualityComparer<TKey> comparer): this(0, comparer) {}
+ public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { }
- public Dictionary(int capacity, IEqualityComparer<TKey> comparer) {
+ public Dictionary(int capacity, IEqualityComparer<TKey> comparer)
+ {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
#if FEATURE_RANDOMIZED_STRING_HASHING
- if (HashHelpers.s_UseRandomizedStringHashing && comparer == EqualityComparer<string>.Default)
+ if (HashHelpers.s_UseRandomizedStringHashing && this.comparer == EqualityComparer<string>.Default)
{
- this.comparer = (IEqualityComparer<TKey>) NonRandomizedStringEqualityComparer.Default;
+ this.comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
- public Dictionary(IDictionary<TKey,TValue> dictionary): this(dictionary, null) {}
-
- public Dictionary(IDictionary<TKey,TValue> dictionary, IEqualityComparer<TKey> comparer):
- this(dictionary != null? dictionary.Count: 0, comparer) {
+ public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
- if( dictionary == null) {
+ public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) :
+ this(dictionary != null ? dictionary.Count : 0, comparer)
+ {
+ if (dictionary == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
@@ -110,138 +135,174 @@ namespace System.Collections.Generic {
// avoid the enumerator allocation and overhead by looping through the entries array directly.
// We only do this when dictionary is Dictionary<TKey,TValue> and not a subclass, to maintain
// back-compat with subclasses that may have overridden the enumerator behavior.
- if (dictionary.GetType() == typeof(Dictionary<TKey,TValue>)) {
- Dictionary<TKey,TValue> d = (Dictionary<TKey,TValue>)dictionary;
+ if (dictionary.GetType() == typeof(Dictionary<TKey, TValue>))
+ {
+ Dictionary<TKey, TValue> d = (Dictionary<TKey, TValue>)dictionary;
int count = d.count;
Entry[] entries = d.entries;
- for (int i = 0; i < count; i++) {
- if (entries[i].hashCode >= 0) {
+ for (int i = 0; i < count; i++)
+ {
+ if (entries[i].hashCode >= 0)
+ {
Add(entries[i].key, entries[i].value);
}
}
return;
}
- foreach (KeyValuePair<TKey,TValue> pair in dictionary) {
+ foreach (KeyValuePair<TKey, TValue> pair in dictionary)
+ {
Add(pair.Key, pair.Value);
}
}
- public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection):
- this(collection, null) { }
+ public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection) :
+ this(collection, null)
+ { }
- public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer):
+ public Dictionary(IEnumerable<KeyValuePair<TKey, TValue>> collection, IEqualityComparer<TKey> comparer) :
this((collection as ICollection<KeyValuePair<TKey, TValue>>)?.Count ?? 0, comparer)
{
- if (collection == null) {
+ if (collection == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
- foreach (KeyValuePair<TKey, TValue> pair in collection) {
+ foreach (KeyValuePair<TKey, TValue> pair in collection)
+ {
Add(pair.Key, pair.Value);
}
}
- protected Dictionary(SerializationInfo info, StreamingContext context) {
+ protected Dictionary(SerializationInfo info, StreamingContext context)
+ {
//We can't do anything with the keys and values until the entire graph has been deserialized
//and we have a resonable estimate that GetHashCode is not going to fail. For the time being,
//we'll just cache this. The graph is not valid until OnDeserialization has been called.
HashHelpers.SerializationInfoTable.Add(this, info);
}
-
- public IEqualityComparer<TKey> Comparer {
- get {
- return comparer;
- }
+
+ public IEqualityComparer<TKey> Comparer
+ {
+ get
+ {
+ return comparer;
+ }
}
-
- public int Count {
+
+ public int Count
+ {
get { return count - freeCount; }
}
- public KeyCollection Keys {
- get {
+ public KeyCollection Keys
+ {
+ get
+ {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
- ICollection<TKey> IDictionary<TKey, TValue>.Keys {
- get {
- if (keys == null) keys = new KeyCollection(this);
+ ICollection<TKey> IDictionary<TKey, TValue>.Keys
+ {
+ get
+ {
+ if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
- IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys {
- get {
- if (keys == null) keys = new KeyCollection(this);
+ IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
+ {
+ get
+ {
+ if (keys == null) keys = new KeyCollection(this);
return keys;
}
}
- public ValueCollection Values {
- get {
+ public ValueCollection Values
+ {
+ get
+ {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
if (values == null) values = new ValueCollection(this);
return values;
}
}
- ICollection<TValue> IDictionary<TKey, TValue>.Values {
- get {
+ ICollection<TValue> IDictionary<TKey, TValue>.Values
+ {
+ get
+ {
if (values == null) values = new ValueCollection(this);
return values;
}
}
- IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values {
- get {
+ IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
+ {
+ get
+ {
if (values == null) values = new ValueCollection(this);
return values;
}
}
- public TValue this[TKey key] {
- get {
+ public TValue this[TKey key]
+ {
+ get
+ {
int i = FindEntry(key);
if (i >= 0) return entries[i].value;
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
- set {
- Insert(key, value, false);
+ set
+ {
+ bool modified = TryInsert(key, value, InsertionBehavior.OverwriteExisting);
+ Debug.Assert(modified);
}
}
- public void Add(TKey key, TValue value) {
- Insert(key, value, true);
+ public void Add(TKey key, TValue value)
+ {
+ bool modified = TryInsert(key, value, InsertionBehavior.ThrowOnExisting);
+ Debug.Assert(modified); // If there was an existing key and the Add failed, an exception will already have been thrown.
}
- void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) {
+ void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
+ {
Add(keyValuePair.Key, keyValuePair.Value);
}
- bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) {
+ bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
+ {
int i = FindEntry(keyValuePair.Key);
- if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
+ if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
+ {
return true;
}
return false;
}
- bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) {
+ bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
+ {
int i = FindEntry(keyValuePair.Key);
- if( i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) {
+ if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value))
+ {
Remove(keyValuePair.Key);
return true;
}
return false;
}
- public void Clear() {
- if (count > 0) {
+ public void Clear()
+ {
+ if (count > 0)
+ {
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
Array.Clear(entries, 0, count);
freeList = -1;
@@ -251,90 +312,106 @@ namespace System.Collections.Generic {
}
}
- public bool ContainsKey(TKey key) {
+ public bool ContainsKey(TKey key)
+ {
return FindEntry(key) >= 0;
}
- public bool ContainsValue(TValue value) {
- if (value == null) {
- for (int i = 0; i < count; i++) {
+ public bool ContainsValue(TValue value)
+ {
+ if (value == null)
+ {
+ for (int i = 0; i < count; i++)
+ {
if (entries[i].hashCode >= 0 && entries[i].value == null) return true;
}
}
- else {
+ else
+ {
EqualityComparer<TValue> c = EqualityComparer<TValue>.Default;
- for (int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++)
+ {
if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true;
}
}
return false;
}
- private void CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
- if (array == null) {
+ private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
-
- if (index < 0 || index > array.Length ) {
+
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < Count) {
+ if (array.Length - index < Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
int count = this.count;
Entry[] entries = this.entries;
- for (int i = 0; i < count; i++) {
- if (entries[i].hashCode >= 0) {
- array[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
+ for (int i = 0; i < count; i++)
+ {
+ if (entries[i].hashCode >= 0)
+ {
+ array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
- public Enumerator GetEnumerator() {
+ public Enumerator GetEnumerator()
+ {
return new Enumerator(this, Enumerator.KeyValuePair);
}
- IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() {
+ IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
+ {
return new Enumerator(this, Enumerator.KeyValuePair);
- }
+ }
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info);
}
info.AddValue(VersionName, version);
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
- info.AddValue(ComparerName, HashHelpers.GetEqualityComparerForSerialization(comparer), typeof(IEqualityComparer<TKey>));
-#else
info.AddValue(ComparerName, comparer, typeof(IEqualityComparer<TKey>));
-#endif
-
info.AddValue(HashSizeName, buckets == null ? 0 : buckets.Length); //This is the length of the bucket array.
- if( buckets != null) {
+ if (buckets != null)
+ {
KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[Count];
CopyTo(array, 0);
info.AddValue(KeyValuePairsName, array, typeof(KeyValuePair<TKey, TValue>[]));
}
}
- private int FindEntry(TKey key) {
- if( key == null) {
+ private int FindEntry(TKey key)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
- if (buckets != null) {
+ if (buckets != null)
+ {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
- for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
+ for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next)
+ {
if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
}
}
return -1;
}
- private void Initialize(int capacity) {
+ private void Initialize(int capacity)
+ {
int size = HashHelpers.GetPrime(capacity);
buckets = new int[size];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
@@ -342,9 +419,10 @@ namespace System.Collections.Generic {
freeList = -1;
}
- private void Insert(TKey key, TValue value, bool add) {
-
- if( key == null ) {
+ private bool TryInsert(TKey key, TValue value, InsertionBehavior behavior)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
@@ -356,27 +434,38 @@ namespace System.Collections.Generic {
int collisionCount = 0;
#endif
- for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
- if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
- if (add) {
+ for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next)
+ {
+ if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
+ {
+ if (behavior == InsertionBehavior.OverwriteExisting)
+ {
+ entries[i].value = value;
+ version++;
+ return true;
+ }
+
+ if (behavior == InsertionBehavior.ThrowOnExisting)
+ {
ThrowHelper.ThrowAddingDuplicateWithKeyArgumentException(key);
}
- entries[i].value = value;
- version++;
- return;
- }
+
+ return false;
+ }
#if FEATURE_RANDOMIZED_STRING_HASHING
collisionCount++;
#endif
}
int index;
- if (freeCount > 0) {
+ if (freeCount > 0)
+ {
index = freeList;
freeList = entries[index].next;
freeCount--;
}
- else {
+ else
+ {
if (count == entries.Length)
{
Resize();
@@ -399,52 +488,60 @@ namespace System.Collections.Generic {
// Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will
// be using randomized string hashing
- if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
+ if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
{
- comparer = (IEqualityComparer<TKey>) EqualityComparer<string>.Default;
+ comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
#endif
+ return true;
}
- public virtual void OnDeserialization(Object sender) {
+ public virtual void OnDeserialization(Object sender)
+ {
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
-
- if (siInfo==null) {
+
+ if (siInfo == null)
+ {
// It might be necessary to call OnDeserialization from a container if the container object also implements
// OnDeserialization. However, remoting will call OnDeserialization again.
// We can return immediately if this function is called twice.
// Note we set remove the serialization info from the table at the end of this method.
return;
- }
-
+ }
+
int realVersion = siInfo.GetInt32(VersionName);
int hashsize = siInfo.GetInt32(HashSizeName);
- comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
-
- if( hashsize != 0) {
+ comparer = (IEqualityComparer<TKey>)siInfo.GetValue(ComparerName, typeof(IEqualityComparer<TKey>));
+
+ if (hashsize != 0)
+ {
buckets = new int[hashsize];
for (int i = 0; i < buckets.Length; i++) buckets[i] = -1;
entries = new Entry[hashsize];
freeList = -1;
- KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
+ KeyValuePair<TKey, TValue>[] array = (KeyValuePair<TKey, TValue>[])
siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair<TKey, TValue>[]));
- if (array==null) {
+ if (array == null)
+ {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_MissingKeys);
}
- for (int i=0; i<array.Length; i++) {
- if ( array[i].Key == null) {
+ for (int i = 0; i < array.Length; i++)
+ {
+ if (array[i].Key == null)
+ {
ThrowHelper.ThrowSerializationException(ExceptionResource.Serialization_NullKey);
}
- Insert(array[i].Key, array[i].Value, true);
+ Add(array[i].Key, array[i].Value);
}
}
- else {
+ else
+ {
buckets = null;
}
@@ -452,25 +549,32 @@ namespace System.Collections.Generic {
HashHelpers.SerializationInfoTable.Remove(this);
}
- private void Resize() {
+ private void Resize()
+ {
Resize(HashHelpers.ExpandPrime(count), false);
}
- private void Resize(int newSize, bool forceNewHashCodes) {
+ private void Resize(int newSize, bool forceNewHashCodes)
+ {
Debug.Assert(newSize >= entries.Length);
int[] newBuckets = new int[newSize];
for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1;
Entry[] newEntries = new Entry[newSize];
Array.Copy(entries, 0, newEntries, 0, count);
- if(forceNewHashCodes) {
- for (int i = 0; i < count; i++) {
- if(newEntries[i].hashCode != -1) {
+ if (forceNewHashCodes)
+ {
+ for (int i = 0; i < count; i++)
+ {
+ if (newEntries[i].hashCode != -1)
+ {
newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF);
}
}
}
- for (int i = 0; i < count; i++) {
- if (newEntries[i].hashCode >= 0) {
+ for (int i = 0; i < count; i++)
+ {
+ if (newEntries[i].hashCode >= 0)
+ {
int bucket = newEntries[i].hashCode % newSize;
newEntries[i].next = newBuckets[bucket];
newBuckets[bucket] = i;
@@ -480,21 +584,31 @@ namespace System.Collections.Generic {
entries = newEntries;
}
- public bool Remove(TKey key) {
- if(key == null) {
+ // The overload Remove(TKey key, out TValue value) is a copy of this method with one additional
+ // statement to copy the value for entry being removed into the output parameter.
+ // Code has been intentionally duplicated for performance reasons.
+ public bool Remove(TKey key)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
- if (buckets != null) {
+ if (buckets != null)
+ {
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int bucket = hashCode % buckets.Length;
int last = -1;
- for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) {
- if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
- if (last < 0) {
+ for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next)
+ {
+ if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
+ {
+ if (last < 0)
+ {
buckets[bucket] = entries[i].next;
}
- else {
+ else
+ {
entries[last].next = entries[i].next;
}
entries[i].hashCode = -1;
@@ -511,9 +625,56 @@ namespace System.Collections.Generic {
return false;
}
- public bool TryGetValue(TKey key, out TValue value) {
+ // This overload is a copy of the overload Remove(TKey key) with one additional
+ // statement to copy the value for entry being removed into the output parameter.
+ // Code has been intentionally duplicated for performance reasons.
+ public bool Remove(TKey key, out TValue value)
+ {
+ if (key == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ }
+
+ if (buckets != null)
+ {
+ int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
+ int bucket = hashCode % buckets.Length;
+ int last = -1;
+ for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next)
+ {
+ if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
+ {
+ if (last < 0)
+ {
+ buckets[bucket] = entries[i].next;
+ }
+ else
+ {
+ entries[last].next = entries[i].next;
+ }
+
+ value = entries[i].value;
+
+ entries[i].hashCode = -1;
+ entries[i].next = freeList;
+ entries[i].key = default(TKey);
+ entries[i].value = default(TValue);
+ freeList = i;
+ freeCount++;
+ version++;
+ return true;
+ }
+ }
+ }
+ value = default(TValue);
+ return false;
+ }
+
+ public bool TryGetValue(TKey key, out TValue value)
+ {
int i = FindEntry(key);
- if (i >= 0) {
+ if (i >= 0)
+ {
value = entries[i].value;
return true;
}
@@ -536,195 +697,246 @@ namespace System.Collections.Generic {
return defaultValue;
}
- bool ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly {
+ public bool TryAdd(TKey key, TValue value) => TryInsert(key, value, InsertionBehavior.None);
+
+ bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
+ {
get { return false; }
}
- void ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[] array, int index) {
+ void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
+ {
CopyTo(array, index);
}
- void ICollection.CopyTo(Array array, int index) {
- if (array == null) {
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
-
- if (array.Rank != 1) {
+
+ if (array.Rank != 1)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if( array.GetLowerBound(0) != 0 ) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
-
- if (index < 0 || index > array.Length) {
+
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < Count) {
+ if (array.Length - index < Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
-
- KeyValuePair<TKey,TValue>[] pairs = array as KeyValuePair<TKey,TValue>[];
- if (pairs != null) {
+
+ KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
+ if (pairs != null)
+ {
CopyTo(pairs, index);
}
- else if( array is DictionaryEntry[]) {
+ else if (array is DictionaryEntry[])
+ {
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
Entry[] entries = this.entries;
- for (int i = 0; i < count; i++) {
- if (entries[i].hashCode >= 0) {
+ for (int i = 0; i < count; i++)
+ {
+ if (entries[i].hashCode >= 0)
+ {
dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value);
}
- }
+ }
}
- else {
+ else
+ {
object[] objects = array as object[];
- if (objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
- try {
+ try
+ {
int count = this.count;
Entry[] entries = this.entries;
- for (int i = 0; i < count; i++) {
- if (entries[i].hashCode >= 0) {
- objects[index++] = new KeyValuePair<TKey,TValue>(entries[i].key, entries[i].value);
+ for (int i = 0; i < count; i++)
+ {
+ if (entries[i].hashCode >= 0)
+ {
+ objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value);
}
}
}
- catch(ArrayTypeMismatchException) {
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return new Enumerator(this, Enumerator.KeyValuePair);
}
-
- bool ICollection.IsSynchronized {
+
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- object ICollection.SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ object ICollection.SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
- return _syncRoot;
+ return _syncRoot;
}
}
- bool IDictionary.IsFixedSize {
+ bool IDictionary.IsFixedSize
+ {
get { return false; }
}
- bool IDictionary.IsReadOnly {
+ bool IDictionary.IsReadOnly
+ {
get { return false; }
}
- ICollection IDictionary.Keys {
+ ICollection IDictionary.Keys
+ {
get { return (ICollection)Keys; }
}
-
- ICollection IDictionary.Values {
+
+ ICollection IDictionary.Values
+ {
get { return (ICollection)Values; }
}
-
- object IDictionary.this[object key] {
- get {
- if( IsCompatibleKey(key)) {
+
+ object IDictionary.this[object key]
+ {
+ get
+ {
+ if (IsCompatibleKey(key))
+ {
int i = FindEntry((TKey)key);
- if (i >= 0) {
- return entries[i].value;
+ if (i >= 0)
+ {
+ return entries[i].value;
}
}
return null;
}
- set {
+ set
+ {
if (key == null)
{
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
- try {
+ try
+ {
TKey tempKey = (TKey)key;
- try {
- this[tempKey] = (TValue)value;
+ try
+ {
+ this[tempKey] = (TValue)value;
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
- catch (InvalidCastException) {
+ catch (InvalidCastException)
+ {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
}
- private static bool IsCompatibleKey(object key) {
- if( key == null) {
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- }
- return (key is TKey);
+ private static bool IsCompatibleKey(object key)
+ {
+ if (key == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ }
+ return (key is TKey);
}
-
- void IDictionary.Add(object key, object value) {
+
+ void IDictionary.Add(object key, object value)
+ {
if (key == null)
{
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value);
- try {
+ try
+ {
TKey tempKey = (TKey)key;
- try {
+ try
+ {
Add(tempKey, (TValue)value);
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue));
}
}
- catch (InvalidCastException) {
+ catch (InvalidCastException)
+ {
ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey));
}
}
-
- bool IDictionary.Contains(object key) {
- if(IsCompatibleKey(key)) {
+
+ bool IDictionary.Contains(object key)
+ {
+ if (IsCompatibleKey(key))
+ {
return ContainsKey((TKey)key);
}
-
+
return false;
}
-
- IDictionaryEnumerator IDictionary.GetEnumerator() {
+
+ IDictionaryEnumerator IDictionary.GetEnumerator()
+ {
return new Enumerator(this, Enumerator.DictEntry);
}
-
- void IDictionary.Remove(object key) {
- if(IsCompatibleKey(key)) {
+
+ void IDictionary.Remove(object key)
+ {
+ if (IsCompatibleKey(key))
+ {
Remove((TKey)key);
}
}
[Serializable]
- public struct Enumerator: IEnumerator<KeyValuePair<TKey,TValue>>,
+ public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>,
IDictionaryEnumerator
{
- private Dictionary<TKey,TValue> dictionary;
+ private Dictionary<TKey, TValue> dictionary;
private int version;
private int index;
- private KeyValuePair<TKey,TValue> current;
+ private KeyValuePair<TKey, TValue> current;
private int getEnumeratorRetType; // What should Enumerator.Current return?
-
+
internal const int DictEntry = 1;
internal const int KeyValuePair = 2;
- internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) {
+ internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
+ {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
@@ -732,15 +944,19 @@ namespace System.Collections.Generic {
current = new KeyValuePair<TKey, TValue>();
}
- public bool MoveNext() {
- if (version != dictionary.version) {
+ public bool MoveNext()
+ {
+ if (version != dictionary.version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
// Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends.
// dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue
- while ((uint)index < (uint)dictionary.count) {
- if (dictionary.entries[index].hashCode >= 0) {
+ while ((uint)index < (uint)dictionary.count)
+ {
+ if (dictionary.entries[index].hashCode >= 0)
+ {
current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value);
index++;
return true;
@@ -753,187 +969,236 @@ namespace System.Collections.Generic {
return false;
}
- public KeyValuePair<TKey,TValue> Current {
+ public KeyValuePair<TKey, TValue> Current
+ {
get { return current; }
}
- public void Dispose() {
+ public void Dispose()
+ {
}
- object IEnumerator.Current {
- get {
- if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
- }
+ object IEnumerator.Current
+ {
+ get
+ {
+ if (index == 0 || (index == dictionary.count + 1))
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
- if (getEnumeratorRetType == DictEntry) {
+ if (getEnumeratorRetType == DictEntry)
+ {
return new System.Collections.DictionaryEntry(current.Key, current.Value);
- } else {
+ }
+ else
+ {
return new KeyValuePair<TKey, TValue>(current.Key, current.Value);
}
}
}
- void IEnumerator.Reset() {
- if (version != dictionary.version) {
+ void IEnumerator.Reset()
+ {
+ if (version != dictionary.version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = 0;
- current = new KeyValuePair<TKey, TValue>();
+ current = new KeyValuePair<TKey, TValue>();
}
- DictionaryEntry IDictionaryEnumerator.Entry {
- get {
- if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
- }
-
- return new DictionaryEntry(current.Key, current.Value);
+ DictionaryEntry IDictionaryEnumerator.Entry
+ {
+ get
+ {
+ if (index == 0 || (index == dictionary.count + 1))
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
+
+ return new DictionaryEntry(current.Key, current.Value);
}
}
- object IDictionaryEnumerator.Key {
- get {
- if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
- }
-
- return current.Key;
+ object IDictionaryEnumerator.Key
+ {
+ get
+ {
+ if (index == 0 || (index == dictionary.count + 1))
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
+
+ return current.Key;
}
}
- object IDictionaryEnumerator.Value {
- get {
- if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
- }
-
- return current.Value;
+ object IDictionaryEnumerator.Value
+ {
+ get
+ {
+ if (index == 0 || (index == dictionary.count + 1))
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
+
+ return current.Value;
}
}
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryKeyCollectionDebugView<,>))]
- [DebuggerDisplay("Count = {Count}")]
+ [DebuggerDisplay("Count = {Count}")]
[Serializable]
- public sealed class KeyCollection: ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
+ public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
- private Dictionary<TKey,TValue> dictionary;
+ private Dictionary<TKey, TValue> dictionary;
- public KeyCollection(Dictionary<TKey,TValue> dictionary) {
- if (dictionary == null) {
+ public KeyCollection(Dictionary<TKey, TValue> dictionary)
+ {
+ if (dictionary == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
- public Enumerator GetEnumerator() {
+ public Enumerator GetEnumerator()
+ {
return new Enumerator(dictionary);
}
- public void CopyTo(TKey[] array, int index) {
- if (array == null) {
+ public void CopyTo(TKey[] array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (index < 0 || index > array.Length) {
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < dictionary.Count) {
+ if (array.Length - index < dictionary.Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
-
+
int count = dictionary.count;
Entry[] entries = dictionary.entries;
- for (int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++)
+ {
if (entries[i].hashCode >= 0) array[index++] = entries[i].key;
}
}
- public int Count {
+ public int Count
+ {
get { return dictionary.Count; }
}
- bool ICollection<TKey>.IsReadOnly {
+ bool ICollection<TKey>.IsReadOnly
+ {
get { return true; }
}
- void ICollection<TKey>.Add(TKey item){
+ void ICollection<TKey>.Add(TKey item)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
-
- void ICollection<TKey>.Clear(){
+
+ void ICollection<TKey>.Clear()
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
}
- bool ICollection<TKey>.Contains(TKey item){
+ bool ICollection<TKey>.Contains(TKey item)
+ {
return dictionary.ContainsKey(item);
}
- bool ICollection<TKey>.Remove(TKey item){
+ bool ICollection<TKey>.Remove(TKey item)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet);
return false;
}
-
- IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() {
+
+ IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
+ {
return new Enumerator(dictionary);
}
- IEnumerator IEnumerable.GetEnumerator() {
- return new Enumerator(dictionary);
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return new Enumerator(dictionary);
}
- void ICollection.CopyTo(Array array, int index) {
- if (array==null) {
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (array.Rank != 1) {
+ if (array.Rank != 1)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if( array.GetLowerBound(0) != 0 ) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
- if (index < 0 || index > array.Length) {
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < dictionary.Count) {
+ if (array.Length - index < dictionary.Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
-
+
TKey[] keys = array as TKey[];
- if (keys != null) {
+ if (keys != null)
+ {
CopyTo(keys, index);
}
- else {
+ else
+ {
object[] objects = array as object[];
- if (objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
-
+
int count = dictionary.count;
Entry[] entries = dictionary.entries;
- try {
- for (int i = 0; i < count; i++) {
+ try
+ {
+ for (int i = 0; i < count; i++)
+ {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].key;
}
- }
- catch(ArrayTypeMismatchException) {
+ }
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- Object ICollection.SyncRoot {
+ Object ICollection.SyncRoot
+ {
get { return ((ICollection)dictionary).SyncRoot; }
}
@@ -944,24 +1209,30 @@ namespace System.Collections.Generic {
private int index;
private int version;
private TKey currentKey;
-
- internal Enumerator(Dictionary<TKey, TValue> dictionary) {
+
+ internal Enumerator(Dictionary<TKey, TValue> dictionary)
+ {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
- currentKey = default(TKey);
+ currentKey = default(TKey);
}
- public void Dispose() {
+ public void Dispose()
+ {
}
- public bool MoveNext() {
- if (version != dictionary.version) {
+ public bool MoveNext()
+ {
+ if (version != dictionary.version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
- while ((uint)index < (uint)dictionary.count) {
- if (dictionary.entries[index].hashCode >= 0) {
+ while ((uint)index < (uint)dictionary.count)
+ {
+ if (dictionary.entries[index].hashCode >= 0)
+ {
currentKey = dictionary.entries[index].key;
index++;
return true;
@@ -973,153 +1244,189 @@ namespace System.Collections.Generic {
currentKey = default(TKey);
return false;
}
-
- public TKey Current {
- get {
+
+ public TKey Current
+ {
+ get
+ {
return currentKey;
}
}
- Object System.Collections.IEnumerator.Current {
- get {
- if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
- }
-
+ Object System.Collections.IEnumerator.Current
+ {
+ get
+ {
+ if (index == 0 || (index == dictionary.count + 1))
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
+
return currentKey;
}
}
-
- void System.Collections.IEnumerator.Reset() {
- if (version != dictionary.version) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
+
+ void System.Collections.IEnumerator.Reset()
+ {
+ if (version != dictionary.version)
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
- index = 0;
+ index = 0;
currentKey = default(TKey);
}
- }
+ }
}
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- public sealed class ValueCollection: ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
+ public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
- private Dictionary<TKey,TValue> dictionary;
+ private Dictionary<TKey, TValue> dictionary;
- public ValueCollection(Dictionary<TKey,TValue> dictionary) {
- if (dictionary == null) {
+ public ValueCollection(Dictionary<TKey, TValue> dictionary)
+ {
+ if (dictionary == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
}
this.dictionary = dictionary;
}
- public Enumerator GetEnumerator() {
- return new Enumerator(dictionary);
+ public Enumerator GetEnumerator()
+ {
+ return new Enumerator(dictionary);
}
- public void CopyTo(TValue[] array, int index) {
- if (array == null) {
+ public void CopyTo(TValue[] array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (index < 0 || index > array.Length) {
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < dictionary.Count) {
+ if (array.Length - index < dictionary.Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
-
+
int count = dictionary.count;
Entry[] entries = dictionary.entries;
- for (int i = 0; i < count; i++) {
+ for (int i = 0; i < count; i++)
+ {
if (entries[i].hashCode >= 0) array[index++] = entries[i].value;
}
}
- public int Count {
+ public int Count
+ {
get { return dictionary.Count; }
}
- bool ICollection<TValue>.IsReadOnly {
+ bool ICollection<TValue>.IsReadOnly
+ {
get { return true; }
}
- void ICollection<TValue>.Add(TValue item){
+ void ICollection<TValue>.Add(TValue item)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
- bool ICollection<TValue>.Remove(TValue item){
+ bool ICollection<TValue>.Remove(TValue item)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
return false;
}
- void ICollection<TValue>.Clear(){
+ void ICollection<TValue>.Clear()
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet);
}
- bool ICollection<TValue>.Contains(TValue item){
+ bool ICollection<TValue>.Contains(TValue item)
+ {
return dictionary.ContainsValue(item);
}
- IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() {
+ IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
+ {
return new Enumerator(dictionary);
}
- IEnumerator IEnumerable.GetEnumerator() {
- return new Enumerator(dictionary);
+ IEnumerator IEnumerable.GetEnumerator()
+ {
+ return new Enumerator(dictionary);
}
- void ICollection.CopyTo(Array array, int index) {
- if (array == null) {
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (array.Rank != 1) {
+ if (array.Rank != 1)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if( array.GetLowerBound(0) != 0 ) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
- if (index < 0 || index > array.Length) {
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
if (array.Length - index < dictionary.Count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
-
+
TValue[] values = array as TValue[];
- if (values != null) {
+ if (values != null)
+ {
CopyTo(values, index);
}
- else {
+ else
+ {
object[] objects = array as object[];
- if (objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = dictionary.count;
Entry[] entries = dictionary.entries;
- try {
- for (int i = 0; i < count; i++) {
+ try
+ {
+ for (int i = 0; i < count; i++)
+ {
if (entries[i].hashCode >= 0) objects[index++] = entries[i].value;
}
}
- catch(ArrayTypeMismatchException) {
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- Object ICollection.SyncRoot {
+ Object ICollection.SyncRoot
+ {
get { return ((ICollection)dictionary).SyncRoot; }
}
@@ -1130,24 +1437,30 @@ namespace System.Collections.Generic {
private int index;
private int version;
private TValue currentValue;
-
- internal Enumerator(Dictionary<TKey, TValue> dictionary) {
+
+ internal Enumerator(Dictionary<TKey, TValue> dictionary)
+ {
this.dictionary = dictionary;
version = dictionary.version;
index = 0;
currentValue = default(TValue);
}
- public void Dispose() {
+ public void Dispose()
+ {
}
- public bool MoveNext() {
- if (version != dictionary.version) {
+ public bool MoveNext()
+ {
+ if (version != dictionary.version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
-
- while ((uint)index < (uint)dictionary.count) {
- if (dictionary.entries[index].hashCode >= 0) {
+
+ while ((uint)index < (uint)dictionary.count)
+ {
+ if (dictionary.entries[index].hashCode >= 0)
+ {
currentValue = dictionary.entries[index].value;
index++;
return true;
@@ -1158,28 +1471,35 @@ namespace System.Collections.Generic {
currentValue = default(TValue);
return false;
}
-
- public TValue Current {
- get {
+
+ public TValue Current
+ {
+ get
+ {
return currentValue;
}
}
- Object System.Collections.IEnumerator.Current {
- get {
- if( index == 0 || (index == dictionary.count + 1)) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
- }
-
+ Object System.Collections.IEnumerator.Current
+ {
+ get
+ {
+ if (index == 0 || (index == dictionary.count + 1))
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ }
+
return currentValue;
}
}
-
- void System.Collections.IEnumerator.Reset() {
- if (version != dictionary.version) {
+
+ void System.Collections.IEnumerator.Reset()
+ {
+ if (version != dictionary.version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
- index = 0;
+ index = 0;
currentValue = default(TValue);
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
index 0f9259d2f3..0cd1bc1c12 100644
--- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
@@ -7,117 +7,56 @@ using System.Collections;
using System.Collections.Generic;
using System.Security;
+using System.Globalization;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
namespace System.Collections.Generic
{
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
-
[Serializable]
[TypeDependencyAttribute("System.Collections.Generic.ObjectEqualityComparer`1")]
public abstract class EqualityComparer<T> : IEqualityComparer, IEqualityComparer<T>
{
- static readonly EqualityComparer<T> defaultComparer = CreateComparer();
-
- public static EqualityComparer<T> Default {
- get {
- Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
- return defaultComparer;
- }
- }
-
- //
- // Note that logic in this method is replicated in vm\compile.cpp to ensure that NGen
- // saves the right instantiations
- //
- private static EqualityComparer<T> CreateComparer()
- {
- Contract.Ensures(Contract.Result<EqualityComparer<T>>() != null);
-
- object result = null;
- RuntimeType t = (RuntimeType)typeof(T);
-
- // Specialize type byte for performance reasons
- if (t == typeof(byte)) {
- result = new ByteEqualityComparer();
- }
- // If T implements IEquatable<T> return a GenericEqualityComparer<T>
- else if (typeof(IEquatable<T>).IsAssignableFrom(t))
- {
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(GenericEqualityComparer<int>), t);
- }
- else if (default(T) == null) // Reference type/Nullable
- {
- // If T is a Nullable<U> where U implements IEquatable<U> return a NullableEqualityComparer<U>
- if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) {
- RuntimeType u = (RuntimeType)t.GetGenericArguments()[0];
- if (typeof(IEquatable<>).MakeGenericType(u).IsAssignableFrom(u)) {
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(NullableEqualityComparer<int>), u);
- }
- }
- }
- // See the METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST and METHOD__JIT_HELPERS__UNSAFE_ENUM_CAST_LONG cases in getILIntrinsicImplementation
- else if (t.IsEnum) {
- TypeCode underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t));
-
- // Depending on the enum type, we need to special case the comparers so that we avoid boxing
- // Note: We have different comparers for Short and SByte because for those types we need to make sure we call GetHashCode on the actual underlying type as the
- // implementation of GetHashCode is more complex than for the other types.
- switch (underlyingTypeCode) {
- case TypeCode.Int16: // short
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(ShortEnumEqualityComparer<short>), t);
- break;
- case TypeCode.SByte:
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(SByteEnumEqualityComparer<sbyte>), t);
- break;
- case TypeCode.Int32:
- case TypeCode.UInt32:
- case TypeCode.Byte:
- case TypeCode.UInt16: //ushort
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(EnumEqualityComparer<int>), t);
- break;
- case TypeCode.Int64:
- case TypeCode.UInt64:
- result = RuntimeTypeHandle.CreateInstanceForAnotherGenericParameter((RuntimeType)typeof(LongEnumEqualityComparer<long>), t);
- break;
- }
- }
-
- return result != null ?
- (EqualityComparer<T>)result :
- new ObjectEqualityComparer<T>(); // Fallback to ObjectEqualityComparer, which uses boxing
- }
+ // To minimize generic instantiation overhead of creating the comparer per type, we keep the generic portion of the code as small
+ // as possible and define most of the creation logic in a non-generic class.
+ public static EqualityComparer<T> Default { get; } = (EqualityComparer<T>)ComparerHelpers.CreateDefaultEqualityComparer(typeof(T));
[Pure]
public abstract bool Equals(T x, T y);
[Pure]
public abstract int GetHashCode(T obj);
- internal virtual int IndexOf(T[] array, T value, int startIndex, int count) {
+ internal virtual int IndexOf(T[] array, T value, int startIndex, int count)
+ {
int endIndex = startIndex + count;
- for (int i = startIndex; i < endIndex; i++) {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (Equals(array[i], value)) return i;
}
return -1;
}
- internal virtual int LastIndexOf(T[] array, T value, int startIndex, int count) {
+ internal virtual int LastIndexOf(T[] array, T value, int startIndex, int count)
+ {
int endIndex = startIndex - count + 1;
- for (int i = startIndex; i >= endIndex; i--) {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (Equals(array[i], value)) return i;
}
return -1;
}
- int IEqualityComparer.GetHashCode(object obj) {
+ int IEqualityComparer.GetHashCode(object obj)
+ {
if (obj == null) return 0;
if (obj is T) return GetHashCode((T)obj);
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
- return 0;
- }
+ return 0;
+ }
- bool IEqualityComparer.Equals(object x, object y) {
+ bool IEqualityComparer.Equals(object x, object y)
+ {
if (x == y) return true;
if (x == null || y == null) return false;
if ((x is T) && (y is T)) return Equals((T)x, (T)y);
@@ -129,11 +68,13 @@ namespace System.Collections.Generic
// The methods in this class look identical to the inherited methods, but the calls
// to Equal bind to IEquatable<T>.Equals(T) instead of Object.Equals(Object)
[Serializable]
- internal class GenericEqualityComparer<T>: EqualityComparer<T> where T: IEquatable<T>
+ internal class GenericEqualityComparer<T> : EqualityComparer<T> where T : IEquatable<T>
{
[Pure]
- public override bool Equals(T x, T y) {
- if (x != null) {
+ public override bool Equals(T x, T y)
+ {
+ if (x != null)
+ {
if (y != null) return x.Equals(y);
return false;
}
@@ -144,30 +85,40 @@ namespace System.Collections.Generic
[Pure]
public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
- internal override int IndexOf(T[] array, T value, int startIndex, int count) {
+ internal override int IndexOf(T[] array, T value, int startIndex, int count)
+ {
int endIndex = startIndex + count;
- if (value == null) {
- for (int i = startIndex; i < endIndex; i++) {
+ if (value == null)
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (array[i] == null) return i;
}
}
- else {
- for (int i = startIndex; i < endIndex; i++) {
+ else
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
- internal override int LastIndexOf(T[] array, T value, int startIndex, int count) {
+ internal override int LastIndexOf(T[] array, T value, int startIndex, int count)
+ {
int endIndex = startIndex - count + 1;
- if (value == null) {
- for (int i = startIndex; i >= endIndex; i--) {
+ if (value == null)
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (array[i] == null) return i;
}
}
- else {
- for (int i = startIndex; i >= endIndex; i--) {
+ else
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
@@ -188,8 +139,10 @@ namespace System.Collections.Generic
internal sealed class NullableEqualityComparer<T> : EqualityComparer<T?> where T : struct, IEquatable<T>
{
[Pure]
- public override bool Equals(T? x, T? y) {
- if (x.HasValue) {
+ public override bool Equals(T? x, T? y)
+ {
+ if (x.HasValue)
+ {
if (y.HasValue) return x.value.Equals(y.value);
return false;
}
@@ -200,30 +153,40 @@ namespace System.Collections.Generic
[Pure]
public override int GetHashCode(T? obj) => obj.GetHashCode();
- internal override int IndexOf(T?[] array, T? value, int startIndex, int count) {
+ internal override int IndexOf(T?[] array, T? value, int startIndex, int count)
+ {
int endIndex = startIndex + count;
- if (!value.HasValue) {
- for (int i = startIndex; i < endIndex; i++) {
+ if (!value.HasValue)
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (!array[i].HasValue) return i;
}
}
- else {
- for (int i = startIndex; i < endIndex; i++) {
+ else
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (array[i].HasValue && array[i].value.Equals(value.value)) return i;
}
}
return -1;
}
- internal override int LastIndexOf(T?[] array, T? value, int startIndex, int count) {
+ internal override int LastIndexOf(T?[] array, T? value, int startIndex, int count)
+ {
int endIndex = startIndex - count + 1;
- if (!value.HasValue) {
- for (int i = startIndex; i >= endIndex; i--) {
+ if (!value.HasValue)
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (!array[i].HasValue) return i;
}
}
- else {
- for (int i = startIndex; i >= endIndex; i--) {
+ else
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (array[i].HasValue && array[i].value.Equals(value.value)) return i;
}
}
@@ -239,11 +202,13 @@ namespace System.Collections.Generic
}
[Serializable]
- internal sealed class ObjectEqualityComparer<T>: EqualityComparer<T>
+ internal sealed class ObjectEqualityComparer<T> : EqualityComparer<T>
{
[Pure]
- public override bool Equals(T x, T y) {
- if (x != null) {
+ public override bool Equals(T x, T y)
+ {
+ if (x != null)
+ {
if (y != null) return x.Equals(y);
return false;
}
@@ -254,30 +219,40 @@ namespace System.Collections.Generic
[Pure]
public override int GetHashCode(T obj) => obj?.GetHashCode() ?? 0;
- internal override int IndexOf(T[] array, T value, int startIndex, int count) {
+ internal override int IndexOf(T[] array, T value, int startIndex, int count)
+ {
int endIndex = startIndex + count;
- if (value == null) {
- for (int i = startIndex; i < endIndex; i++) {
+ if (value == null)
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (array[i] == null) return i;
}
}
- else {
- for (int i = startIndex; i < endIndex; i++) {
+ else
+ {
+ for (int i = startIndex; i < endIndex; i++)
+ {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
return -1;
}
- internal override int LastIndexOf(T[] array, T value, int startIndex, int count) {
+ internal override int LastIndexOf(T[] array, T value, int startIndex, int count)
+ {
int endIndex = startIndex - count + 1;
- if (value == null) {
- for (int i = startIndex; i >= endIndex; i--) {
+ if (value == null)
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (array[i] == null) return i;
}
}
- else {
- for (int i = startIndex; i >= endIndex; i--) {
+ else
+ {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (array[i] != null && array[i].Equals(value)) return i;
}
}
@@ -299,20 +274,25 @@ namespace System.Collections.Generic
// keep the perofrmance not affected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing GenericEqualityComparer<string>
[Serializable]
- internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer<string> {
- static IEqualityComparer<string> s_nonRandomizedComparer;
-
- internal static new IEqualityComparer<string> Default {
- get {
- if (s_nonRandomizedComparer == null) {
- s_nonRandomizedComparer = new NonRandomizedStringEqualityComparer();
- }
- return s_nonRandomizedComparer;
+ internal class NonRandomizedStringEqualityComparer : GenericEqualityComparer<string>
+ {
+ private static IEqualityComparer<string> s_nonRandomizedComparer;
+
+ internal static new IEqualityComparer<string> Default
+ {
+ get
+ {
+ if (s_nonRandomizedComparer == null)
+ {
+ s_nonRandomizedComparer = new NonRandomizedStringEqualityComparer();
+ }
+ return s_nonRandomizedComparer;
}
}
[Pure]
- public override int GetHashCode(string obj) {
+ public override int GetHashCode(string obj)
+ {
if (obj == null) return 0;
return obj.GetLegacyNonRandomizedHashCode();
}
@@ -321,37 +301,43 @@ namespace System.Collections.Generic
// Performance of IndexOf on byte array is very important for some scenarios.
// We will call the C runtime function memchr, which is optimized.
[Serializable]
- internal sealed class ByteEqualityComparer: EqualityComparer<byte>
+ internal sealed class ByteEqualityComparer : EqualityComparer<byte>
{
[Pure]
- public override bool Equals(byte x, byte y) {
+ public override bool Equals(byte x, byte y)
+ {
return x == y;
}
[Pure]
- public override int GetHashCode(byte b) {
+ public override int GetHashCode(byte b)
+ {
return b.GetHashCode();
}
- internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count) {
- if (array==null)
+ internal unsafe override int IndexOf(byte[] array, byte value, int startIndex, int count)
+ {
+ if (array == null)
throw new ArgumentNullException(nameof(array));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (count > array.Length - startIndex)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (count == 0) return -1;
- fixed (byte* pbytes = array) {
+ fixed (byte* pbytes = array)
+ {
return Buffer.IndexOfByte(pbytes, value, startIndex, count);
}
}
- internal override int LastIndexOf(byte[] array, byte value, int startIndex, int count) {
+ internal override int LastIndexOf(byte[] array, byte value, int startIndex, int count)
+ {
int endIndex = startIndex - count + 1;
- for (int i = startIndex; i >= endIndex; i--) {
+ for (int i = startIndex; i >= endIndex; i--)
+ {
if (array[i] == value) return i;
}
return -1;
@@ -362,21 +348,23 @@ namespace System.Collections.Generic
obj != null && GetType() == obj.GetType();
public override int GetHashCode() =>
- GetType().GetHashCode();
+ GetType().GetHashCode();
}
[Serializable]
internal class EnumEqualityComparer<T> : EqualityComparer<T> where T : struct
{
[Pure]
- public override bool Equals(T x, T y) {
+ public override bool Equals(T x, T y)
+ {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(x);
int y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(y);
return x_final == y_final;
}
[Pure]
- public override int GetHashCode(T obj) {
+ public override int GetHashCode(T obj)
+ {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return x_final.GetHashCode();
}
@@ -421,7 +409,8 @@ namespace System.Collections.Generic
public SByteEnumEqualityComparer() { }
[Pure]
- public override int GetHashCode(T obj) {
+ public override int GetHashCode(T obj)
+ {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return ((sbyte)x_final).GetHashCode();
}
@@ -433,7 +422,8 @@ namespace System.Collections.Generic
public ShortEnumEqualityComparer() { }
[Pure]
- public override int GetHashCode(T obj) {
+ public override int GetHashCode(T obj)
+ {
int x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCast(obj);
return ((short)x_final).GetHashCode();
}
@@ -443,14 +433,16 @@ namespace System.Collections.Generic
internal sealed class LongEnumEqualityComparer<T> : EqualityComparer<T> where T : struct
{
[Pure]
- public override bool Equals(T x, T y) {
+ public override bool Equals(T x, T y)
+ {
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(x);
long y_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(y);
return x_final == y_final;
}
[Pure]
- public override int GetHashCode(T obj) {
+ public override int GetHashCode(T obj)
+ {
long x_final = System.Runtime.CompilerServices.JitHelpers.UnsafeEnumCastLong(obj);
return x_final.GetHashCode();
}
diff --git a/src/mscorlib/src/System/Collections/Generic/ICollection.cs b/src/mscorlib/src/System/Collections/Generic/ICollection.cs
deleted file mode 100644
index 741e8cc79b..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/ICollection.cs
+++ /dev/null
@@ -1,52 +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.
-
-/*============================================================
-**
-** Interface: ICollection
-**
-**
-**
-**
-** Purpose: Base interface for all generic collections.
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
-
- // Base interface for all collections, defining enumerators, size, and
- // synchronization methods.
-
- // Note that T[] : IList<T>, and we want to ensure that if you use
- // IList<YourValueType>, we ensure a YourValueType[] can be used
- // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper.
- // This is a special workaround internally though - see VM\compile.cpp.
- // The same attribute is on IEnumerable<T> and ICollection<T>.
- [TypeDependencyAttribute("System.SZArrayHelper")]
- public interface ICollection<T> : IEnumerable<T>
- {
- // Number of items in the collections.
- int Count { get; }
-
- bool IsReadOnly { get; }
-
- void Add(T item);
-
- void Clear();
-
- bool Contains(T item);
-
- // CopyTo copies a collection into an Array, starting at a particular
- // index into the array.
- //
- void CopyTo(T[] array, int arrayIndex);
-
- //void CopyTo(int sourceIndex, T[] destinationArray, int destinationIndex, int count);
-
- bool Remove(T item);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IComparer.cs b/src/mscorlib/src/System/Collections/Generic/IComparer.cs
deleted file mode 100644
index 7b9e97ff0e..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IComparer.cs
+++ /dev/null
@@ -1,30 +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.
-
-/*============================================================
-**
-** Interface: IComparer
-**
-**
-**
-**
-** Purpose: Interface for comparing two generic Objects.
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
-
- using System;
- // The generic IComparer interface implements a method that compares
- // two objects. It is used in conjunction with the Sort and
- // BinarySearch methods on the Array, List, and SortedList classes.
- public interface IComparer<in T>
- {
- // Compares two objects. An implementation of this method must return a
- // value less than zero if x is less than y, zero if x is equal to y, or a
- // value greater than zero if x is greater than y.
- //
- int Compare(T x, T y);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IDictionary.cs b/src/mscorlib/src/System/Collections/Generic/IDictionary.cs
deleted file mode 100644
index 2a2da944d3..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IDictionary.cs
+++ /dev/null
@@ -1,58 +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.
-
-/*============================================================
-**
-** Interface: IDictionary
-**
-**
-**
-**
-** Purpose: Base interface for all generic dictionaries.
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Diagnostics.Contracts;
-
- // An IDictionary is a possibly unordered set of key-value pairs.
- // Keys can be any non-null object. Values can be any object.
- // You can look up a value in an IDictionary via the default indexed
- // property, Items.
- public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>
- {
- // Interfaces are not serializable
- // The Item property provides methods to read and edit entries
- // in the Dictionary.
- TValue this[TKey key] {
- get;
- set;
- }
-
- // Returns a collections of the keys in this dictionary.
- ICollection<TKey> Keys {
- get;
- }
-
- // Returns a collections of the values in this dictionary.
- ICollection<TValue> Values {
- get;
- }
-
- // Returns whether this dictionary contains a particular key.
- //
- bool ContainsKey(TKey key);
-
- // Adds a key-value pair to the dictionary.
- //
- void Add(TKey key, TValue value);
-
- // Removes a particular key from the dictionary.
- //
- bool Remove(TKey key);
-
- bool TryGetValue(TKey key, out TValue value);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs b/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs
deleted file mode 100644
index 67f35ce675..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IEnumerable.cs
+++ /dev/null
@@ -1,38 +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.
-
-/*============================================================
-**
-** Interface: IEnumerable
-**
-**
-**
-**
-** Purpose: Interface for providing generic IEnumerators
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Collections;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
-
- // Implement this interface if you need to support foreach semantics.
-
- // Note that T[] : IList<T>, and we want to ensure that if you use
- // IList<YourValueType>, we ensure a YourValueType[] can be used
- // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper.
- // This is a special workaround internally though - see VM\compile.cpp.
- // The same attribute is on IList<T> and ICollection<T>.
- [TypeDependencyAttribute("System.SZArrayHelper")]
- public interface IEnumerable<out T> : IEnumerable
- {
- // Returns an IEnumerator for this enumerable Object. The enumerator provides
- // a simple way to access all the contents of a collection.
- /// <include file='doc\IEnumerable.uex' path='docs/doc[@for="IEnumerable.GetEnumerator"]/*' />
- new IEnumerator<T> GetEnumerator();
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IEnumerator.cs b/src/mscorlib/src/System/Collections/Generic/IEnumerator.cs
deleted file mode 100644
index 335616757b..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IEnumerator.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.
-
-/*============================================================
-**
-** Interface: IEnumerator
-**
-**
-**
-**
-** Purpose: Base interface for all generic enumerators.
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Runtime.InteropServices;
-
- // Base interface for all generic enumerators, providing a simple approach
- // to iterating over a collection.
- public interface IEnumerator<out T> : IDisposable, IEnumerator
- {
- // Returns the current element of the enumeration. The returned value is
- // undefined before the first call to MoveNext and following a
- // call to MoveNext that returned false. Multiple calls to
- // GetCurrent with no intervening calls to MoveNext
- // will return the same object.
- //
- /// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator.Current"]/*' />
- new T Current {
- get;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs
deleted file mode 100644
index b6ac3be006..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IEqualityComparer.cs
+++ /dev/null
@@ -1,19 +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.
-
-//
-
-namespace System.Collections.Generic {
- using System;
-
- // The generic IEqualityComparer interface implements methods to if check two objects are equal
- // and generate Hashcode for an object.
- // It is use in Dictionary class.
- public interface IEqualityComparer<in T>
- {
- bool Equals(T x, T y);
- int GetHashCode(T obj);
- }
-}
-
diff --git a/src/mscorlib/src/System/Collections/Generic/IList.cs b/src/mscorlib/src/System/Collections/Generic/IList.cs
deleted file mode 100644
index 75ca0a9b00..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IList.cs
+++ /dev/null
@@ -1,54 +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.
-
-/*============================================================
-**
-** Interface: IList
-**
-**
-**
-**
-** Purpose: Base interface for all generic lists.
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
-
- using System;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.Contracts;
-
- // An IList is an ordered collection of objects. The exact ordering
- // is up to the implementation of the list, ranging from a sorted
- // order to insertion order.
-
- // Note that T[] : IList<T>, and we want to ensure that if you use
- // IList<YourValueType>, we ensure a YourValueType[] can be used
- // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper.
- // This is a special workaround internally though - see VM\compile.cpp.
- // The same attribute is on IEnumerable<T> and ICollection<T>.
- [TypeDependencyAttribute("System.SZArrayHelper")]
- public interface IList<T> : ICollection<T>
- {
- // The Item property provides methods to read and edit entries in the List.
- T this[int index] {
- get;
- set;
- }
-
- // Returns the index of a particular item, if it is in the list.
- // Returns -1 if the item isn't in the list.
- int IndexOf(T item);
-
- // Inserts value into the list at position index.
- // index must be non-negative and less than or equal to the
- // number of elements in the list. If index equals the number
- // of items in the list, then value is appended to the end.
- void Insert(int index, T item);
-
- // Removes the item at position index.
- void RemoveAt(int index);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs b/src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs
deleted file mode 100644
index 13bc718760..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IReadOnlyCollection.cs
+++ /dev/null
@@ -1,34 +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.
-
-/*============================================================
-**
-** Interface: IReadOnlyCollection<T>
-**
-**
-**
-** Purpose: Base interface for read-only generic lists.
-**
-===========================================================*/
-using System;
-using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-
-namespace System.Collections.Generic
-{
-
- // Provides a read-only, covariant view of a generic list.
-
- // Note that T[] : IReadOnlyList<T>, and we want to ensure that if you use
- // IList<YourValueType>, we ensure a YourValueType[] can be used
- // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper.
- // This is a special workaround internally though - see VM\compile.cpp.
- // The same attribute is on IList<T>, IEnumerable<T>, ICollection<T>, and IReadOnlyList<T>.
- [TypeDependencyAttribute("System.SZArrayHelper")]
- // If we ever implement more interfaces on IReadOnlyCollection, we should also update RuntimeTypeCache.PopulateInterfaces() in rttype.cs
- public interface IReadOnlyCollection<out T> : IEnumerable<T>
- {
- int Count { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.cs
deleted file mode 100644
index 3603b9a4ea..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IReadOnlyDictionary.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.
-
-/*============================================================
-**
-** Interface: IReadOnlyDictionary<TKey, TValue>
-**
-**
-**
-** Purpose: Base interface for read-only generic dictionaries.
-**
-===========================================================*/
-using System;
-using System.Diagnostics.Contracts;
-
-namespace System.Collections.Generic
-{
- // Provides a read-only view of a generic dictionary.
- public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>>
- {
- bool ContainsKey(TKey key);
- bool TryGetValue(TKey key, out TValue value);
-
- TValue this[TKey key] { get; }
- IEnumerable<TKey> Keys { get; }
- IEnumerable<TValue> Values { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs b/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs
deleted file mode 100644
index 77366f0b2f..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/IReadOnlyList.cs
+++ /dev/null
@@ -1,34 +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.
-
-/*============================================================
-**
-** Interface: IReadOnlyList<T>
-**
-**
-**
-** Purpose: Base interface for read-only generic lists.
-**
-===========================================================*/
-using System;
-using System.Diagnostics.Contracts;
-using System.Runtime.CompilerServices;
-
-namespace System.Collections.Generic
-{
-
- // Provides a read-only, covariant view of a generic list.
-
- // Note that T[] : IReadOnlyList<T>, and we want to ensure that if you use
- // IList<YourValueType>, we ensure a YourValueType[] can be used
- // without jitting. Hence the TypeDependencyAttribute on SZArrayHelper.
- // This is a special workaround internally though - see VM\compile.cpp.
- // The same attribute is on IList<T>, IEnumerable<T>, ICollection<T> and IReadOnlyCollection<T>.
- [TypeDependencyAttribute("System.SZArrayHelper")]
- // If we ever implement more interfaces on IReadOnlyList, we should also update RuntimeTypeCache.PopulateInterfaces() in rttype.cs
- public interface IReadOnlyList<out T> : IReadOnlyCollection<T>
- {
- T this[int index] { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs b/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
deleted file mode 100644
index 1cd18cf808..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/KeyNotFoundException.cs
+++ /dev/null
@@ -1,44 +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 class for Hashtable and Dictionary.
-**
-**
-=============================================================================*/
-
-namespace System.Collections.Generic {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
-
- [Serializable]
- public class KeyNotFoundException : SystemException, ISerializable {
-
- public KeyNotFoundException ()
- : base(Environment.GetResourceString("Arg_KeyNotFound")) {
- SetErrorCode(System.__HResults.COR_E_KEYNOTFOUND);
- }
-
- public KeyNotFoundException(String message)
- : base(message) {
- SetErrorCode(System.__HResults.COR_E_KEYNOTFOUND);
- }
-
- public KeyNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(System.__HResults.COR_E_KEYNOTFOUND);
- }
-
-
- protected KeyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs b/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
deleted file mode 100644
index ba98adad7d..0000000000
--- a/src/mscorlib/src/System/Collections/Generic/KeyValuePair.cs
+++ /dev/null
@@ -1,74 +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.
-
-/*============================================================
-**
-** Interface: KeyValuePair
-**
-**
-**
-**
-** Purpose: Generic key-value pair for dictionary enumerators.
-**
-**
-===========================================================*/
-namespace System.Collections.Generic {
-
- using System;
- using System.ComponentModel;
- using System.Text;
-
- // Provides the Create factory method for KeyValuePair<TKey, TValue>.
- public static class KeyValuePair
- {
- // Creates a new KeyValuePair<TKey, TValue> from the given values.
- public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value)
- {
- return new KeyValuePair<TKey, TValue>(key, value);
- }
- }
-
- // A KeyValuePair holds a key and a value from a dictionary.
- // It is used by the IEnumerable<T> implementation for both IDictionary<TKey, TValue>
- // and IReadOnlyDictionary<TKey, TValue>.
- [Serializable]
- public struct KeyValuePair<TKey, TValue> {
- private TKey key;
- private TValue value;
-
- public KeyValuePair(TKey key, TValue value) {
- this.key = key;
- this.value = value;
- }
-
- public TKey Key {
- get { return key; }
- }
-
- public TValue Value {
- get { return value; }
- }
-
- public override string ToString() {
- StringBuilder s = StringBuilderCache.Acquire();
- s.Append('[');
- if( Key != null) {
- s.Append(Key.ToString());
- }
- s.Append(", ");
- if( Value != null) {
- s.Append(Value.ToString());
- }
- s.Append(']');
- return StringBuilderCache.GetStringAndRelease(s);
- }
-
- [EditorBrowsable(EditorBrowsableState.Never)]
- public void Deconstruct(out TKey key, out TValue value)
- {
- key = Key;
- value = Value;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/Generic/List.cs b/src/mscorlib/src/System/Collections/Generic/List.cs
index 362e26599d..67d1668aad 100644
--- a/src/mscorlib/src/System/Collections/Generic/List.cs
+++ b/src/mscorlib/src/System/Collections/Generic/List.cs
@@ -12,15 +12,15 @@
**
**
===========================================================*/
-namespace System.Collections.Generic {
- using System;
- using System.Runtime;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Collections.ObjectModel;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Collections.ObjectModel;
+using System.Runtime.CompilerServices;
+namespace System.Collections.Generic
+{
// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length
// of the internal array. As elements are added to a List, the capacity
@@ -40,22 +40,24 @@ namespace System.Collections.Generic {
private int _version;
[NonSerialized]
private Object _syncRoot;
-
- static readonly T[] _emptyArray = new T[0];
-
+
+ private static readonly T[] _emptyArray = new T[0];
+
// Constructs a List. The list is initially empty and has a capacity
// of zero. Upon adding the first element to the list the capacity is
// increased to _defaultCapacity, and then increased in multiples of two
// as required.
- public List() {
+ public List()
+ {
_items = _emptyArray;
}
-
+
// Constructs a List with a given initial capacity. The list is
// initially empty, but will have room for the given number of elements
// before any reallocations are required.
//
- public List(int capacity) {
+ public List(int capacity)
+ {
if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
@@ -64,116 +66,142 @@ namespace System.Collections.Generic {
else
_items = new T[capacity];
}
-
+
// Constructs a List, copying the contents of the given collection. The
// size and capacity of the new list will both be equal to the size of the
// given collection.
//
- public List(IEnumerable<T> collection) {
- if (collection==null)
+ public List(IEnumerable<T> collection)
+ {
+ if (collection == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
- if( c != null) {
+ if (c != null)
+ {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
- else {
+ else
+ {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
- }
- else {
+ }
+ else
+ {
_size = 0;
_items = _emptyArray;
AddEnumerable(collection);
}
}
-
+
// Gets and sets the capacity of this list. The capacity is the size of
// the internal array used to hold items. When set, the internal
// array of the list is reallocated to the given capacity.
//
- public int Capacity {
- get {
+ public int Capacity
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
return _items.Length;
}
- set {
- if (value < _size) {
+ set
+ {
+ if (value < _size)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity);
}
Contract.EndContractBlock();
- if (value != _items.Length) {
- if (value > 0) {
+ if (value != _items.Length)
+ {
+ if (value > 0)
+ {
T[] newItems = new T[value];
- if (_size > 0) {
+ if (_size > 0)
+ {
Array.Copy(_items, 0, newItems, 0, _size);
}
_items = newItems;
}
- else {
+ else
+ {
_items = _emptyArray;
}
}
}
}
-
+
// Read-only property describing how many elements are in the List.
- public int Count {
- get {
+ public int Count
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
- return _size;
+ return _size;
}
}
- bool System.Collections.IList.IsFixedSize {
+ bool System.Collections.IList.IsFixedSize
+ {
get { return false; }
}
-
+
// Is this List read-only?
- bool ICollection<T>.IsReadOnly {
+ bool ICollection<T>.IsReadOnly
+ {
get { return false; }
}
- bool System.Collections.IList.IsReadOnly {
+ bool System.Collections.IList.IsReadOnly
+ {
get { return false; }
}
// Is this List synchronized (thread-safe)?
- bool System.Collections.ICollection.IsSynchronized {
+ bool System.Collections.ICollection.IsSynchronized
+ {
get { return false; }
}
-
+
// Synchronization root for this object.
- Object System.Collections.ICollection.SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ Object System.Collections.ICollection.SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
// Sets or Gets the element at the given index.
//
- public T this[int index] {
- get {
+ public T this[int index]
+ {
+ get
+ {
// Following trick can reduce the range check by one
- if ((uint) index >= (uint)_size) {
+ if ((uint)index >= (uint)_size)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
- return _items[index];
+ return _items[index];
}
- set {
- if ((uint) index >= (uint)_size) {
+ set
+ {
+ if ((uint)index >= (uint)_size)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
@@ -182,24 +210,30 @@ namespace System.Collections.Generic {
}
}
- private static bool IsCompatibleObject(object value) {
+ private static bool IsCompatibleObject(object value)
+ {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
- Object System.Collections.IList.this[int index] {
- get {
+ Object System.Collections.IList.this[int index]
+ {
+ get
+ {
return this[index];
}
- set {
+ set
+ {
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
- try {
- this[index] = (T)value;
+ try
+ {
+ this[index] = (T)value;
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
}
}
@@ -207,22 +241,44 @@ namespace System.Collections.Generic {
// Adds the given object to the end of this list. The size of the list is
// increased by one. If required, the capacity of the list is doubled
// before adding the new element.
- //
- public void Add(T item) {
- if (_size == _items.Length) EnsureCapacity(_size + 1);
- _items[_size++] = item;
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void Add(T item)
+ {
+ var array = _items;
+ var size = _size;
_version++;
+ if ((uint)size < (uint)array.Length)
+ {
+ _size = size + 1;
+ array[size] = item;
+ }
+ else
+ {
+ AddWithResize(item);
+ }
+ }
+
+ // Non-inline from List.Add to improve its code quality as uncommon path
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private void AddWithResize(T item)
+ {
+ var size = _size;
+ EnsureCapacity(size + 1);
+ _size = size + 1;
+ _items[size] = item;
}
int System.Collections.IList.Add(Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
- try {
- Add((T) item);
+ try
+ {
+ Add((T)item);
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
return Count - 1;
@@ -233,17 +289,19 @@ namespace System.Collections.Generic {
// required, the capacity of the list is increased to twice the previous
// capacity or the new size, whichever is larger.
//
- public void AddRange(IEnumerable<T> collection) {
+ public void AddRange(IEnumerable<T> collection)
+ {
Contract.Ensures(Count >= Contract.OldValue(Count));
InsertRange(_size, collection);
}
- public ReadOnlyCollection<T> AsReadOnly() {
+ public ReadOnlyCollection<T> AsReadOnly()
+ {
Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null);
return new ReadOnlyCollection<T>(this);
}
-
+
// Searches a section of the list for a given element using a binary search
// algorithm. Elements of the list are compared to the search value using
// the given IComparer interface. If comparer is null, elements of
@@ -264,7 +322,8 @@ namespace System.Collections.Generic {
// The method uses the Array.BinarySearch method to perform the
// search.
//
- public int BinarySearch(int index, int count, T item, IComparer<T> comparer) {
+ public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
+ {
if (index < 0)
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
if (count < 0)
@@ -276,7 +335,7 @@ namespace System.Collections.Generic {
return Array.BinarySearch<T>(_items, index, count, item, comparer);
}
-
+
public int BinarySearch(T item)
{
Contract.Ensures(Contract.Result<int>() <= Count);
@@ -289,17 +348,27 @@ namespace System.Collections.Generic {
return BinarySearch(0, Count, item, comparer);
}
-
+
// Clears the contents of List.
- public void Clear() {
- if (_size > 0)
+ public void Clear()
+ {
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
- Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
+ int size = _size;
_size = 0;
+ _version++;
+ if (size > 0)
+ {
+ Array.Clear(_items, 0, size); // Clear the elements so that the gc can reclaim the references.
+ }
+ }
+ else
+ {
+ _size = 0;
+ _version++;
}
- _version++;
}
-
+
// Contains returns true if the specified element is in the List.
// It does a linear, O(n) search. Equality is determined by calling
// EqualityComparer<T>.Default.Equals().
@@ -319,21 +388,25 @@ namespace System.Collections.Generic {
bool System.Collections.IList.Contains(Object item)
{
- if(IsCompatibleObject(item)) {
- return Contains((T) item);
+ if (IsCompatibleObject(item))
+ {
+ return Contains((T)item);
}
return false;
}
- public List<TOutput> ConvertAll<TOutput>(Converter<T,TOutput> converter) {
- if( converter == null) {
+ public List<TOutput> ConvertAll<TOutput>(Converter<T, TOutput> converter)
+ {
+ if (converter == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter);
}
Contract.EndContractBlock();
List<TOutput> list = new List<TOutput>(_size);
- for( int i = 0; i< _size; i++) {
+ for (int i = 0; i < _size; i++)
+ {
list._items[i] = converter(_items[i]);
}
list._size = _size;
@@ -343,43 +416,51 @@ namespace System.Collections.Generic {
// Copies this List into array, which must be of a
// compatible array type.
//
- public void CopyTo(T[] array) {
+ public void CopyTo(T[] array)
+ {
CopyTo(array, 0);
}
// Copies this List into array, which must be of a
// compatible array type.
//
- void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) {
- if ((array != null) && (array.Rank != 1)) {
+ void System.Collections.ICollection.CopyTo(Array array, int arrayIndex)
+ {
+ if ((array != null) && (array.Rank != 1))
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
Contract.EndContractBlock();
- try {
+ try
+ {
// Array.Copy will check for NULL.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
- catch(ArrayTypeMismatchException){
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
-
+
// Copies a section of this list to the given array at the given index.
//
// The method uses the Array.Copy method to copy the elements.
//
- public void CopyTo(int index, T[] array, int arrayIndex, int count) {
- if (_size - index < count) {
+ public void CopyTo(int index, T[] array, int arrayIndex, int count)
+ {
+ if (_size - index < count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.EndContractBlock();
-
+
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, index, array, arrayIndex, count);
}
- public void CopyTo(T[] array, int arrayIndex) {
+ public void CopyTo(T[] array, int arrayIndex)
+ {
// Delegate rest of error checking to Array.Copy.
Array.Copy(_items, 0, array, arrayIndex, _size);
}
@@ -388,9 +469,11 @@ namespace System.Collections.Generic {
// value. If the current capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
- private void EnsureCapacity(int min) {
- if (_items.Length < min) {
- int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
+ private void EnsureCapacity(int min)
+ {
+ if (_items.Length < min)
+ {
+ int newCapacity = _items.Length == 0 ? _defaultCapacity : _items.Length * 2;
// Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength;
@@ -398,62 +481,77 @@ namespace System.Collections.Generic {
Capacity = newCapacity;
}
}
-
- public bool Exists(Predicate<T> match) {
+
+ public bool Exists(Predicate<T> match)
+ {
return FindIndex(match) != -1;
}
- public T Find(Predicate<T> match) {
- if( match == null) {
+ public T Find(Predicate<T> match)
+ {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- for(int i = 0 ; i < _size; i++) {
- if(match(_items[i])) {
+ for (int i = 0; i < _size; i++)
+ {
+ if (match(_items[i]))
+ {
return _items[i];
}
}
return default(T);
}
-
- public List<T> FindAll(Predicate<T> match) {
- if( match == null) {
+
+ public List<T> FindAll(Predicate<T> match)
+ {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- List<T> list = new List<T>();
- for(int i = 0 ; i < _size; i++) {
- if(match(_items[i])) {
+ List<T> list = new List<T>();
+ for (int i = 0; i < _size; i++)
+ {
+ if (match(_items[i]))
+ {
list.Add(_items[i]);
}
}
return list;
}
-
- public int FindIndex(Predicate<T> match) {
+
+ public int FindIndex(Predicate<T> match)
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindIndex(0, _size, match);
}
-
- public int FindIndex(int startIndex, Predicate<T> match) {
+
+ public int FindIndex(int startIndex, Predicate<T> match)
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < startIndex + Count);
return FindIndex(startIndex, _size - startIndex, match);
}
-
- public int FindIndex(int startIndex, int count, Predicate<T> match) {
- if( (uint)startIndex > (uint)_size ) {
- ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
+
+ public int FindIndex(int startIndex, int count, Predicate<T> match)
+ {
+ if ((uint)startIndex > (uint)_size)
+ {
+ ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
- if (count < 0 || startIndex > _size - count) {
+ if (count < 0 || startIndex > _size - count)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
- if( match == null) {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
@@ -461,83 +559,103 @@ namespace System.Collections.Generic {
Contract.EndContractBlock();
int endIndex = startIndex + count;
- for( int i = startIndex; i < endIndex; i++) {
- if( match(_items[i])) return i;
+ for (int i = startIndex; i < endIndex; i++)
+ {
+ if (match(_items[i])) return i;
}
return -1;
}
-
- public T FindLast(Predicate<T> match) {
- if( match == null) {
+
+ public T FindLast(Predicate<T> match)
+ {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- for(int i = _size - 1 ; i >= 0; i--) {
- if(match(_items[i])) {
+ for (int i = _size - 1; i >= 0; i--)
+ {
+ if (match(_items[i]))
+ {
return _items[i];
}
}
return default(T);
}
- public int FindLastIndex(Predicate<T> match) {
+ public int FindLastIndex(Predicate<T> match)
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return FindLastIndex(_size - 1, _size, match);
}
-
- public int FindLastIndex(int startIndex, Predicate<T> match) {
+
+ public int FindLastIndex(int startIndex, Predicate<T> match)
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
return FindLastIndex(startIndex, startIndex + 1, match);
}
- public int FindLastIndex(int startIndex, int count, Predicate<T> match) {
- if( match == null) {
+ public int FindLastIndex(int startIndex, int count, Predicate<T> match)
+ {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() <= startIndex);
Contract.EndContractBlock();
- if(_size == 0) {
+ if (_size == 0)
+ {
// Special case for 0 length List
- if( startIndex != -1) {
+ if (startIndex != -1)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
- else {
+ else
+ {
// Make sure we're not out of range
- if ( (uint)startIndex >= (uint)_size) {
+ if ((uint)startIndex >= (uint)_size)
+ {
ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index();
}
}
-
+
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
- if (count < 0 || startIndex - count + 1 < 0) {
+ if (count < 0 || startIndex - count + 1 < 0)
+ {
ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
}
-
+
int endIndex = startIndex - count;
- for( int i = startIndex; i > endIndex; i--) {
- if( match(_items[i])) {
+ for (int i = startIndex; i > endIndex; i--)
+ {
+ if (match(_items[i]))
+ {
return i;
}
}
return -1;
}
- public void ForEach(Action<T> action) {
- if( action == null) {
+ public void ForEach(Action<T> action)
+ {
+ if (action == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action);
}
Contract.EndContractBlock();
int version = _version;
- for(int i = 0 ; i < _size; i++) {
- if (version != _version) {
+ for (int i = 0; i < _size; i++)
+ {
+ if (version != _version)
+ {
break;
}
action(_items[i]);
@@ -552,36 +670,42 @@ namespace System.Collections.Generic {
// while an enumeration is in progress, the MoveNext and
// GetObject methods of the enumerator will throw an exception.
//
- public Enumerator GetEnumerator() {
+ public Enumerator GetEnumerator()
+ {
return new Enumerator(this);
}
- /// <internalonly/>
- IEnumerator<T> IEnumerable<T>.GetEnumerator() {
+ IEnumerator<T> IEnumerable<T>.GetEnumerator()
+ {
return new Enumerator(this);
}
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+ {
return new Enumerator(this);
}
- public List<T> GetRange(int index, int count) {
- if (index < 0) {
+ public List<T> GetRange(int index, int count)
+ {
+ if (index < 0)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (count < 0) {
+ if (count < 0)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
- if (_size - index < count) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
+ if (_size - index < count)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<List<T>>() != null);
Contract.EndContractBlock();
List<T> list = new List<T>(count);
- Array.Copy(_items, index, list._items, 0, count);
+ Array.Copy(_items, index, list._items, 0, count);
list._size = count;
return list;
}
@@ -595,7 +719,8 @@ namespace System.Collections.Generic {
// This method uses the Array.IndexOf method to perform the
// search.
//
- public int IndexOf(T item) {
+ public int IndexOf(T item)
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
return Array.IndexOf(_items, item, 0, _size);
@@ -603,7 +728,8 @@ namespace System.Collections.Generic {
int System.Collections.IList.IndexOf(Object item)
{
- if(IsCompatibleObject(item)) {
+ if (IsCompatibleObject(item))
+ {
return IndexOf((T)item);
}
return -1;
@@ -618,7 +744,8 @@ namespace System.Collections.Generic {
// This method uses the Array.IndexOf method to perform the
// search.
//
- public int IndexOf(T item, int index) {
+ public int IndexOf(T item, int index)
+ {
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
Contract.Ensures(Contract.Result<int>() >= -1);
@@ -636,46 +763,52 @@ namespace System.Collections.Generic {
// This method uses the Array.IndexOf method to perform the
// search.
//
- public int IndexOf(T item, int index, int count) {
+ public int IndexOf(T item, int index, int count)
+ {
if (index > _size)
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
- if (count <0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
+ if (count < 0 || index > _size - count) ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count();
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
Contract.EndContractBlock();
return Array.IndexOf(_items, item, index, count);
}
-
+
// Inserts an element into this list at a given index. The size of the list
// is increased by one. If required, the capacity of the list is doubled
// before inserting the new element.
//
- public void Insert(int index, T item) {
+ public void Insert(int index, T item)
+ {
// Note that insertions at the end are legal.
- if ((uint) index > (uint)_size) {
+ if ((uint)index > (uint)_size)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
Contract.EndContractBlock();
if (_size == _items.Length) EnsureCapacity(_size + 1);
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index, _items, index + 1, _size - index);
}
_items[index] = item;
- _size++;
+ _size++;
_version++;
}
-
+
void System.Collections.IList.Insert(int index, Object item)
{
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item);
- try {
- Insert(index, (T) item);
+ try
+ {
+ Insert(index, (T)item);
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T));
}
}
@@ -684,44 +817,55 @@ namespace System.Collections.Generic {
// capacity or the new size, whichever is larger. Ranges may be added
// to the end of the list by setting index to the List's size.
//
- public void InsertRange(int index, IEnumerable<T> collection) {
- if (collection==null) {
+ public void InsertRange(int index, IEnumerable<T> collection)
+ {
+ if (collection == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
-
- if ((uint)index > (uint)_size) {
+
+ if ((uint)index > (uint)_size)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
ICollection<T> c = collection as ICollection<T>;
- if( c != null ) { // if collection is ICollection<T>
+ if (c != null)
+ { // if collection is ICollection<T>
int count = c.Count;
- if (count > 0) {
+ if (count > 0)
+ {
EnsureCapacity(_size + count);
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index, _items, index + count, _size - index);
}
-
+
// If we're inserting a List into itself, we want to be able to deal with that.
- if (this == c) {
+ if (this == c)
+ {
// Copy first part of _items to insert location
Array.Copy(_items, 0, _items, index, index);
// Copy last part of _items back to inserted location
- Array.Copy(_items, index+count, _items, index*2, _size-index);
+ Array.Copy(_items, index + count, _items, index * 2, _size - index);
}
- else {
+ else
+ {
c.CopyTo(_items, index);
}
_size += count;
- }
+ }
}
- else if (index < _size) {
+ else if (index < _size)
+ {
// We're inserting a lazy enumerable. Call Insert on each of the constituent items.
- using(IEnumerator<T> en = collection.GetEnumerator()) {
- while(en.MoveNext()) {
- Insert(index++, en.Current);
- }
+ using (IEnumerator<T> en = collection.GetEnumerator())
+ {
+ while (en.MoveNext())
+ {
+ Insert(index++, en.Current);
+ }
}
}
else
@@ -729,9 +873,9 @@ namespace System.Collections.Generic {
// We're adding a lazy enumerable because the index is at the end of this list.
AddEnumerable(collection);
}
- _version++;
+ _version++;
}
-
+
// Returns the index of the last occurrence of a given value in a range of
// this list. The list is searched backwards, starting at the end
// and ending at the first element in the list. The elements of the list
@@ -744,10 +888,12 @@ namespace System.Collections.Generic {
{
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(Contract.Result<int>() < Count);
- if (_size == 0) { // Special case for empty list
+ if (_size == 0)
+ { // Special case for empty list
return -1;
}
- else {
+ else
+ {
return LastIndexOf(item, _size - 1, _size);
}
}
@@ -780,39 +926,47 @@ namespace System.Collections.Generic {
// This method uses the Array.LastIndexOf method to perform the
// search.
//
- public int LastIndexOf(T item, int index, int count) {
- if ((Count != 0) && (index < 0)) {
+ public int LastIndexOf(T item, int index, int count)
+ {
+ if ((Count != 0) && (index < 0))
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if ((Count !=0) && (count < 0)) {
+ if ((Count != 0) && (count < 0))
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<int>() >= -1);
Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index)));
Contract.EndContractBlock();
- if (_size == 0) { // Special case for empty list
+ if (_size == 0)
+ { // Special case for empty list
return -1;
}
- if (index >= _size) {
+ if (index >= _size)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
}
- if (count > index + 1) {
+ if (count > index + 1)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection);
- }
+ }
return Array.LastIndexOf(_items, item, index, count);
}
-
+
// Removes the element at the given index. The size of the list is
// decreased by one.
//
- public bool Remove(T item) {
+ public bool Remove(T item)
+ {
int index = IndexOf(item);
- if (index >= 0) {
+ if (index >= 0)
+ {
RemoveAt(index);
return true;
}
@@ -822,39 +976,48 @@ namespace System.Collections.Generic {
void System.Collections.IList.Remove(Object item)
{
- if(IsCompatibleObject(item)) {
- Remove((T) item);
+ if (IsCompatibleObject(item))
+ {
+ Remove((T)item);
}
}
// This method removes all items which matches the predicate.
// The complexity is O(n).
- public int RemoveAll(Predicate<T> match) {
- if( match == null) {
+ public int RemoveAll(Predicate<T> match)
+ {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count));
Contract.EndContractBlock();
-
+
int freeIndex = 0; // the first free slot in items array
// Find the first item which needs to be removed.
- while( freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
- if( freeIndex >= _size) return 0;
-
+ while (freeIndex < _size && !match(_items[freeIndex])) freeIndex++;
+ if (freeIndex >= _size) return 0;
+
int current = freeIndex + 1;
- while( current < _size) {
+ while (current < _size)
+ {
// Find the first item which needs to be kept.
- while( current < _size && match(_items[current])) current++;
+ while (current < _size && match(_items[current])) current++;
- if( current < _size) {
+ if (current < _size)
+ {
// copy item to the free slot.
_items[freeIndex++] = _items[current++];
}
- }
-
- Array.Clear(_items, freeIndex, _size - freeIndex);
+ }
+
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
+ {
+ Array.Clear(_items, freeIndex, _size - freeIndex); // Clear the elements so that the gc can reclaim the references.
+ }
+
int result = _size - freeIndex;
_size = freeIndex;
_version++;
@@ -864,61 +1027,80 @@ namespace System.Collections.Generic {
// Removes the element at the given index. The size of the list is
// decreased by one.
//
- public void RemoveAt(int index) {
- if ((uint)index >= (uint)_size) {
+ public void RemoveAt(int index)
+ {
+ if ((uint)index >= (uint)_size)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
Contract.EndContractBlock();
_size--;
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index + 1, _items, index, _size - index);
}
- _items[_size] = default(T);
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
+ {
+ _items[_size] = default(T);
+ }
_version++;
}
-
+
// Removes a range of elements from this list.
//
- public void RemoveRange(int index, int count) {
- if (index < 0) {
+ public void RemoveRange(int index, int count)
+ {
+ if (index < 0)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (count < 0) {
+ if (count < 0)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
-
+
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
-
- if (count > 0) {
+
+ if (count > 0)
+ {
int i = _size;
_size -= count;
- if (index < _size) {
+ if (index < _size)
+ {
Array.Copy(_items, index + count, _items, index, _size - index);
}
- Array.Clear(_items, _size, count);
+
_version++;
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
+ {
+ Array.Clear(_items, _size, count);
+ }
}
}
-
+
// Reverses the elements in this list.
- public void Reverse() {
+ public void Reverse()
+ {
Reverse(0, Count);
}
-
+
// Reverses the elements in a range of this list. Following a call to this
// method, an element in the range given by index and count
// which was previously located at index i will now be located at
// index index + (index + count - i - 1).
//
- public void Reverse(int index, int count) {
- if (index < 0) {
+ public void Reverse(int index, int count)
+ {
+ if (index < 0)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
-
- if (count < 0) {
+
+ if (count < 0)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
@@ -926,12 +1108,13 @@ namespace System.Collections.Generic {
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- if (count > 1) {
+ if (count > 1)
+ {
Array.Reverse(_items, index, count);
}
_version++;
}
-
+
// Sorts the elements in this list. Uses the default comparer and
// Array.Sort.
public void Sort()
@@ -954,32 +1137,39 @@ namespace System.Collections.Generic {
//
// This method uses the Array.Sort method to sort the elements.
//
- public void Sort(int index, int count, IComparer<T> comparer) {
- if (index < 0) {
+ public void Sort(int index, int count, IComparer<T> comparer)
+ {
+ if (index < 0)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
-
- if (count < 0) {
+
+ if (count < 0)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
-
+
if (_size - index < count)
ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen);
Contract.EndContractBlock();
- if (count > 1) {
+ if (count > 1)
+ {
Array.Sort<T>(_items, index, count, comparer);
}
_version++;
}
- public void Sort(Comparison<T> comparison) {
- if( comparison == null) {
+ public void Sort(Comparison<T> comparison)
+ {
+ if (comparison == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison);
}
Contract.EndContractBlock();
- if (_size > 1) {
+ if (_size > 1)
+ {
ArraySortHelper<T>.Sort(_items, 0, _size, comparison);
}
_version++;
@@ -987,7 +1177,8 @@ namespace System.Collections.Generic {
// ToArray returns an array containing the contents of the List.
// This requires copying the List, which is an O(n) operation.
- public T[] ToArray() {
+ public T[] ToArray()
+ {
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == Count);
@@ -1000,7 +1191,7 @@ namespace System.Collections.Generic {
Array.Copy(_items, 0, array, 0, _size);
return array;
}
-
+
// Sets the capacity of this list to the size of the list. This method can
// be used to minimize a list's memory overhead once it is known that no
// new elements will be added to the list. To completely clear a list and
@@ -1010,21 +1201,27 @@ namespace System.Collections.Generic {
// list.Clear();
// list.TrimExcess();
//
- public void TrimExcess() {
- int threshold = (int)(((double)_items.Length) * 0.9);
- if( _size < threshold ) {
- Capacity = _size;
+ public void TrimExcess()
+ {
+ int threshold = (int)(((double)_items.Length) * 0.9);
+ if (_size < threshold)
+ {
+ Capacity = _size;
}
- }
+ }
- public bool TrueForAll(Predicate<T> match) {
- if( match == null) {
+ public bool TrueForAll(Predicate<T> match)
+ {
+ if (match == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
Contract.EndContractBlock();
- for(int i = 0 ; i < _size; i++) {
- if( !match(_items[i])) {
+ for (int i = 0; i < _size; i++)
+ {
+ if (!match(_items[i]))
+ {
return false;
}
}
@@ -1064,23 +1261,25 @@ namespace System.Collections.Generic {
private int version;
private T current;
- internal Enumerator(List<T> list) {
+ internal Enumerator(List<T> list)
+ {
this.list = list;
index = 0;
version = list._version;
current = default(T);
}
- public void Dispose() {
+ public void Dispose()
+ {
}
- public bool MoveNext() {
-
+ public bool MoveNext()
+ {
List<T> localList = list;
- if (version == localList._version && ((uint)index < (uint)localList._size))
- {
- current = localList._items[index];
+ if (version == localList._version && ((uint)index < (uint)localList._size))
+ {
+ current = localList._items[index];
index++;
return true;
}
@@ -1088,40 +1287,47 @@ namespace System.Collections.Generic {
}
private bool MoveNextRare()
- {
- if (version != list._version) {
+ {
+ if (version != list._version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
index = list._size + 1;
current = default(T);
- return false;
+ return false;
}
- public T Current {
- get {
+ public T Current
+ {
+ get
+ {
return current;
}
}
- Object System.Collections.IEnumerator.Current {
- get {
- if( index == 0 || index == list._size + 1) {
- ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
+ Object System.Collections.IEnumerator.Current
+ {
+ get
+ {
+ if (index == 0 || index == list._size + 1)
+ {
+ ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen();
}
return Current;
}
}
-
- void System.Collections.IEnumerator.Reset() {
- if (version != list._version) {
+
+ void System.Collections.IEnumerator.Reset()
+ {
+ if (version != list._version)
+ {
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
-
+
index = 0;
current = default(T);
}
-
}
}
}
diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs
index d1831dd97d..e2fd57ea4d 100644
--- a/src/mscorlib/src/System/Collections/Hashtable.cs
+++ b/src/mscorlib/src/System/Collections/Hashtable.cs
@@ -13,12 +13,13 @@
**
===========================================================*/
-namespace System.Collections {
+namespace System.Collections
+{
using System;
using System.Runtime;
using System.Runtime.Serialization;
using System.Diagnostics;
- using System.Threading;
+ using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics.Contracts;
@@ -66,7 +67,8 @@ namespace System.Collections {
[DebuggerTypeProxy(typeof(System.Collections.Hashtable.HashtableDebugView))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- internal class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable {
+ internal class Hashtable : IDictionary, ISerializable, IDeserializationCallback, ICloneable
+ {
/*
Implementation Notes:
The generic Dictionary was copied from Hashtable's source - any bug
@@ -121,7 +123,7 @@ namespace System.Collections {
--
*/
-
+
internal const Int32 HashPrime = 101;
private const Int32 InitialSize = 3;
private const String LoadFactorName = "LoadFactor";
@@ -132,31 +134,32 @@ namespace System.Collections {
private const String KeysName = "Keys";
private const String ValuesName = "Values";
private const String KeyComparerName = "KeyComparer";
-
+
// Deleted entries have their key set to buckets
-
+
// The hash table data.
// This cannot be serialised
- private struct bucket {
+ private struct bucket
+ {
public Object key;
public Object val;
public int hash_coll; // Store hash code; sign bit means there was a collision.
}
-
+
private bucket[] buckets;
-
+
// The total number of entries in the hash table.
- private int count;
-
+ private int count;
+
// The total number of collision bits set in the hashtable
private int occupancy;
-
- private int loadsize;
- private float loadFactor;
-
+
+ private int loadsize;
+ private float loadFactor;
+
private volatile int version;
- private volatile bool isWriterInProgress;
-
+ private volatile bool isWriterInProgress;
+
private ICollection keys;
private ICollection values;
@@ -165,15 +168,16 @@ namespace System.Collections {
// Note: this constructor is a bogus constructor that does nothing
// and is for use only with SyncHashtable.
- internal Hashtable( bool trash )
+ internal Hashtable(bool trash)
{
}
// Constructs a new hashtable. The hashtable is created with an initial
// capacity of zero and a load factor of 1.0.
- public Hashtable() : this(0, 1.0f) {
+ public Hashtable() : this(0, 1.0f)
+ {
}
-
+
// Constructs a new hashtable with the given initial capacity and a load
// factor of 1.0. The capacity argument serves as an indication of
// the number of entries the hashtable will contain. When this number (or
@@ -181,9 +185,10 @@ namespace System.Collections {
// eliminate a number of resizing operations that would otherwise be
// performed when elements are added to the hashtable.
//
- public Hashtable(int capacity) : this(capacity, 1.0f) {
+ public Hashtable(int capacity) : this(capacity, 1.0f)
+ {
}
-
+
// Constructs a new hashtable with the given initial capacity and load
// factor. The capacity argument serves as an indication of the
// number of entries the hashtable will contain. When this number (or an
@@ -195,19 +200,20 @@ namespace System.Collections {
// increased memory consumption. A load factor of 1.0 generally provides
// the best balance between speed and size.
//
- public Hashtable(int capacity, float loadFactor) {
+ public Hashtable(int capacity, float loadFactor)
+ {
if (capacity < 0)
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (!(loadFactor >= 0.1f && loadFactor <= 1.0f))
- throw new ArgumentOutOfRangeException(nameof(loadFactor), Environment.GetResourceString("ArgumentOutOfRange_HashtableLoadFactor", .1, 1.0));
+ throw new ArgumentOutOfRangeException(nameof(loadFactor), SR.Format(SR.ArgumentOutOfRange_HashtableLoadFactor, .1, 1.0));
Contract.EndContractBlock();
-
+
// Based on perf work, .72 is the optimal load factor for this table.
this.loadFactor = 0.72f * loadFactor;
double rawsize = capacity / this.loadFactor;
if (rawsize > Int32.MaxValue)
- throw new ArgumentException(Environment.GetResourceString("Arg_HTCapacityOverflow"));
+ throw new ArgumentException(SR.Arg_HTCapacityOverflow);
// Avoid awfully small sizes
int hashsize = (rawsize > InitialSize) ? HashHelpers.GetPrime((int)rawsize) : InitialSize;
@@ -216,18 +222,21 @@ namespace System.Collections {
loadsize = (int)(this.loadFactor * hashsize);
isWriterInProgress = false;
// Based on the current algorithm, loadsize must be less than hashsize.
- Debug.Assert( loadsize < hashsize, "Invalid hashtable loadsize!");
+ Debug.Assert(loadsize < hashsize, "Invalid hashtable loadsize!");
}
-
- public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor) {
- this._keycomparer = equalityComparer;
+
+ public Hashtable(int capacity, float loadFactor, IEqualityComparer equalityComparer) : this(capacity, loadFactor)
+ {
+ _keycomparer = equalityComparer;
}
- public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer) {
+ public Hashtable(IEqualityComparer equalityComparer) : this(0, 1.0f, equalityComparer)
+ {
}
-
- public Hashtable(int capacity, IEqualityComparer equalityComparer)
- : this(capacity, 1.0f, equalityComparer) {
+
+ public Hashtable(int capacity, IEqualityComparer equalityComparer)
+ : this(capacity, 1.0f, equalityComparer)
+ {
}
// InitHash is basically an implementation of classic DoubleHashing (see http://en.wikipedia.org/wiki/Double_hashing)
@@ -250,11 +259,12 @@ namespace System.Collections {
// The out parameter seed is h1(key), while the out parameter
// incr is h2(key, hashSize). Callers of this function should
// add incr each time through a loop.
- private uint InitHash(Object key, int hashsize, out uint seed, out uint incr) {
+ private uint InitHash(Object key, int hashsize, out uint seed, out uint incr)
+ {
// Hashcode must be positive. Also, we must not use the sign bit, since
// that is used for the collision bit.
- uint hashcode = (uint) GetHash(key) & 0x7FFFFFFF;
- seed = (uint) hashcode;
+ uint hashcode = (uint)GetHash(key) & 0x7FFFFFFF;
+ seed = (uint)hashcode;
// Restriction: incr MUST be between 1 and hashsize - 1, inclusive for
// the modular arithmetic to work correctly. This guarantees you'll
// visit every bucket in the table exactly once within hashsize
@@ -268,64 +278,72 @@ namespace System.Collections {
// ArgumentException is thrown if the key is null or if the key is already
// present in the hashtable.
//
- public virtual void Add(Object key, Object value) {
+ public virtual void Add(Object key, Object value)
+ {
Insert(key, value, true);
}
// Removes all entries from this hashtable.
- public virtual void Clear() {
+ public virtual void Clear()
+ {
Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
if (count == 0 && occupancy == 0)
return;
isWriterInProgress = true;
- for (int i = 0; i < buckets.Length; i++){
+ for (int i = 0; i < buckets.Length; i++)
+ {
buckets[i].hash_coll = 0;
buckets[i].key = null;
buckets[i].val = null;
}
-
+
count = 0;
occupancy = 0;
- UpdateVersion();
- isWriterInProgress = false;
+ UpdateVersion();
+ isWriterInProgress = false;
}
-
+
// Clone returns a virtually identical copy of this hash table. This does
// a shallow copy - the Objects in the table aren't cloned, only the references
// to those Objects.
public virtual Object Clone()
- {
+ {
bucket[] lbuckets = buckets;
- Hashtable ht = new Hashtable(count,_keycomparer);
+ Hashtable ht = new Hashtable(count, _keycomparer);
ht.version = version;
ht.loadFactor = loadFactor;
ht.count = 0;
int bucket = lbuckets.Length;
- while (bucket > 0) {
+ while (bucket > 0)
+ {
bucket--;
Object keyv = lbuckets[bucket].key;
- if ((keyv!= null) && (keyv != lbuckets)) {
+ if ((keyv != null) && (keyv != lbuckets))
+ {
ht[keyv] = lbuckets[bucket].val;
}
}
return ht;
}
-
+
// Checks if this hashtable contains the given key.
- public virtual bool Contains(Object key) {
+ public virtual bool Contains(Object key)
+ {
return ContainsKey(key);
}
-
+
// Checks if this hashtable contains an entry with the given key. This is
// an O(1) operation.
//
- public virtual bool ContainsKey(Object key) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public virtual bool ContainsKey(Object key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
@@ -334,68 +352,76 @@ namespace System.Collections {
// Take a snapshot of buckets, in case another thread resizes table
bucket[] lbuckets = buckets;
uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
- int ntry = 0;
-
+ int ntry = 0;
+
bucket b;
- int bucketNumber = (int) (seed % (uint)lbuckets.Length);
- do {
+ int bucketNumber = (int)(seed % (uint)lbuckets.Length);
+ do
+ {
b = lbuckets[bucketNumber];
- if (b.key == null) {
+ if (b.key == null)
+ {
return false;
}
- if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
- KeyEquals (b.key, key))
+ if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
+ KeyEquals(b.key, key))
return true;
- bucketNumber = (int) (((long)bucketNumber + incr)% (uint)lbuckets.Length);
+ bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length);
} while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
return false;
}
-
+
// Copies the keys of this hashtable to a given array starting at a given
// index. This method is used by the implementation of the CopyTo method in
// the KeyCollection class.
- private void CopyKeys(Array array, int arrayIndex) {
+ private void CopyKeys(Array array, int arrayIndex)
+ {
Contract.Requires(array != null);
Contract.Requires(array.Rank == 1);
bucket[] lbuckets = buckets;
- for (int i = lbuckets.Length; --i >= 0;) {
+ for (int i = lbuckets.Length; --i >= 0;)
+ {
Object keyv = lbuckets[i].key;
- if ((keyv != null) && (keyv != buckets)){
+ if ((keyv != null) && (keyv != buckets))
+ {
array.SetValue(keyv, arrayIndex++);
}
- }
+ }
}
// Copies the keys of this hashtable to a given array starting at a given
// index. This method is used by the implementation of the CopyTo method in
// the KeyCollection class.
- private void CopyEntries(Array array, int arrayIndex) {
+ private void CopyEntries(Array array, int arrayIndex)
+ {
Contract.Requires(array != null);
Contract.Requires(array.Rank == 1);
bucket[] lbuckets = buckets;
- for (int i = lbuckets.Length; --i >= 0;) {
+ for (int i = lbuckets.Length; --i >= 0;)
+ {
Object keyv = lbuckets[i].key;
- if ((keyv != null) && (keyv != buckets)){
- DictionaryEntry entry = new DictionaryEntry(keyv,lbuckets[i].val);
+ if ((keyv != null) && (keyv != buckets))
+ {
+ DictionaryEntry entry = new DictionaryEntry(keyv, lbuckets[i].val);
array.SetValue(entry, arrayIndex++);
}
}
}
-
+
// Copies the values in this hash table to an array at
// a given index. Note that this only copies values, and not keys.
public virtual void CopyTo(Array array, int arrayIndex)
{
if (array == null)
- throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Array);
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
+ if (arrayIndex < 0)
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - arrayIndex < Count)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
+ throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
Contract.EndContractBlock();
CopyEntries(array, arrayIndex);
}
@@ -404,40 +430,46 @@ namespace System.Collections {
// Copies the values of this hashtable to a given array starting at a given
// index. This method is used by the implementation of the CopyTo method in
// the ValueCollection class.
- private void CopyValues(Array array, int arrayIndex) {
+ private void CopyValues(Array array, int arrayIndex)
+ {
Contract.Requires(array != null);
Contract.Requires(array.Rank == 1);
bucket[] lbuckets = buckets;
- for (int i = lbuckets.Length; --i >= 0;) {
+ for (int i = lbuckets.Length; --i >= 0;)
+ {
Object keyv = lbuckets[i].key;
- if ((keyv != null) && (keyv != buckets)){
+ if ((keyv != null) && (keyv != buckets))
+ {
array.SetValue(lbuckets[i].val, arrayIndex++);
}
}
}
-
+
// Returns the value associated with the given key. If an entry with the
// given key is not found, the returned value is null.
//
- public virtual Object this[Object key] {
- get {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public virtual Object this[Object key]
+ {
+ get
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
uint seed;
uint incr;
-
+
// Take a snapshot of buckets, in case another thread does a resize
bucket[] lbuckets = buckets;
uint hashcode = InitHash(key, lbuckets.Length, out seed, out incr);
- int ntry = 0;
-
+ int ntry = 0;
+
bucket b;
- int bucketNumber = (int) (seed % (uint)lbuckets.Length);
+ int bucketNumber = (int)(seed % (uint)lbuckets.Length);
do
{
int currentversion;
@@ -459,35 +491,39 @@ namespace System.Collections {
// we will see the 'isWriterProgress' flag to be true or 'version' is changed in the reader.
//
int spinCount = 0;
- do {
+ do
+ {
// this is violate read, following memory accesses can not be moved ahead of it.
currentversion = version;
- b = lbuckets[bucketNumber];
+ b = lbuckets[bucketNumber];
// The contention between reader and writer shouldn't happen frequently.
// But just in case this will burn CPU, yield the control of CPU if we spinned a few times.
// 8 is just a random number I pick.
- if( (++spinCount) % 8 == 0 ) {
+ if ((++spinCount) % 8 == 0)
+ {
Thread.Sleep(1); // 1 means we are yeilding control to all threads, including low-priority ones.
}
- } while ( isWriterInProgress || (currentversion != version) );
+ } while (isWriterInProgress || (currentversion != version));
- if (b.key == null) {
+ if (b.key == null)
+ {
return null;
}
- if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
- KeyEquals (b.key, key))
+ if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
+ KeyEquals(b.key, key))
return b.val;
- bucketNumber = (int) (((long)bucketNumber + incr)% (uint)lbuckets.Length);
+ bucketNumber = (int)(((long)bucketNumber + incr) % (uint)lbuckets.Length);
} while (b.hash_coll < 0 && ++ntry < lbuckets.Length);
return null;
}
- set {
+ set
+ {
Insert(key, value, false);
}
}
-
+
// Increases the bucket count of this hashtable. This method is called from
// the Insert method when the actual load factor of the hashtable reaches
// the upper limit specified when the hashtable was constructed. The number
@@ -495,27 +531,30 @@ namespace System.Collections {
// that is larger than twice the current number of buckets, and the entries
// in the hashtable are redistributed into the new buckets using the cached
// hashcodes.
- private void expand() {
+ private void expand()
+ {
int rawsize = HashHelpers.ExpandPrime(buckets.Length);
rehash(rawsize, false);
}
// We occationally need to rehash the table to clean up the collision bits.
- private void rehash() {
- rehash( buckets.Length, false );
+ private void rehash()
+ {
+ rehash(buckets.Length, false);
}
- private void UpdateVersion() {
+ private void UpdateVersion()
+ {
// Version might become negative when version is Int32.MaxValue, but the oddity will be still be correct.
// So we don't need to special case this.
version++;
}
- private void rehash( int newsize, bool forceNewHashCode ) {
-
+ private void rehash(int newsize, bool forceNewHashCode)
+ {
// reset occupancy
- occupancy=0;
-
+ occupancy = 0;
+
// Don't replace any internal state until we've finished adding to the
// new bucket[]. This serves two purposes:
// 1) Allow concurrent readers to see valid hashtable contents
@@ -523,12 +562,14 @@ namespace System.Collections {
// 2) Protect against an OutOfMemoryException while allocating this
// new bucket[].
bucket[] newBuckets = new bucket[newsize];
-
+
// rehash table into new buckets
int nb;
- for (nb = 0; nb < buckets.Length; nb++){
+ for (nb = 0; nb < buckets.Length; nb++)
+ {
bucket oldb = buckets[nb];
- if ((oldb.key != null) && (oldb.key != buckets)) {
+ if ((oldb.key != null) && (oldb.key != buckets))
+ {
int hashcode = ((forceNewHashCode ? GetHash(oldb.key) : oldb.hash_coll) & 0x7FFFFFFF);
putEntry(newBuckets, oldb.key, oldb.val, hashcode);
}
@@ -551,7 +592,8 @@ namespace System.Collections {
// in progress, the MoveNext and Current methods of the
// enumerator will throw an exception.
//
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
}
@@ -560,10 +602,11 @@ namespace System.Collections {
// in progress, the MoveNext and Current methods of the
// enumerator will throw an exception.
//
- public virtual IDictionaryEnumerator GetEnumerator() {
+ public virtual IDictionaryEnumerator GetEnumerator()
+ {
return new HashtableEnumerator(this, HashtableEnumerator.DictEntry);
}
-
+
// Internal method to get the hash code for an Object. This will call
// GetHashCode() on each object if you haven't provided an IHashCodeProvider
// instance. Otherwise, it calls hcp.GetHashCode(obj).
@@ -575,16 +618,19 @@ namespace System.Collections {
}
// Is this Hashtable read-only?
- public virtual bool IsReadOnly {
+ public virtual bool IsReadOnly
+ {
get { return false; }
}
- public virtual bool IsFixedSize {
+ public virtual bool IsFixedSize
+ {
get { return false; }
}
// Is this Hashtable synchronized? See SyncRoot property
- public virtual bool IsSynchronized {
+ public virtual bool IsSynchronized
+ {
get { return false; }
}
@@ -595,11 +641,12 @@ namespace System.Collections {
protected virtual bool KeyEquals(Object item, Object key)
{
Debug.Assert(key != null, "key can't be null here!");
- if( Object.ReferenceEquals(buckets, item)) {
+ if (Object.ReferenceEquals(buckets, item))
+ {
return false;
}
- if (Object.ReferenceEquals(item,key))
+ if (Object.ReferenceEquals(item, key))
return true;
if (_keycomparer != null)
@@ -616,13 +663,15 @@ namespace System.Collections {
// to the hash table are reflected in this collection. It is not
// a static copy of all the keys in the hash table.
//
- public virtual ICollection Keys {
- get {
+ public virtual ICollection Keys
+ {
+ get
+ {
if (keys == null) keys = new KeyCollection(this);
- return keys;
+ return keys;
}
}
-
+
// Returns a collection representing the values of this hashtable. The
// order in which the returned collection represents the values is
// unspecified, but it is guaranteed to be the same order in which a
@@ -633,39 +682,45 @@ namespace System.Collections {
// to the hash table are reflected in this collection. It is not
// a static copy of all the keys in the hash table.
//
- public virtual ICollection Values {
- get {
+ public virtual ICollection Values
+ {
+ get
+ {
if (values == null) values = new ValueCollection(this);
- return values;
+ return values;
}
}
-
+
// Inserts an entry into this hashtable. This method is called from the Set
// and Add methods. If the add parameter is true and the given key already
// exists in the hashtable, an exception is thrown.
- private void Insert (Object key, Object nvalue, bool add) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ private void Insert(Object key, Object nvalue, bool add)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
- if (count >= loadsize) {
+ if (count >= loadsize)
+ {
expand();
}
- else if(occupancy > loadsize && count > 100) {
+ else if (occupancy > loadsize && count > 100)
+ {
rehash();
}
-
+
uint seed;
uint incr;
// Assume we only have one thread writing concurrently. Modify
// buckets to contain new data, as long as we insert in the right order.
uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
- int ntry = 0;
+ int ntry = 0;
int emptySlotNumber = -1; // We use the empty slot number to cache the first empty slot. We chose to reuse slots
// create by remove that have the collision bit set over using up new slots.
- int bucketNumber = (int) (seed % (uint)buckets.Length);
- do {
-
+ int bucketNumber = (int)(seed % (uint)buckets.Length);
+ do
+ {
// Set emptySlot number to current bucket if it is the first available bucket that we have seen
// that once contained an entry and also has had a collision.
// We need to search this entire collision chain because we have to ensure that there are no
@@ -676,9 +731,9 @@ namespace System.Collections {
// Insert the key/value pair into this bucket if this bucket is empty and has never contained an entry
// OR
// This bucket once contained an entry but there has never been a collision
- if ((buckets[bucketNumber].key == null) ||
- (buckets[bucketNumber].key == buckets && ((buckets[bucketNumber].hash_coll & unchecked(0x80000000))==0))) {
-
+ if ((buckets[bucketNumber].key == null) ||
+ (buckets[bucketNumber].key == buckets && ((buckets[bucketNumber].hash_coll & unchecked(0x80000000)) == 0)))
+ {
// If we have found an available bucket that has never had a collision, but we've seen an available
// bucket in the past that has the collision bit set, use the previous bucket instead
if (emptySlotNumber != -1) // Reuse slot
@@ -688,11 +743,11 @@ namespace System.Collections {
// code until the value & key are set appropriately.
isWriterInProgress = true;
buckets[bucketNumber].val = nvalue;
- buckets[bucketNumber].key = key;
- buckets[bucketNumber].hash_coll |= (int) hashcode;
+ buckets[bucketNumber].key = key;
+ buckets[bucketNumber].hash_coll |= (int)hashcode;
count++;
UpdateVersion();
- isWriterInProgress = false;
+ isWriterInProgress = false;
return;
}
@@ -700,29 +755,33 @@ namespace System.Collections {
// The current bucket is in use
// OR
// it is available, but has had the collision bit set and we have already found an available bucket
- if (((buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) &&
- KeyEquals (buckets[bucketNumber].key, key)) {
- if (add) {
- throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", buckets[bucketNumber].key, key));
+ if (((buckets[bucketNumber].hash_coll & 0x7FFFFFFF) == hashcode) &&
+ KeyEquals(buckets[bucketNumber].key, key))
+ {
+ if (add)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, buckets[bucketNumber].key, key));
}
isWriterInProgress = true;
buckets[bucketNumber].val = nvalue;
UpdateVersion();
- isWriterInProgress = false;
+ isWriterInProgress = false;
return;
}
// The current bucket is full, and we have therefore collided. We need to set the collision bit
// UNLESS
// we have remembered an available slot previously.
- if (emptySlotNumber == -1) {// We don't need to set the collision bit here since we already have an empty slot
- if( buckets[bucketNumber].hash_coll >= 0 ) {
+ if (emptySlotNumber == -1)
+ {// We don't need to set the collision bit here since we already have an empty slot
+ if (buckets[bucketNumber].hash_coll >= 0)
+ {
buckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
occupancy++;
}
}
- bucketNumber = (int) (((long)bucketNumber + incr)% (uint)buckets.Length);
+ bucketNumber = (int)(((long)bucketNumber + incr) % (uint)buckets.Length);
} while (++ntry < buckets.Length);
// This code is here if and only if there were no buckets without a collision bit set in the entire table
@@ -732,11 +791,11 @@ namespace System.Collections {
// code until the value & key are set appropriately.
isWriterInProgress = true;
buckets[emptySlotNumber].val = nvalue;
- buckets[emptySlotNumber].key = key;
- buckets[emptySlotNumber].hash_coll |= (int) hashcode;
+ buckets[emptySlotNumber].key = key;
+ buckets[emptySlotNumber].hash_coll |= (int)hashcode;
count++;
- UpdateVersion();
- isWriterInProgress = false;
+ UpdateVersion();
+ isWriterInProgress = false;
return;
}
@@ -745,40 +804,44 @@ namespace System.Collections {
// Then verify that our double hash function (h2, described at top of file)
// meets the requirements described above. You should never see this assert.
Debug.Assert(false, "hash table insert failed! Load factor too high, or our double hashing function is incorrect.");
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HashInsertFailed"));
+ throw new InvalidOperationException(SR.InvalidOperation_HashInsertFailed);
}
-
- private void putEntry (bucket[] newBuckets, Object key, Object nvalue, int hashcode)
+
+ private void putEntry(bucket[] newBuckets, Object key, Object nvalue, int hashcode)
{
Debug.Assert(hashcode >= 0, "hashcode >= 0"); // make sure collision bit (sign bit) wasn't set.
- uint seed = (uint) hashcode;
+ uint seed = (uint)hashcode;
uint incr = (uint)(1 + ((seed * HashPrime) % ((uint)newBuckets.Length - 1)));
- int bucketNumber = (int) (seed % (uint)newBuckets.Length);
- do {
-
- if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == buckets)) {
+ int bucketNumber = (int)(seed % (uint)newBuckets.Length);
+ do
+ {
+ if ((newBuckets[bucketNumber].key == null) || (newBuckets[bucketNumber].key == buckets))
+ {
newBuckets[bucketNumber].val = nvalue;
newBuckets[bucketNumber].key = key;
newBuckets[bucketNumber].hash_coll |= hashcode;
return;
}
-
- if( newBuckets[bucketNumber].hash_coll >= 0 ) {
- newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
+
+ if (newBuckets[bucketNumber].hash_coll >= 0)
+ {
+ newBuckets[bucketNumber].hash_coll |= unchecked((int)0x80000000);
occupancy++;
}
- bucketNumber = (int) (((long)bucketNumber + incr)% (uint)newBuckets.Length);
+ bucketNumber = (int)(((long)bucketNumber + incr) % (uint)newBuckets.Length);
} while (true);
}
-
+
// Removes an entry from this hashtable. If an entry with the specified
// key exists in the hashtable, it is removed. An ArgumentException is
// thrown if the key is null.
//
- public virtual void Remove(Object key) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public virtual void Remove(Object key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
Debug.Assert(!isWriterInProgress, "Race condition detected in usages of Hashtable - multiple threads appear to be writing to a Hashtable instance simultaneously! Don't do that - use Hashtable.Synchronized.");
@@ -788,124 +851,135 @@ namespace System.Collections {
// Assuming only one concurrent writer, write directly into buckets.
uint hashcode = InitHash(key, buckets.Length, out seed, out incr);
int ntry = 0;
-
+
bucket b;
- int bn = (int) (seed % (uint)buckets.Length); // bucketNumber
- do {
+ int bn = (int)(seed % (uint)buckets.Length); // bucketNumber
+ do
+ {
b = buckets[bn];
- if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
- KeyEquals (b.key, key)) {
+ if (((b.hash_coll & 0x7FFFFFFF) == hashcode) &&
+ KeyEquals(b.key, key))
+ {
isWriterInProgress = true;
// Clear hash_coll field, then key, then value
buckets[bn].hash_coll &= unchecked((int)0x80000000);
- if (buckets[bn].hash_coll != 0) {
+ if (buckets[bn].hash_coll != 0)
+ {
buckets[bn].key = buckets;
- }
- else {
+ }
+ else
+ {
buckets[bn].key = null;
}
buckets[bn].val = null; // Free object references sooner & simplify ContainsValue.
count--;
UpdateVersion();
- isWriterInProgress = false;
+ isWriterInProgress = false;
return;
}
- bn = (int) (((long)bn + incr)% (uint)buckets.Length);
+ bn = (int)(((long)bn + incr) % (uint)buckets.Length);
} while (b.hash_coll < 0 && ++ntry < buckets.Length);
- //throw new ArgumentException(Environment.GetResourceString("Arg_RemoveArgNotFound"));
+ //throw new ArgumentException(SR.Arg_RemoveArgNotFound);
}
-
+
// Returns the object to synchronize on for this hash table.
- public virtual Object SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ public virtual Object SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
- return _syncRoot;
+ return _syncRoot;
}
}
-
+
// Returns the number of associations in this hashtable.
//
- public virtual int Count {
+ public virtual int Count
+ {
get { return count; }
}
-
+
// Returns a thread-safe wrapper for a Hashtable.
//
- public static Hashtable Synchronized(Hashtable table) {
- if (table==null)
+ public static Hashtable Synchronized(Hashtable table)
+ {
+ if (table == null)
throw new ArgumentNullException(nameof(table));
Contract.EndContractBlock();
return new SyncHashtable(table);
}
-
+
//
// The ISerializable Implementation
//
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
// This is imperfect - it only works well if all other writes are
// also using our synchronized wrapper. But it's still a good idea.
- lock (SyncRoot) {
+ lock (SyncRoot)
+ {
// This method hasn't been fully tweaked to be safe for a concurrent writer.
int oldVersion = version;
- info.AddValue(LoadFactorName, loadFactor);
- info.AddValue(VersionName, version);
-
- //
- // We need to maintain serialization compatibility with Everett and RTM.
- // If the comparer is null or a compatible comparer, serialize Hashtable
- // in a format that can be deserialized on Everett and RTM.
- //
- // Also, if the Hashtable is using randomized hashing, serialize the old
- // view of the _keycomparer so perevious frameworks don't see the new types
+ info.AddValue(LoadFactorName, loadFactor);
+ info.AddValue(VersionName, version);
+
+ //
+ // We need to maintain serialization compatibility with Everett and RTM.
+ // If the comparer is null or a compatible comparer, serialize Hashtable
+ // in a format that can be deserialized on Everett and RTM.
+ //
#pragma warning disable 618
-#if FEATURE_RANDOMIZED_STRING_HASHING
- IEqualityComparer keyComparerForSerilization = (IEqualityComparer) HashHelpers.GetEqualityComparerForSerialization(_keycomparer);
-#else
- IEqualityComparer keyComparerForSerilization = _keycomparer;
-#endif
+ IEqualityComparer keyComparerForSerilization = _keycomparer;
- if( keyComparerForSerilization == null) {
- info.AddValue(ComparerName, null,typeof(IComparer));
- info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
- }
- else if(keyComparerForSerilization is CompatibleComparer) {
- CompatibleComparer c = keyComparerForSerilization as CompatibleComparer;
- info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
- info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
- }
- else {
- info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer));
- }
+ if (keyComparerForSerilization == null)
+ {
+ info.AddValue(ComparerName, null, typeof(IComparer));
+ info.AddValue(HashCodeProviderName, null, typeof(IHashCodeProvider));
+ }
+ else if (keyComparerForSerilization is CompatibleComparer)
+ {
+ CompatibleComparer c = keyComparerForSerilization as CompatibleComparer;
+ info.AddValue(ComparerName, c.Comparer, typeof(IComparer));
+ info.AddValue(HashCodeProviderName, c.HashCodeProvider, typeof(IHashCodeProvider));
+ }
+ else
+ {
+ info.AddValue(KeyComparerName, keyComparerForSerilization, typeof(IEqualityComparer));
+ }
#pragma warning restore 618
- info.AddValue(HashSizeName, buckets.Length); //This is the length of the bucket array.
- Object [] serKeys = new Object[count];
- Object [] serValues = new Object[count];
- CopyKeys(serKeys, 0);
- CopyValues(serValues,0);
- info.AddValue(KeysName, serKeys, typeof(Object[]));
- info.AddValue(ValuesName, serValues, typeof(Object[]));
+ info.AddValue(HashSizeName, buckets.Length); //This is the length of the bucket array.
+ Object[] serKeys = new Object[count];
+ Object[] serValues = new Object[count];
+ CopyKeys(serKeys, 0);
+ CopyValues(serValues, 0);
+ info.AddValue(KeysName, serKeys, typeof(Object[]));
+ info.AddValue(ValuesName, serValues, typeof(Object[]));
// Explicitly check to see if anyone changed the Hashtable while we
// were serializing it. That's a race condition in their code.
if (version != oldVersion)
- throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- }
+ throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
+ }
}
-
+
//
// DeserializationEvent Listener
//
- public virtual void OnDeserialization(Object sender) {
- if (buckets!=null) {
+ public virtual void OnDeserialization(Object sender)
+ {
+ if (buckets != null)
+ {
// Somebody had a dependency on this hashtable and fixed us up before the ObjectManager got to it.
return;
}
@@ -913,8 +987,9 @@ namespace System.Collections {
SerializationInfo siInfo;
HashHelpers.SerializationInfoTable.TryGetValue(this, out siInfo);
- if (siInfo==null) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidOnDeser"));
+ if (siInfo == null)
+ {
+ throw new SerializationException(SR.Serialization_InvalidOnDeser);
}
int hashsize = 0;
@@ -924,14 +999,14 @@ namespace System.Collections {
IHashCodeProvider hcp = null;
#pragma warning restore 618
- Object [] serKeys = null;
- Object [] serValues = null;
+ Object[] serKeys = null;
+ Object[] serValues = null;
SerializationInfoEnumerator enumerator = siInfo.GetEnumerator();
- while( enumerator.MoveNext())
+ while (enumerator.MoveNext())
{
- switch( enumerator.Name)
+ switch (enumerator.Name)
{
case LoadFactorName:
loadFactor = siInfo.GetSingle(LoadFactorName);
@@ -939,7 +1014,7 @@ namespace System.Collections {
case HashSizeName:
hashsize = siInfo.GetInt32(HashSizeName);
break;
- case KeyComparerName:
+ case KeyComparerName:
_keycomparer = (IEqualityComparer)siInfo.GetValue(KeyComparerName, typeof(IEqualityComparer));
break;
case ComparerName:
@@ -959,129 +1034,148 @@ namespace System.Collections {
}
}
- loadsize = (int)(loadFactor*hashsize);
+ loadsize = (int)(loadFactor * hashsize);
// V1 object doesn't has _keycomparer field.
- if ( (_keycomparer == null) && ( (c != null) || (hcp != null) ) ){
- _keycomparer = new CompatibleComparer(c,hcp);
+ if ((_keycomparer == null) && ((c != null) || (hcp != null)))
+ {
+ _keycomparer = new CompatibleComparer(c, hcp);
}
buckets = new bucket[hashsize];
-
- if (serKeys==null) {
- throw new SerializationException(Environment.GetResourceString("Serialization_MissingKeys"));
+
+ if (serKeys == null)
+ {
+ throw new SerializationException(SR.Serialization_MissingKeys);
}
- if (serValues==null) {
- throw new SerializationException(Environment.GetResourceString("Serialization_MissingValues"));
+ if (serValues == null)
+ {
+ throw new SerializationException(SR.Serialization_MissingValues);
}
- if (serKeys.Length!=serValues.Length) {
- throw new SerializationException(Environment.GetResourceString("Serialization_KeyValueDifferentSizes"));
+ if (serKeys.Length != serValues.Length)
+ {
+ throw new SerializationException(SR.Serialization_KeyValueDifferentSizes);
}
- for (int i=0; i<serKeys.Length; i++) {
- if (serKeys[i]==null) {
- throw new SerializationException(Environment.GetResourceString("Serialization_NullKey"));
+ for (int i = 0; i < serKeys.Length; i++)
+ {
+ if (serKeys[i] == null)
+ {
+ throw new SerializationException(SR.Serialization_NullKey);
}
Insert(serKeys[i], serValues[i], true);
}
-
+
version = siInfo.GetInt32(VersionName);
-
+
HashHelpers.SerializationInfoTable.Remove(this);
}
-
-
+
+
// Implements a Collection for the keys of a hashtable. An instance of this
// class is created by the GetKeys method of a hashtable.
[Serializable]
private class KeyCollection : ICollection
{
private Hashtable _hashtable;
-
- internal KeyCollection(Hashtable hashtable) {
+
+ internal KeyCollection(Hashtable hashtable)
+ {
_hashtable = hashtable;
}
-
- public virtual void CopyTo(Array array, int arrayIndex) {
- if (array==null)
+
+ public virtual void CopyTo(Array array, int arrayIndex)
+ {
+ if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
+ if (arrayIndex < 0)
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (array.Length - arrayIndex < _hashtable.count)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
+ throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
_hashtable.CopyKeys(array, arrayIndex);
}
-
- public virtual IEnumerator GetEnumerator() {
+
+ public virtual IEnumerator GetEnumerator()
+ {
return new HashtableEnumerator(_hashtable, HashtableEnumerator.Keys);
}
-
- public virtual bool IsSynchronized {
+
+ public virtual bool IsSynchronized
+ {
get { return _hashtable.IsSynchronized; }
}
- public virtual Object SyncRoot {
+ public virtual Object SyncRoot
+ {
get { return _hashtable.SyncRoot; }
}
- public virtual int Count {
+ public virtual int Count
+ {
get { return _hashtable.count; }
}
}
-
+
// Implements a Collection for the values of a hashtable. An instance of
// this class is created by the GetValues method of a hashtable.
[Serializable]
private class ValueCollection : ICollection
{
private Hashtable _hashtable;
-
- internal ValueCollection(Hashtable hashtable) {
+
+ internal ValueCollection(Hashtable hashtable)
+ {
_hashtable = hashtable;
}
-
- public virtual void CopyTo(Array array, int arrayIndex) {
- if (array==null)
+
+ public virtual void CopyTo(Array array, int arrayIndex)
+ {
+ if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
- if (arrayIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(arrayIndex), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
+ if (arrayIndex < 0)
+ throw new ArgumentOutOfRangeException(nameof(arrayIndex), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (array.Length - arrayIndex < _hashtable.count)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayPlusOffTooSmall"));
+ throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
_hashtable.CopyValues(array, arrayIndex);
}
-
- public virtual IEnumerator GetEnumerator() {
+
+ public virtual IEnumerator GetEnumerator()
+ {
return new HashtableEnumerator(_hashtable, HashtableEnumerator.Values);
}
-
- public virtual bool IsSynchronized {
+
+ public virtual bool IsSynchronized
+ {
get { return _hashtable.IsSynchronized; }
}
- public virtual Object SyncRoot {
+ public virtual Object SyncRoot
+ {
get { return _hashtable.SyncRoot; }
}
- public virtual int Count {
+ public virtual int Count
+ {
get { return _hashtable.count; }
}
}
-
+
// Synchronized wrapper for hashtable
[Serializable]
private class SyncHashtable : Hashtable, IEnumerable
{
protected Hashtable _table;
-
- internal SyncHashtable(Hashtable table) : base(false) {
+
+ internal SyncHashtable(Hashtable table) : base(false)
+ {
_table = table;
}
-
+
/*================================GetObjectData=================================
**Action: Return a serialization info containing a reference to _table. We need
@@ -1093,115 +1187,148 @@ namespace System.Collections {
** context -- the StreamingContext for the current serialization (ignored)
**Exceptions: ArgumentNullException if info is null.
==============================================================================*/
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
// Our serialization code hasn't been fully tweaked to be safe
// for a concurrent writer.
- lock (_table.SyncRoot) {
- info.AddValue("ParentTable", _table, typeof(Hashtable));
- }
+ lock (_table.SyncRoot)
+ {
+ info.AddValue("ParentTable", _table, typeof(Hashtable));
+ }
}
- public override int Count {
+ public override int Count
+ {
get { return _table.Count; }
}
-
- public override bool IsReadOnly {
+
+ public override bool IsReadOnly
+ {
get { return _table.IsReadOnly; }
}
- public override bool IsFixedSize {
+ public override bool IsFixedSize
+ {
get { return _table.IsFixedSize; }
}
-
- public override bool IsSynchronized {
+
+ public override bool IsSynchronized
+ {
get { return true; }
}
- public override Object this[Object key] {
- get {
- return _table[key];
+ public override Object this[Object key]
+ {
+ get
+ {
+ return _table[key];
}
- set {
- lock(_table.SyncRoot) {
+ set
+ {
+ lock (_table.SyncRoot)
+ {
_table[key] = value;
}
}
}
-
- public override Object SyncRoot {
+
+ public override Object SyncRoot
+ {
get { return _table.SyncRoot; }
}
-
- public override void Add(Object key, Object value) {
- lock(_table.SyncRoot) {
+
+ public override void Add(Object key, Object value)
+ {
+ lock (_table.SyncRoot)
+ {
_table.Add(key, value);
}
}
-
- public override void Clear() {
- lock(_table.SyncRoot) {
+
+ public override void Clear()
+ {
+ lock (_table.SyncRoot)
+ {
_table.Clear();
}
}
-
- public override bool Contains(Object key) {
+
+ public override bool Contains(Object key)
+ {
return _table.Contains(key);
}
-
- public override bool ContainsKey(Object key) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+
+ public override bool ContainsKey(Object key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
return _table.ContainsKey(key);
}
-
- public override void CopyTo(Array array, int arrayIndex) {
- lock (_table.SyncRoot) {
+
+ public override void CopyTo(Array array, int arrayIndex)
+ {
+ lock (_table.SyncRoot)
+ {
_table.CopyTo(array, arrayIndex);
}
}
- public override Object Clone() {
- lock (_table.SyncRoot) {
+ public override Object Clone()
+ {
+ lock (_table.SyncRoot)
+ {
return Hashtable.Synchronized((Hashtable)_table.Clone());
}
}
-
- IEnumerator IEnumerable.GetEnumerator() {
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return _table.GetEnumerator();
}
-
- public override IDictionaryEnumerator GetEnumerator() {
+
+ public override IDictionaryEnumerator GetEnumerator()
+ {
return _table.GetEnumerator();
}
-
- public override ICollection Keys {
- get {
- lock(_table.SyncRoot) {
+
+ public override ICollection Keys
+ {
+ get
+ {
+ lock (_table.SyncRoot)
+ {
return _table.Keys;
}
}
}
-
- public override ICollection Values {
- get {
- lock(_table.SyncRoot) {
+
+ public override ICollection Values
+ {
+ get
+ {
+ lock (_table.SyncRoot)
+ {
return _table.Values;
}
}
}
-
- public override void Remove(Object key) {
- lock(_table.SyncRoot) {
+
+ public override void Remove(Object key)
+ {
+ lock (_table.SyncRoot)
+ {
_table.Remove(key);
}
}
-
+
/*==============================OnDeserialization===============================
**Action: Does nothing. We have to implement this because our parent HT implements it,
** but it doesn't do anything meaningful. The real work will be done when we
@@ -1210,13 +1337,13 @@ namespace System.Collections {
**Arguments: None
**Exceptions: None
==============================================================================*/
- public override void OnDeserialization(Object sender) {
+ public override void OnDeserialization(Object sender)
+ {
return;
}
-
}
-
-
+
+
// Implements an enumerator for a hashtable. The enumerator uses the
// internal version number of the hashtabke to ensure that no modifications
// are made to the hashtable while an enumeration is in progress.
@@ -1230,12 +1357,13 @@ namespace System.Collections {
private int getObjectRetType; // What should GetObject return?
private Object currentKey;
private Object currentValue;
-
+
internal const int Keys = 1;
internal const int Values = 2;
internal const int DictEntry = 3;
-
- internal HashtableEnumerator(Hashtable hashtable, int getObjRetType) {
+
+ internal HashtableEnumerator(Hashtable hashtable, int getObjRetType)
+ {
this.hashtable = hashtable;
bucket = hashtable.buckets.Length;
version = hashtable.version;
@@ -1243,23 +1371,29 @@ namespace System.Collections {
getObjectRetType = getObjRetType;
}
- public Object Clone() {
+ public Object Clone()
+ {
return MemberwiseClone();
}
-
- public virtual Object Key {
- get {
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
+
+ public virtual Object Key
+ {
+ get
+ {
+ if (current == false) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
return currentKey;
}
}
-
- public virtual bool MoveNext() {
- if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
- while (bucket > 0) {
+
+ public virtual bool MoveNext()
+ {
+ if (version != hashtable.version) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
+ while (bucket > 0)
+ {
bucket--;
Object keyv = hashtable.buckets[bucket].key;
- if ((keyv!= null) && (keyv != hashtable.buckets)) {
+ if ((keyv != null) && (keyv != hashtable.buckets))
+ {
currentKey = keyv;
currentValue = hashtable.buckets[bucket].val;
current = true;
@@ -1269,54 +1403,61 @@ namespace System.Collections {
current = false;
return false;
}
-
- public virtual DictionaryEntry Entry {
- get {
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
+
+ public virtual DictionaryEntry Entry
+ {
+ get
+ {
+ if (current == false) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
return new DictionaryEntry(currentKey, currentValue);
}
}
-
-
- public virtual Object Current {
- get {
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
-
- if (getObjectRetType==Keys)
+
+
+ public virtual Object Current
+ {
+ get
+ {
+ if (current == false) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
+
+ if (getObjectRetType == Keys)
return currentKey;
- else if (getObjectRetType==Values)
+ else if (getObjectRetType == Values)
return currentValue;
- else
+ else
return new DictionaryEntry(currentKey, currentValue);
}
}
-
- public virtual Object Value {
- get {
- if (current == false) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
+
+ public virtual Object Value
+ {
+ get
+ {
+ if (current == false) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumOpCantHappen));
return currentValue;
}
}
-
- public virtual void Reset() {
- if (version != hashtable.version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
+
+ public virtual void Reset()
+ {
+ if (version != hashtable.version) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumFailedVersion));
current = false;
bucket = hashtable.buckets.Length;
currentKey = null;
currentValue = null;
}
}
-
+
// internal debug view class for hashtable
- internal class HashtableDebugView {
- private Hashtable hashtable;
- }
+ internal class HashtableDebugView
+ {
+ private Hashtable hashtable;
+ }
}
[FriendAccessAllowed]
internal static class HashHelpers
{
-
#if FEATURE_RANDOMIZED_STRING_HASHING
public const int HashCollisionThreshold = 100;
public static bool s_UseRandomizedStringHashing = String.UseRandomizedHashing();
@@ -1344,11 +1485,11 @@ namespace System.Collections {
// object until OnDeserialization is called.
private static ConditionalWeakTable<object, SerializationInfo> s_SerializationInfoTable;
- internal static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable
- {
- get
- {
- if(s_SerializationInfoTable == null)
+ internal static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable
+ {
+ get
+ {
+ if (s_SerializationInfoTable == null)
{
ConditionalWeakTable<object, SerializationInfo> newTable = new ConditionalWeakTable<object, SerializationInfo>();
Interlocked.CompareExchange(ref s_SerializationInfoTable, newTable, null);
@@ -1356,15 +1497,14 @@ namespace System.Collections {
return s_SerializationInfoTable;
}
-
}
- public static bool IsPrime(int candidate)
+ public static bool IsPrime(int candidate)
{
- if ((candidate & 1) != 0)
+ if ((candidate & 1) != 0)
{
- int limit = (int)Math.Sqrt (candidate);
- for (int divisor = 3; divisor <= limit; divisor+=2)
+ int limit = (int)Math.Sqrt(candidate);
+ for (int divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
@@ -1374,13 +1514,13 @@ namespace System.Collections {
return (candidate == 2);
}
- public static int GetPrime(int min)
+ public static int GetPrime(int min)
{
if (min < 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_HTCapacityOverflow"));
+ throw new ArgumentException(SR.Arg_HTCapacityOverflow);
Contract.EndContractBlock();
- for (int i = 0; i < primes.Length; i++)
+ for (int i = 0; i < primes.Length; i++)
{
int prime = primes[i];
if (prime >= min) return prime;
@@ -1388,7 +1528,7 @@ namespace System.Collections {
//outside of our predefined table.
//compute the hard way.
- for (int i = (min | 1); i < Int32.MaxValue;i+=2)
+ for (int i = (min | 1); i < Int32.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % Hashtable.HashPrime != 0))
return i;
@@ -1405,7 +1545,7 @@ namespace System.Collections {
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
{
- Debug.Assert( MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
+ Debug.Assert(MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
return MaxPrimeArrayLength;
}
@@ -1415,29 +1555,5 @@ namespace System.Collections {
// This is the maximum prime smaller than Array.MaxArrayLength
public const int MaxPrimeArrayLength = 0x7FEFFFFD;
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-
- public static object GetEqualityComparerForSerialization(object comparer)
- {
- if(comparer == null)
- {
- return null;
- }
-
- IWellKnownStringEqualityComparer cmp = comparer as IWellKnownStringEqualityComparer;
-
- if(cmp != null)
- {
- return cmp.GetEqualityComparerForSerialization();
- }
-
- return comparer;
- }
-
- private const int bufferSize = 1024;
- private static int currentIndex = bufferSize;
- private static readonly object lockObj = new Object();
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
}
diff --git a/src/mscorlib/src/System/Collections/ICollection.cs b/src/mscorlib/src/System/Collections/ICollection.cs
deleted file mode 100644
index 088928a0ef..0000000000
--- a/src/mscorlib/src/System/Collections/ICollection.cs
+++ /dev/null
@@ -1,80 +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.
-
-/*============================================================
-**
-** Interface: ICollection
-**
-**
-**
-**
-** Purpose: Base interface for all collections.
-**
-**
-===========================================================*/
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
-
- // Base interface for all collections, defining enumerators, size, and
- // synchronization methods.
- public interface ICollection : IEnumerable
- {
- // Interfaces are not serialable
- // CopyTo copies a collection into an Array, starting at a particular
- // index into the array.
- //
- void CopyTo(Array array, int index);
-
- // Number of items in the collections.
- int Count
- { get; }
-
-
- // SyncRoot will return an Object to use for synchronization
- // (thread safety). You can use this object in your code to take a
- // lock on the collection, even if this collection is a wrapper around
- // another collection. The intent is to tunnel through to a real
- // implementation of a collection, and use one of the internal objects
- // found in that code.
- //
- // In the absense of a static Synchronized method on a collection,
- // the expected usage for SyncRoot would look like this:
- //
- // ICollection col = ...
- // lock (col.SyncRoot) {
- // // Some operation on the collection, which is now thread safe.
- // // This may include multiple operations.
- // }
- //
- //
- // The system-provided collections have a static method called
- // Synchronized which will create a thread-safe wrapper around the
- // collection. All access to the collection that you want to be
- // thread-safe should go through that wrapper collection. However, if
- // you need to do multiple calls on that collection (such as retrieving
- // two items, or checking the count then doing something), you should
- // NOT use our thread-safe wrapper since it only takes a lock for the
- // duration of a single method call. Instead, use Monitor.Enter/Exit
- // or your language's equivalent to the C# lock keyword as mentioned
- // above.
- //
- // For collections with no publically available underlying store, the
- // expected implementation is to simply return the this pointer. Note
- // that the this pointer may not be sufficient for collections that
- // wrap other collections; those should return the underlying
- // collection's SyncRoot property.
- Object SyncRoot
- { get; }
-
- // Is this collection synchronized (i.e., thread-safe)? If you want a
- // thread-safe collection, you can use SyncRoot as an object to
- // synchronize your collection with. If you're using one of the
- // collections in System.Collections, you could call the static
- // Synchronized method to get a thread-safe wrapper around the
- // underlying collection.
- bool IsSynchronized
- { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IComparer.cs b/src/mscorlib/src/System/Collections/IComparer.cs
deleted file mode 100644
index 574af1a768..0000000000
--- a/src/mscorlib/src/System/Collections/IComparer.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.
-
-/*============================================================
-**
-** Interface: IComparer
-**
-**
-**
-**
-** Purpose: Interface for comparing two Objects.
-**
-**
-===========================================================*/
-namespace System.Collections {
-
- using System;
- // The IComparer interface implements a method that compares two objects. It is
- // used in conjunction with the Sort and BinarySearch methods on
- // the Array and List classes.
- //
- // Interfaces are not serializable
- public interface IComparer {
- // Compares two objects. An implementation of this method must return a
- // value less than zero if x is less than y, zero if x is equal to y, or a
- // value greater than zero if x is greater than y.
- //
- int Compare(Object x, Object y);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IDictionary.cs b/src/mscorlib/src/System/Collections/IDictionary.cs
deleted file mode 100644
index 519d53ed55..0000000000
--- a/src/mscorlib/src/System/Collections/IDictionary.cs
+++ /dev/null
@@ -1,68 +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.
-
-/*============================================================
-**
-** Interface: IDictionary
-**
-**
-**
-**
-** Purpose: Base interface for all dictionaries.
-**
-**
-===========================================================*/
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
-
- // An IDictionary is a possibly unordered set of key-value pairs.
- // Keys can be any non-null object. Values can be any object.
- // You can look up a value in an IDictionary via the default indexed
- // property, Items.
- public interface IDictionary : ICollection
- {
- // Interfaces are not serializable
- // The Item property provides methods to read and edit entries
- // in the Dictionary.
- Object this[Object key] {
- get;
- set;
- }
-
- // Returns a collections of the keys in this dictionary.
- ICollection Keys {
- get;
- }
-
- // Returns a collections of the values in this dictionary.
- ICollection Values {
- get;
- }
-
- // Returns whether this dictionary contains a particular key.
- //
- bool Contains(Object key);
-
- // Adds a key-value pair to the dictionary.
- //
- void Add(Object key, Object value);
-
- // Removes all pairs from the dictionary.
- void Clear();
-
- bool IsReadOnly
- { get; }
-
- bool IsFixedSize
- { get; }
-
- // Returns an IDictionaryEnumerator for this dictionary.
- new IDictionaryEnumerator GetEnumerator();
-
- // Removes a particular key from the dictionary.
- //
- void Remove(Object key);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs b/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
deleted file mode 100644
index 2f1add682c..0000000000
--- a/src/mscorlib/src/System/Collections/IDictionaryEnumerator.cs
+++ /dev/null
@@ -1,78 +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.
-
-/*============================================================
-**
-** Interface: IDictionaryEnumerator
-**
-**
-**
-**
-** Purpose: Base interface for dictionary enumerators.
-**
-**
-===========================================================*/
-namespace System.Collections {
- // Interfaces are not serializable
-
- using System;
- // This interface represents an enumerator that allows sequential access to the
- // elements of a dictionary. Upon creation, an enumerator is conceptually
- // positioned before the first element of the enumeration. The first call to the
- // MoveNext method brings the first element of the enumeration into view,
- // and each successive call to MoveNext brings the next element into
- // view until MoveNext returns false, indicating that there are no more
- // elements to enumerate. Following each call to MoveNext, the
- // Key and Value methods are used to obtain the key and
- // value of the element currently in view. The values returned by calls to
- // Key and Value are undefined before the first call to
- // MoveNext and following a call to MoveNext that returned false.
- // Enumerators are typically used in while loops of the form
- //
- // IDictionaryEnumerator e = ...;
- // while (e.MoveNext()) {
- // Object key = e.Key;
- // Object value = e.Value;
- // ...
- // }
- //
- // The IDictionaryEnumerator interface extends the IEnumerator
- // inerface and can thus be used as a regular enumerator. The Current
- // method of an IDictionaryEnumerator returns a DictionaryEntry containing
- // the current key and value pair. However, the GetEntry method will
- // return the same DictionaryEntry and avoids boxing the DictionaryEntry (boxing
- // is somewhat expensive).
- //
- public interface IDictionaryEnumerator : IEnumerator
- {
- // Returns the key of the current element of the enumeration. The returned
- // value is undefined before the first call to GetNext and following
- // a call to GetNext that returned false. Multiple calls to
- // GetKey with no intervening calls to GetNext will return
- // the same object.
- //
- Object Key {
- get;
- }
-
- // Returns the value of the current element of the enumeration. The
- // returned value is undefined before the first call to GetNext and
- // following a call to GetNext that returned false. Multiple calls
- // to GetValue with no intervening calls to GetNext will
- // return the same object.
- //
- Object Value {
- get;
- }
-
- // GetBlock will copy dictionary values into the given Array. It will either
- // fill up the array, or if there aren't enough elements, it will
- // copy as much as possible into the Array. The number of elements
- // copied is returned.
- //
- DictionaryEntry Entry {
- get;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IEnumerable.cs b/src/mscorlib/src/System/Collections/IEnumerable.cs
deleted file mode 100644
index 1d8e71cf07..0000000000
--- a/src/mscorlib/src/System/Collections/IEnumerable.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.
-
-/*============================================================
-**
-** Interface: IEnumerable
-**
-**
-**
-**
-** Purpose: Interface for classes providing IEnumerators
-**
-**
-===========================================================*/
-namespace System.Collections {
- using System;
- using System.Diagnostics.Contracts;
- using System.Runtime.InteropServices;
-
- // Implement this interface if you need to support VB's foreach semantics.
- // Also, COM classes that support an enumerator will also implement this interface.
- [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")]
- public interface IEnumerable
- {
- // Interfaces are not serializable
- // Returns an IEnumerator for this enumerable Object. The enumerator provides
- // a simple way to access all the contents of a collection.
- [Pure]
- [DispId(-4)]
- IEnumerator GetEnumerator();
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IEnumerator.cs b/src/mscorlib/src/System/Collections/IEnumerator.cs
deleted file mode 100644
index 4c4fc085e8..0000000000
--- a/src/mscorlib/src/System/Collections/IEnumerator.cs
+++ /dev/null
@@ -1,52 +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.
-
-/*============================================================
-**
-** Interface: IEnumerator
-**
-**
-**
-**
-** Purpose: Base interface for all enumerators.
-**
-**
-===========================================================*/
-namespace System.Collections {
- using System;
- using System.Runtime.InteropServices;
-
- // Base interface for all enumerators, providing a simple approach
- // to iterating over a collection.
- [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")]
- public interface IEnumerator
- {
- // Interfaces are not serializable
- // Advances the enumerator to the next element of the enumeration and
- // returns a boolean indicating whether an element is available. Upon
- // creation, an enumerator is conceptually positioned before the first
- // element of the enumeration, and the first call to MoveNext
- // brings the first element of the enumeration into view.
- //
- bool MoveNext();
-
- // Returns the current element of the enumeration. The returned value is
- // undefined before the first call to MoveNext and following a
- // call to MoveNext that returned false. Multiple calls to
- // GetCurrent with no intervening calls to MoveNext
- // will return the same object.
- //
- Object Current {
- get;
- }
-
- // Resets the enumerator to the beginning of the enumeration, starting over.
- // The preferred behavior for Reset is to return the exact same enumeration.
- // This means if you modify the underlying collection then call Reset, your
- // IEnumerator will be invalid, just as it would have been if you had called
- // MoveNext or Current.
- //
- void Reset();
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IEqualityComparer.cs b/src/mscorlib/src/System/Collections/IEqualityComparer.cs
deleted file mode 100644
index f591b11152..0000000000
--- a/src/mscorlib/src/System/Collections/IEqualityComparer.cs
+++ /dev/null
@@ -1,26 +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.
-
-/*============================================================
-**
-** Interface: IEqualityComparer
-**
-**
-**
-**
-** Purpose: A mechanism to expose a simplified infrastructure for
-** Comparing objects in collections.
-**
-**
-===========================================================*/
-namespace System.Collections {
-
- using System;
- // An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure
- // that can be consumed by some of the common collections.
- public interface IEqualityComparer {
- bool Equals(Object x, Object y);
- int GetHashCode(Object obj);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IHashCodeProvider.cs b/src/mscorlib/src/System/Collections/IHashCodeProvider.cs
index 0ae1e3295b..fa4738ab64 100644
--- a/src/mscorlib/src/System/Collections/IHashCodeProvider.cs
+++ b/src/mscorlib/src/System/Collections/IHashCodeProvider.cs
@@ -13,17 +13,19 @@
**
**
===========================================================*/
-namespace System.Collections {
-
- using System;
+
+using System;
+
+namespace System.Collections
+{
// Provides a mechanism for a hash table user to override the default
// GetHashCode() function on Objects, providing their own hash function.
[Obsolete("Please use IEqualityComparer instead.")]
- internal interface IHashCodeProvider
+ internal interface IHashCodeProvider
{
// Interfaces are not serializable
// Returns a hash code for the given object.
//
- int GetHashCode (Object obj);
+ int GetHashCode(Object obj);
}
}
diff --git a/src/mscorlib/src/System/Collections/IList.cs b/src/mscorlib/src/System/Collections/IList.cs
deleted file mode 100644
index 8b63400852..0000000000
--- a/src/mscorlib/src/System/Collections/IList.cs
+++ /dev/null
@@ -1,70 +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.
-
-/*============================================================
-**
-** Interface: IList
-**
-**
-**
-**
-** Purpose: Base interface for all Lists.
-**
-**
-===========================================================*/
-namespace System.Collections {
-
- using System;
- using System.Diagnostics.Contracts;
-
- // An IList is an ordered collection of objects. The exact ordering
- // is up to the implementation of the list, ranging from a sorted
- // order to insertion order.
- public interface IList : ICollection
- {
- // The Item property provides methods to read and edit entries in the List.
- Object this[int index] {
- get;
- set;
- }
-
- // Adds an item to the list. The exact position in the list is
- // implementation-dependent, so while ArrayList may always insert
- // in the last available location, a SortedList most likely would not.
- // The return value is the position the new element was inserted in.
- int Add(Object value);
-
- // Returns whether the list contains a particular item.
- bool Contains(Object value);
-
- // Removes all items from the list.
- void Clear();
-
- bool IsReadOnly
- { get; }
-
-
- bool IsFixedSize
- {
- get;
- }
-
-
- // Returns the index of a particular item, if it is in the list.
- // Returns -1 if the item isn't in the list.
- int IndexOf(Object value);
-
- // Inserts value into the list at position index.
- // index must be non-negative and less than or equal to the
- // number of elements in the list. If index equals the number
- // of items in the list, then value is appended to the end.
- void Insert(int index, Object value);
-
- // Removes an item from the list.
- void Remove(Object value);
-
- // Removes the item at position index.
- void RemoveAt(int index);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IStructuralComparable.cs b/src/mscorlib/src/System/Collections/IStructuralComparable.cs
deleted file mode 100644
index 1b6f3aff7a..0000000000
--- a/src/mscorlib/src/System/Collections/IStructuralComparable.cs
+++ /dev/null
@@ -1,11 +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;
-
-namespace System.Collections {
-
- public interface IStructuralComparable {
- Int32 CompareTo(Object other, IComparer comparer);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/IStructuralEquatable.cs b/src/mscorlib/src/System/Collections/IStructuralEquatable.cs
deleted file mode 100644
index 5a5295fc38..0000000000
--- a/src/mscorlib/src/System/Collections/IStructuralEquatable.cs
+++ /dev/null
@@ -1,10 +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.
-namespace System.Collections {
-
- public interface IStructuralEquatable {
- Boolean Equals(Object other, IEqualityComparer comparer);
- int GetHashCode(IEqualityComparer comparer);
- }
-}
diff --git a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs b/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
index 617c33707a..3f92038d4f 100644
--- a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
+++ b/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
@@ -11,55 +11,70 @@
**
**
===========================================================*/
+
using System.Diagnostics.Contracts;
-namespace System.Collections {
+
+namespace System.Collections
+{
/// This is a simple implementation of IDictionary using a singly linked list. This
/// will be smaller and faster than a Hashtable if the number of elements is 10 or less.
/// This should not be used if performance is important for large numbers of elements.
[Serializable]
- internal class ListDictionaryInternal: IDictionary {
- DictionaryNode head;
- int version;
- int count;
+ internal class ListDictionaryInternal : IDictionary
+ {
+ private DictionaryNode head;
+ private int version;
+ private int count;
[NonSerialized]
private Object _syncRoot;
- public ListDictionaryInternal() {
+ public ListDictionaryInternal()
+ {
}
- public Object this[Object key] {
- get {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public Object this[Object key]
+ {
+ get
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
DictionaryNode node = head;
- while (node != null) {
- if ( node.key.Equals(key) ) {
+ while (node != null)
+ {
+ if (node.key.Equals(key))
+ {
return node.value;
}
node = node.next;
}
return null;
}
- set {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ set
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
-
+
version++;
DictionaryNode last = null;
DictionaryNode node;
- for (node = head; node != null; node = node.next) {
- if( node.key.Equals(key) ) {
+ for (node = head; node != null; node = node.next)
+ {
+ if (node.key.Equals(key))
+ {
break;
- }
+ }
last = node;
}
- if (node != null) {
+ if (node != null)
+ {
// Found it
node.value = value;
return;
@@ -68,78 +83,100 @@ namespace System.Collections {
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
- if (last != null) {
+ if (last != null)
+ {
last.next = newNode;
}
- else {
+ else
+ {
head = newNode;
}
count++;
}
}
- public int Count {
- get {
+ public int Count
+ {
+ get
+ {
return count;
}
- }
+ }
- public ICollection Keys {
- get {
+ public ICollection Keys
+ {
+ get
+ {
return new NodeKeyValueCollection(this, true);
}
}
- public bool IsReadOnly {
- get {
+ public bool IsReadOnly
+ {
+ get
+ {
return false;
}
}
- public bool IsFixedSize {
- get {
+ public bool IsFixedSize
+ {
+ get
+ {
return false;
}
}
- public bool IsSynchronized {
- get {
+ public bool IsSynchronized
+ {
+ get
+ {
return false;
}
}
- public Object SyncRoot {
- get {
- if( _syncRoot == null) {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ public Object SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
- return _syncRoot;
+ return _syncRoot;
}
}
- public ICollection Values {
- get {
+ public ICollection Values
+ {
+ get
+ {
return new NodeKeyValueCollection(this, false);
}
}
- public void Add(Object key, Object value) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public void Add(Object key, Object value)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
-
+
version++;
DictionaryNode last = null;
DictionaryNode node;
- for (node = head; node != null; node = node.next) {
- if (node.key.Equals(key)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", node.key, key));
- }
+ for (node = head; node != null; node = node.next)
+ {
+ if (node.key.Equals(key))
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, node.key, key));
+ }
last = node;
}
- if (node != null) {
+ if (node != null)
+ {
// Found it
node.value = value;
return;
@@ -148,265 +185,328 @@ namespace System.Collections {
DictionaryNode newNode = new DictionaryNode();
newNode.key = key;
newNode.value = value;
- if (last != null) {
+ if (last != null)
+ {
last.next = newNode;
}
- else {
+ else
+ {
head = newNode;
}
count++;
}
- public void Clear() {
+ public void Clear()
+ {
count = 0;
head = null;
version++;
}
- public bool Contains(Object key) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public bool Contains(Object key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
- for (DictionaryNode node = head; node != null; node = node.next) {
- if (node.key.Equals(key)) {
+ for (DictionaryNode node = head; node != null; node = node.next)
+ {
+ if (node.key.Equals(key))
+ {
return true;
}
}
return false;
}
- public void CopyTo(Array array, int index) {
- if (array==null)
+ public void CopyTo(Array array, int index)
+ {
+ if (array == null)
throw new ArgumentNullException(nameof(array));
-
+
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
- if ( array.Length - index < this.Count )
- throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
+ if (array.Length - index < this.Count)
+ throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
Contract.EndContractBlock();
- for (DictionaryNode node = head; node != null; node = node.next) {
+ for (DictionaryNode node = head; node != null; node = node.next)
+ {
array.SetValue(new DictionaryEntry(node.key, node.value), index);
index++;
}
}
- public IDictionaryEnumerator GetEnumerator() {
+ public IDictionaryEnumerator GetEnumerator()
+ {
return new NodeEnumerator(this);
}
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return new NodeEnumerator(this);
}
- public void Remove(Object key) {
- if (key == null) {
- throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
+ public void Remove(Object key)
+ {
+ if (key == null)
+ {
+ throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
}
Contract.EndContractBlock();
version++;
DictionaryNode last = null;
DictionaryNode node;
- for (node = head; node != null; node = node.next) {
- if (node.key.Equals(key)) {
+ for (node = head; node != null; node = node.next)
+ {
+ if (node.key.Equals(key))
+ {
break;
- }
+ }
last = node;
}
- if (node == null) {
+ if (node == null)
+ {
return;
- }
- if (node == head) {
+ }
+ if (node == head)
+ {
head = node.next;
- } else {
+ }
+ else
+ {
last.next = node.next;
}
count--;
}
- private class NodeEnumerator : IDictionaryEnumerator {
- ListDictionaryInternal list;
- DictionaryNode current;
- int version;
- bool start;
+ private class NodeEnumerator : IDictionaryEnumerator
+ {
+ private ListDictionaryInternal list;
+ private DictionaryNode current;
+ private int version;
+ private bool start;
- public NodeEnumerator(ListDictionaryInternal list) {
+ public NodeEnumerator(ListDictionaryInternal list)
+ {
this.list = list;
version = list.version;
start = true;
current = null;
}
- public Object Current {
- get {
+ public Object Current
+ {
+ get
+ {
return Entry;
}
}
- public DictionaryEntry Entry {
- get {
- if (current == null) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public DictionaryEntry Entry
+ {
+ get
+ {
+ if (current == null)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(current.key, current.value);
}
}
- public Object Key {
- get {
- if (current == null) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public Object Key
+ {
+ get
+ {
+ if (current == null)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return current.key;
}
}
- public Object Value {
- get {
- if (current == null) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public Object Value
+ {
+ get
+ {
+ if (current == null)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return current.value;
}
}
- public bool MoveNext() {
- if (version != list.version) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
+ public bool MoveNext()
+ {
+ if (version != list.version)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
- if (start) {
+ if (start)
+ {
current = list.head;
start = false;
}
- else {
- if( current != null ) {
+ else
+ {
+ if (current != null)
+ {
current = current.next;
}
}
return (current != null);
}
- public void Reset() {
- if (version != list.version) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
+ public void Reset()
+ {
+ if (version != list.version)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
start = true;
current = null;
}
-
}
- private class NodeKeyValueCollection : ICollection {
- ListDictionaryInternal list;
- bool isKeys;
+ private class NodeKeyValueCollection : ICollection
+ {
+ private ListDictionaryInternal list;
+ private bool isKeys;
- public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) {
+ public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys)
+ {
this.list = list;
this.isKeys = isKeys;
}
- void ICollection.CopyTo(Array array, int index) {
- if (array==null)
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
throw new ArgumentNullException(nameof(array));
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
- if (array.Length - index < list.Count)
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index));
- for (DictionaryNode node = list.head; node != null; node = node.next) {
+ if (array.Length - index < list.Count)
+ throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index));
+ for (DictionaryNode node = list.head; node != null; node = node.next)
+ {
array.SetValue(isKeys ? node.key : node.value, index);
index++;
}
}
- int ICollection.Count {
- get {
+ int ICollection.Count
+ {
+ get
+ {
int count = 0;
- for (DictionaryNode node = list.head; node != null; node = node.next) {
+ for (DictionaryNode node = list.head; node != null; node = node.next)
+ {
count++;
}
return count;
}
- }
+ }
- bool ICollection.IsSynchronized {
- get {
+ bool ICollection.IsSynchronized
+ {
+ get
+ {
return false;
}
}
- Object ICollection.SyncRoot {
- get {
+ Object ICollection.SyncRoot
+ {
+ get
+ {
return list.SyncRoot;
}
}
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return new NodeKeyValueEnumerator(list, isKeys);
}
- private class NodeKeyValueEnumerator: IEnumerator {
- ListDictionaryInternal list;
- DictionaryNode current;
- int version;
- bool isKeys;
- bool start;
+ private class NodeKeyValueEnumerator : IEnumerator
+ {
+ private ListDictionaryInternal list;
+ private DictionaryNode current;
+ private int version;
+ private bool isKeys;
+ private bool start;
- public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) {
+ public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys)
+ {
this.list = list;
this.isKeys = isKeys;
- this.version = list.version;
- this.start = true;
- this.current = null;
+ version = list.version;
+ start = true;
+ current = null;
}
- public Object Current {
- get {
- if (current == null) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
+ public Object Current
+ {
+ get
+ {
+ if (current == null)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return isKeys ? current.key : current.value;
}
}
- public bool MoveNext() {
- if (version != list.version) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
+ public bool MoveNext()
+ {
+ if (version != list.version)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
- if (start) {
+ if (start)
+ {
current = list.head;
start = false;
}
- else {
- if( current != null) {
+ else
+ {
+ if (current != null)
+ {
current = current.next;
}
}
return (current != null);
}
- public void Reset() {
- if (version != list.version) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion"));
+ public void Reset()
+ {
+ if (version != list.version)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
}
start = true;
current = null;
}
- }
+ }
}
[Serializable]
- private class DictionaryNode {
+ private class DictionaryNode
+ {
public Object key;
public Object value;
public DictionaryNode next;
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs b/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
index b3b19fb616..d9801dfaaf 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
@@ -4,50 +4,59 @@
//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime;
+
namespace System.Collections.ObjectModel
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Runtime;
-
[Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
- [DebuggerDisplay("Count = {Count}")]
- public class Collection<T>: IList<T>, IList, IReadOnlyList<T>
+ [DebuggerDisplay("Count = {Count}")]
+ public class Collection<T> : IList<T>, IList, IReadOnlyList<T>
{
- IList<T> items;
+ private IList<T> items;
[NonSerialized]
private Object _syncRoot;
- public Collection() {
+ public Collection()
+ {
items = new List<T>();
}
- public Collection(IList<T> list) {
- if (list == null) {
+ public Collection(IList<T> list)
+ {
+ if (list == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
items = list;
}
- public int Count {
+ public int Count
+ {
get { return items.Count; }
}
- protected IList<T> Items {
+ protected IList<T> Items
+ {
get { return items; }
}
- public T this[int index] {
+ public T this[int index]
+ {
get { return items[index]; }
- set {
- if( items.IsReadOnly) {
+ set
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
-
- if (index < 0 || index >= items.Count) {
+
+ if (index < 0 || index >= items.Count)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
@@ -55,154 +64,192 @@ namespace System.Collections.ObjectModel
}
}
- public void Add(T item) {
- if( items.IsReadOnly) {
+ public void Add(T item)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
-
+
int index = items.Count;
InsertItem(index, item);
}
- public void Clear() {
- if( items.IsReadOnly) {
+ public void Clear()
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
-
+
ClearItems();
}
- public void CopyTo(T[] array, int index) {
+ public void CopyTo(T[] array, int index)
+ {
items.CopyTo(array, index);
}
- public bool Contains(T item) {
+ public bool Contains(T item)
+ {
return items.Contains(item);
}
- public IEnumerator<T> GetEnumerator() {
+ public IEnumerator<T> GetEnumerator()
+ {
return items.GetEnumerator();
}
- public int IndexOf(T item) {
+ public int IndexOf(T item)
+ {
return items.IndexOf(item);
}
- public void Insert(int index, T item) {
- if (items.IsReadOnly) {
+ public void Insert(int index, T item)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- if (index < 0 || index > items.Count) {
+ if (index < 0 || index > items.Count)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert);
}
InsertItem(index, item);
}
- public bool Remove(T item) {
- if( items.IsReadOnly) {
+ public bool Remove(T item)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
-
+
int index = items.IndexOf(item);
if (index < 0) return false;
RemoveItem(index);
return true;
}
- public void RemoveAt(int index) {
- if( items.IsReadOnly) {
+ public void RemoveAt(int index)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- if (index < 0 || index >= items.Count) {
+ if (index < 0 || index >= items.Count)
+ {
ThrowHelper.ThrowArgumentOutOfRange_IndexException();
}
RemoveItem(index);
}
- protected virtual void ClearItems() {
+ protected virtual void ClearItems()
+ {
items.Clear();
}
- protected virtual void InsertItem(int index, T item) {
+ protected virtual void InsertItem(int index, T item)
+ {
items.Insert(index, item);
}
-
- protected virtual void RemoveItem(int index) {
+
+ protected virtual void RemoveItem(int index)
+ {
items.RemoveAt(index);
}
- protected virtual void SetItem(int index, T item) {
+ protected virtual void SetItem(int index, T item)
+ {
items[index] = item;
}
-
- bool ICollection<T>.IsReadOnly {
- get {
- return items.IsReadOnly;
+
+ bool ICollection<T>.IsReadOnly
+ {
+ get
+ {
+ return items.IsReadOnly;
}
}
-
- IEnumerator IEnumerable.GetEnumerator() {
+
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return ((IEnumerable)items).GetEnumerator();
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- object ICollection.SyncRoot {
- get {
- if( _syncRoot == null) {
+ object ICollection.SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
ICollection c = items as ICollection;
- if( c != null) {
+ if (c != null)
+ {
_syncRoot = c.SyncRoot;
}
- else {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ else
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
- return _syncRoot;
+ return _syncRoot;
}
}
- void ICollection.CopyTo(Array array, int index) {
- if (array == null) {
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
-
- if (array.Rank != 1) {
+
+ if (array.Rank != 1)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if( array.GetLowerBound(0) != 0 ) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
-
- if (index < 0 ) {
+
+ if (index < 0)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < Count) {
+ if (array.Length - index < Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] tArray = array as T[];
- if (tArray != null) {
- items.CopyTo(tArray , index);
+ if (tArray != null)
+ {
+ items.CopyTo(tArray, index);
}
- else {
+ else
+ {
//
// Catch the obvious case assignment will fail.
// We can found 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.
//
- Type targetType = array.GetType().GetElementType();
+ Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
- if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
+ if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
@@ -211,51 +258,62 @@ namespace System.Collections.ObjectModel
// widening of primitive types here.
//
object[] objects = array as object[];
- if( objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = items.Count;
- try {
- for (int i = 0; i < count; i++) {
+ try
+ {
+ for (int i = 0; i < count; i++)
+ {
objects[index++] = items[i];
}
}
- catch(ArrayTypeMismatchException) {
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
- }
+ }
}
- object IList.this[int index] {
+ object IList.this[int index]
+ {
get { return items[index]; }
- set {
+ set
+ {
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
- try {
- this[index] = (T)value;
+ try
+ {
+ this[index] = (T)value;
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
}
-
}
}
- bool IList.IsReadOnly {
- get {
+ bool IList.IsReadOnly
+ {
+ get
+ {
return items.IsReadOnly;
}
}
- bool IList.IsFixedSize {
- get {
+ bool IList.IsFixedSize
+ {
+ get
+ {
// There is no IList<T>.IsFixedSize, so we must assume that only
// readonly collections are fixed size, if our internal item
// collection does not implement IList. Note that Array implements
// IList, and therefore T[] and U[] will be fixed-size.
IList list = items as IList;
- if(list != null)
+ if (list != null)
{
return list.IsFixedSize;
}
@@ -263,62 +321,77 @@ namespace System.Collections.ObjectModel
}
}
- int IList.Add(object value) {
- if( items.IsReadOnly) {
+ int IList.Add(object value)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
-
- try {
+
+ try
+ {
Add((T)value);
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
- }
-
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
+ }
+
return this.Count - 1;
}
- bool IList.Contains(object value) {
- if(IsCompatibleObject(value)) {
- return Contains((T) value);
+ bool IList.Contains(object value)
+ {
+ if (IsCompatibleObject(value))
+ {
+ return Contains((T)value);
}
return false;
}
- int IList.IndexOf(object value) {
- if(IsCompatibleObject(value)) {
+ int IList.IndexOf(object value)
+ {
+ if (IsCompatibleObject(value))
+ {
return IndexOf((T)value);
- }
+ }
return -1;
}
- void IList.Insert(int index, object value) {
- if( items.IsReadOnly) {
+ void IList.Insert(int index, object value)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
-
- try {
+
+ try
+ {
Insert(index, (T)value);
}
- catch (InvalidCastException) {
- ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
- }
-
+ catch (InvalidCastException)
+ {
+ ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T));
+ }
}
- void IList.Remove(object value) {
- if( items.IsReadOnly) {
+ void IList.Remove(object value)
+ {
+ if (items.IsReadOnly)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- if(IsCompatibleObject(value)) {
- Remove((T) value);
- }
+ if (IsCompatibleObject(value))
+ {
+ Remove((T)value);
+ }
}
- private static bool IsCompatibleObject(object value) {
+ private static bool IsCompatibleObject(object value)
+ {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
deleted file mode 100644
index 3fe7716203..0000000000
--- a/src/mscorlib/src/System/Collections/ObjectModel/KeyedCollection.cs
+++ /dev/null
@@ -1,244 +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.
-
-//
-
-namespace System.Collections.ObjectModel
-{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [DebuggerTypeProxy(typeof(Mscorlib_KeyedCollectionDebugView<,>))]
- [DebuggerDisplay("Count = {Count}")]
- public abstract class KeyedCollection<TKey,TItem>: Collection<TItem>
- {
- const int defaultThreshold = 0;
-
- IEqualityComparer<TKey> comparer;
- Dictionary<TKey,TItem> dict;
- int keyCount;
- int threshold;
-
- protected KeyedCollection(): this(null, defaultThreshold) {}
-
- protected KeyedCollection(IEqualityComparer<TKey> comparer): this(comparer, defaultThreshold) {}
-
-
- protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold)
- : base(new List<TItem>()) { // Be explicit about the use of List<T> so we can foreach over
- // Items internally without enumerator allocations.
- if (comparer == null) {
- comparer = EqualityComparer<TKey>.Default;
- }
-
- if (dictionaryCreationThreshold == -1) {
- dictionaryCreationThreshold = int.MaxValue;
- }
-
- if( dictionaryCreationThreshold < -1) {
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold);
- }
-
- this.comparer = comparer;
- this.threshold = dictionaryCreationThreshold;
- }
-
- /// <summary>
- /// Enables the use of foreach internally without allocations using <see cref="List{T}"/>'s struct enumerator.
- /// </summary>
- new private List<TItem> Items {
- get {
- Debug.Assert(base.Items is List<TItem>);
-
- return (List<TItem>)base.Items;
- }
- }
-
- public IEqualityComparer<TKey> Comparer {
- get {
- return comparer;
- }
- }
-
- public TItem this[TKey key] {
- get {
- if( key == null) {
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- }
-
- if (dict != null) {
- return dict[key];
- }
-
- foreach (TItem item in Items) {
- if (comparer.Equals(GetKeyForItem(item), key)) return item;
- }
-
- ThrowHelper.ThrowKeyNotFoundException();
- return default(TItem);
- }
- }
-
- public bool Contains(TKey key) {
- if( key == null) {
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- }
-
- if (dict != null) {
- return dict.ContainsKey(key);
- }
-
- foreach (TItem item in Items) {
- if (comparer.Equals(GetKeyForItem(item), key)) return true;
- }
- return false;
- }
-
- private bool ContainsItem(TItem item) {
- TKey key;
- if( (dict == null) || ((key = GetKeyForItem(item)) == null)) {
- return Items.Contains(item);
- }
-
- TItem itemInDict;
- bool exist = dict.TryGetValue(key, out itemInDict);
- if( exist) {
- return EqualityComparer<TItem>.Default.Equals(itemInDict, item);
- }
- return false;
- }
-
- public bool Remove(TKey key) {
- if( key == null) {
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- }
-
- if (dict != null) {
- if (dict.ContainsKey(key)) {
- return Remove(dict[key]);
- }
-
- return false;
- }
-
- for (int i = 0; i < Items.Count; i++) {
- if (comparer.Equals(GetKeyForItem(Items[i]), key)) {
- RemoveItem(i);
- return true;
- }
- }
- return false;
- }
-
- protected IDictionary<TKey,TItem> Dictionary {
- get { return dict; }
- }
-
- protected void ChangeItemKey(TItem item, TKey newKey) {
- // check if the item exists in the collection
- if( !ContainsItem(item)) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist);
- }
-
- TKey oldKey = GetKeyForItem(item);
- if (!comparer.Equals(oldKey, newKey)) {
- if (newKey != null) {
- AddKey(newKey, item);
- }
-
- if (oldKey != null) {
- RemoveKey(oldKey);
- }
- }
- }
-
- protected override void ClearItems() {
- base.ClearItems();
- if (dict != null) {
- dict.Clear();
- }
-
- keyCount = 0;
- }
-
- protected abstract TKey GetKeyForItem(TItem item);
-
- protected override void InsertItem(int index, TItem item) {
- TKey key = GetKeyForItem(item);
- if (key != null) {
- AddKey(key, item);
- }
- base.InsertItem(index, item);
- }
-
- protected override void RemoveItem(int index) {
- TKey key = GetKeyForItem(Items[index]);
- if (key != null) {
- RemoveKey(key);
- }
- base.RemoveItem(index);
- }
-
- protected override void SetItem(int index, TItem item) {
- TKey newKey = GetKeyForItem(item);
- TKey oldKey = GetKeyForItem(Items[index]);
-
- if (comparer.Equals(oldKey, newKey)) {
- if (newKey != null && dict != null) {
- dict[newKey] = item;
- }
- }
- else {
- if (newKey != null) {
- AddKey(newKey, item);
- }
-
- if (oldKey != null) {
- RemoveKey(oldKey);
- }
- }
- base.SetItem(index, item);
- }
-
- private void AddKey(TKey key, TItem item) {
- if (dict != null) {
- dict.Add(key, item);
- }
- else if (keyCount == threshold) {
- CreateDictionary();
- dict.Add(key, item);
- }
- else {
- if (Contains(key)) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
- }
-
- keyCount++;
- }
- }
-
- private void CreateDictionary() {
- dict = new Dictionary<TKey,TItem>(comparer);
- foreach (TItem item in Items) {
- TKey key = GetKeyForItem(item);
- if (key != null) {
- dict.Add(key, item);
- }
- }
- }
-
- private void RemoveKey(TKey key) {
- Debug.Assert(key != null, "key shouldn't be null!");
- if (dict != null) {
- dict.Remove(key);
- }
- else {
- keyCount--;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
index 10c48cf76d..b484879c27 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
@@ -4,150 +4,184 @@
//
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Runtime;
+
namespace System.Collections.ObjectModel
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Runtime;
-
[Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
- [DebuggerDisplay("Count = {Count}")]
- public class ReadOnlyCollection<T>: IList<T>, IList, IReadOnlyList<T>
+ [DebuggerDisplay("Count = {Count}")]
+ public class ReadOnlyCollection<T> : IList<T>, IList, IReadOnlyList<T>
{
- IList<T> list;
+ private IList<T> list;
[NonSerialized]
private Object _syncRoot;
- public ReadOnlyCollection(IList<T> list) {
- if (list == null) {
+ public ReadOnlyCollection(IList<T> list)
+ {
+ if (list == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.list);
}
this.list = list;
}
- public int Count {
+ public int Count
+ {
get { return list.Count; }
}
- public T this[int index] {
+ public T this[int index]
+ {
get { return list[index]; }
}
- public bool Contains(T value) {
+ public bool Contains(T value)
+ {
return list.Contains(value);
}
- public void CopyTo(T[] array, int index) {
+ public void CopyTo(T[] array, int index)
+ {
list.CopyTo(array, index);
}
- public IEnumerator<T> GetEnumerator() {
+ public IEnumerator<T> GetEnumerator()
+ {
return list.GetEnumerator();
}
- public int IndexOf(T value) {
+ public int IndexOf(T value)
+ {
return list.IndexOf(value);
}
- protected IList<T> Items {
- get {
+ protected IList<T> Items
+ {
+ get
+ {
return list;
}
}
- bool ICollection<T>.IsReadOnly {
+ bool ICollection<T>.IsReadOnly
+ {
get { return true; }
}
-
- T IList<T>.this[int index] {
+
+ T IList<T>.this[int index]
+ {
get { return list[index]; }
- set {
+ set
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
- void ICollection<T>.Add(T value) {
+ void ICollection<T>.Add(T value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
-
- void ICollection<T>.Clear() {
+
+ void ICollection<T>.Clear()
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- void IList<T>.Insert(int index, T value) {
+ void IList<T>.Insert(int index, T value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- bool ICollection<T>.Remove(T value) {
+ bool ICollection<T>.Remove(T value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
- void IList<T>.RemoveAt(int index) {
+ void IList<T>.RemoveAt(int index)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
return ((IEnumerable)list).GetEnumerator();
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- object ICollection.SyncRoot {
- get {
- if( _syncRoot == null) {
+ object ICollection.SyncRoot
+ {
+ get
+ {
+ if (_syncRoot == null)
+ {
ICollection c = list as ICollection;
- if( c != null) {
+ if (c != null)
+ {
_syncRoot = c.SyncRoot;
}
- else {
- System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
+ else
+ {
+ System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
}
- return _syncRoot;
+ return _syncRoot;
}
}
- void ICollection.CopyTo(Array array, int index) {
- if (array==null) {
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (array.Rank != 1) {
- ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
+ if (array.Rank != 1)
+ {
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if( array.GetLowerBound(0) != 0 ) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
-
- if (index < 0) {
+
+ if (index < 0)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < Count) {
+ if (array.Length - index < Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
T[] items = array as T[];
- if (items != null) {
+ if (items != null)
+ {
list.CopyTo(items, index);
}
- else {
+ else
+ {
//
// Catch the obvious case assignment will fail.
// We can found 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.
//
- Type targetType = array.GetType().GetElementType();
+ Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
- if(!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
+ if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
@@ -156,76 +190,94 @@ namespace System.Collections.ObjectModel
// widening of primitive types here.
//
object[] objects = array as object[];
- if( objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
int count = list.Count;
- try {
- for (int i = 0; i < count; i++) {
+ try
+ {
+ for (int i = 0; i < count; i++)
+ {
objects[index++] = list[i];
}
}
- catch(ArrayTypeMismatchException) {
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
- bool IList.IsFixedSize {
+ bool IList.IsFixedSize
+ {
get { return true; }
}
- bool IList.IsReadOnly {
+ bool IList.IsReadOnly
+ {
get { return true; }
}
- object IList.this[int index] {
+ object IList.this[int index]
+ {
get { return list[index]; }
- set {
+ set
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
- int IList.Add(object value) {
+ int IList.Add(object value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return -1;
}
- void IList.Clear() {
- ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
+ void IList.Clear()
+ {
+ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- private static bool IsCompatibleObject(object value) {
+ private static bool IsCompatibleObject(object value)
+ {
// Non-null values are fine. Only accept nulls if T is a class or Nullable<U>.
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
return ((value is T) || (value == null && default(T) == null));
}
- bool IList.Contains(object value) {
- if(IsCompatibleObject(value)) {
- return Contains((T) value);
+ bool IList.Contains(object value)
+ {
+ if (IsCompatibleObject(value))
+ {
+ return Contains((T)value);
}
return false;
}
- int IList.IndexOf(object value) {
- if(IsCompatibleObject(value)) {
+ int IList.IndexOf(object value)
+ {
+ if (IsCompatibleObject(value))
+ {
return IndexOf((T)value);
}
return -1;
}
- void IList.Insert(int index, object value) {
+ void IList.Insert(int index, object value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- void IList.Remove(object value) {
- ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
+ void IList.Remove(object value)
+ {
+ ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- void IList.RemoveAt(int index) {
+ void IList.RemoveAt(int index)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
index 5c9e8c44c6..ebf86cdc58 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
+++ b/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyDictionary.cs
@@ -11,18 +11,18 @@
**
===========================================================*/
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Collections.ObjectModel
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
[Serializable]
[DebuggerTypeProxy(typeof(Mscorlib_DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
- public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
+ internal class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> m_dictionary;
[NonSerialized]
@@ -32,32 +32,41 @@ namespace System.Collections.ObjectModel
[NonSerialized]
private ValueCollection m_values;
- public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary) {
- if (dictionary == null) {
+ public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
+ {
+ if (dictionary == null)
+ {
throw new ArgumentNullException(nameof(dictionary));
}
Contract.EndContractBlock();
m_dictionary = dictionary;
}
- protected IDictionary<TKey, TValue> Dictionary {
+ protected IDictionary<TKey, TValue> Dictionary
+ {
get { return m_dictionary; }
}
- public KeyCollection Keys {
- get {
+ public KeyCollection Keys
+ {
+ get
+ {
Contract.Ensures(Contract.Result<KeyCollection>() != null);
- if (m_keys == null) {
+ if (m_keys == null)
+ {
m_keys = new KeyCollection(m_dictionary.Keys);
}
return m_keys;
}
}
- public ValueCollection Values {
- get {
+ public ValueCollection Values
+ {
+ get
+ {
Contract.Ensures(Contract.Result<ValueCollection>() != null);
- if (m_values == null) {
+ if (m_values == null)
+ {
m_values = new ValueCollection(m_dictionary.Values);
}
return m_values;
@@ -66,46 +75,59 @@ namespace System.Collections.ObjectModel
#region IDictionary<TKey, TValue> Members
- public bool ContainsKey(TKey key) {
+ public bool ContainsKey(TKey key)
+ {
return m_dictionary.ContainsKey(key);
}
- ICollection<TKey> IDictionary<TKey, TValue>.Keys {
- get {
+ ICollection<TKey> IDictionary<TKey, TValue>.Keys
+ {
+ get
+ {
return Keys;
}
}
- public bool TryGetValue(TKey key, out TValue value) {
+ public bool TryGetValue(TKey key, out TValue value)
+ {
return m_dictionary.TryGetValue(key, out value);
}
- ICollection<TValue> IDictionary<TKey, TValue>.Values {
- get {
+ ICollection<TValue> IDictionary<TKey, TValue>.Values
+ {
+ get
+ {
return Values;
}
}
- public TValue this[TKey key] {
- get {
+ public TValue this[TKey key]
+ {
+ get
+ {
return m_dictionary[key];
}
}
- void IDictionary<TKey, TValue>.Add(TKey key, TValue value) {
+ void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- bool IDictionary<TKey, TValue>.Remove(TKey key) {
+ bool IDictionary<TKey, TValue>.Remove(TKey key)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
- TValue IDictionary<TKey, TValue>.this[TKey key] {
- get {
+ TValue IDictionary<TKey, TValue>.this[TKey key]
+ {
+ get
+ {
return m_dictionary[key];
}
- set {
+ set
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
@@ -114,31 +136,38 @@ namespace System.Collections.ObjectModel
#region ICollection<KeyValuePair<TKey, TValue>> Members
- public int Count {
+ public int Count
+ {
get { return m_dictionary.Count; }
}
- bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) {
+ bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
+ {
return m_dictionary.Contains(item);
}
- void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) {
+ void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
+ {
m_dictionary.CopyTo(array, arrayIndex);
}
- bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly {
+ bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
+ {
get { return true; }
}
- void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) {
+ void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- void ICollection<KeyValuePair<TKey, TValue>>.Clear() {
+ void ICollection<KeyValuePair<TKey, TValue>>.Clear()
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) {
+ bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
return false;
}
@@ -147,7 +176,8 @@ namespace System.Collections.ObjectModel
#region IEnumerable<KeyValuePair<TKey, TValue>> Members
- public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() {
+ public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
+ {
return m_dictionary.GetEnumerator();
}
@@ -155,7 +185,8 @@ namespace System.Collections.ObjectModel
#region IEnumerable Members
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+ {
return ((IEnumerable)m_dictionary).GetEnumerator();
}
@@ -163,131 +194,170 @@ namespace System.Collections.ObjectModel
#region IDictionary Members
- private static bool IsCompatibleKey(object key) {
- if (key == null) {
+ private static bool IsCompatibleKey(object key)
+ {
+ if (key == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
}
return key is TKey;
}
- void IDictionary.Add(object key, object value) {
+ void IDictionary.Add(object key, object value)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- void IDictionary.Clear() {
+ void IDictionary.Clear()
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- bool IDictionary.Contains(object key) {
+ bool IDictionary.Contains(object key)
+ {
return IsCompatibleKey(key) && ContainsKey((TKey)key);
}
- IDictionaryEnumerator IDictionary.GetEnumerator() {
+ IDictionaryEnumerator IDictionary.GetEnumerator()
+ {
IDictionary d = m_dictionary as IDictionary;
- if (d != null) {
+ if (d != null)
+ {
return d.GetEnumerator();
}
return new DictionaryEnumerator(m_dictionary);
}
- bool IDictionary.IsFixedSize {
+ bool IDictionary.IsFixedSize
+ {
get { return true; }
}
- bool IDictionary.IsReadOnly {
+ bool IDictionary.IsReadOnly
+ {
get { return true; }
}
- ICollection IDictionary.Keys {
- get {
+ ICollection IDictionary.Keys
+ {
+ get
+ {
return Keys;
}
}
- void IDictionary.Remove(object key) {
+ void IDictionary.Remove(object key)
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
- ICollection IDictionary.Values {
- get {
+ ICollection IDictionary.Values
+ {
+ get
+ {
return Values;
}
}
- object IDictionary.this[object key] {
- get {
- if (IsCompatibleKey(key)) {
+ object IDictionary.this[object key]
+ {
+ get
+ {
+ if (IsCompatibleKey(key))
+ {
return this[(TKey)key];
}
return null;
}
- set {
+ set
+ {
ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection);
}
}
- void ICollection.CopyTo(Array array, int index) {
- if (array == null) {
+ void ICollection.CopyTo(Array array, int index)
+ {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (array.Rank != 1) {
+ if (array.Rank != 1)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if (array.GetLowerBound(0) != 0) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
- if (index < 0 || index > array.Length) {
+ if (index < 0 || index > array.Length)
+ {
ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException();
}
- if (array.Length - index < Count) {
+ if (array.Length - index < Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
- if (pairs != null) {
+ if (pairs != null)
+ {
m_dictionary.CopyTo(pairs, index);
}
- else {
+ else
+ {
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
- if (dictEntryArray != null) {
- foreach (var item in m_dictionary) {
+ if (dictEntryArray != null)
+ {
+ foreach (var item in m_dictionary)
+ {
dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value);
}
}
- else {
+ else
+ {
object[] objects = array as object[];
- if (objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
- try {
- foreach (var item in m_dictionary) {
+ try
+ {
+ foreach (var item in m_dictionary)
+ {
objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
}
- catch (ArrayTypeMismatchException) {
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
}
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- object ICollection.SyncRoot {
- get {
- if (m_syncRoot == null) {
+ object ICollection.SyncRoot
+ {
+ get
+ {
+ if (m_syncRoot == null)
+ {
ICollection c = m_dictionary as ICollection;
- if (c != null) {
+ if (c != null)
+ {
m_syncRoot = c.SyncRoot;
}
- else {
+ else
+ {
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
@@ -296,36 +366,44 @@ namespace System.Collections.ObjectModel
}
[Serializable]
- private struct DictionaryEnumerator : IDictionaryEnumerator {
+ private struct DictionaryEnumerator : IDictionaryEnumerator
+ {
private readonly IDictionary<TKey, TValue> m_dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator;
- public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) {
+ public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary)
+ {
m_dictionary = dictionary;
m_enumerator = m_dictionary.GetEnumerator();
}
- public DictionaryEntry Entry {
+ public DictionaryEntry Entry
+ {
get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); }
}
- public object Key {
+ public object Key
+ {
get { return m_enumerator.Current.Key; }
}
- public object Value {
+ public object Value
+ {
get { return m_enumerator.Current.Value; }
}
- public object Current {
+ public object Current
+ {
get { return Entry; }
}
- public bool MoveNext() {
+ public bool MoveNext()
+ {
return m_enumerator.MoveNext();
}
- public void Reset() {
+ public void Reset()
+ {
m_enumerator.Reset();
}
}
@@ -334,14 +412,18 @@ namespace System.Collections.ObjectModel
#region IReadOnlyDictionary members
- IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys {
- get {
+ IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
+ {
+ get
+ {
return Keys;
}
}
- IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values {
- get {
+ IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
+ {
+ get
+ {
return Values;
}
}
@@ -351,14 +433,16 @@ namespace System.Collections.ObjectModel
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> {
+ public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
+ {
private readonly ICollection<TKey> m_collection;
[NonSerialized]
private Object m_syncRoot;
internal KeyCollection(ICollection<TKey> collection)
{
- if (collection == null) {
+ if (collection == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
m_collection = collection;
@@ -386,11 +470,13 @@ namespace System.Collections.ObjectModel
m_collection.CopyTo(array, arrayIndex);
}
- public int Count {
+ public int Count
+ {
get { return m_collection.Count; }
}
- bool ICollection<TKey>.IsReadOnly {
+ bool ICollection<TKey>.IsReadOnly
+ {
get { return true; }
}
@@ -413,7 +499,8 @@ namespace System.Collections.ObjectModel
#region IEnumerable Members
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+ {
return ((IEnumerable)m_collection).GetEnumerator();
}
@@ -421,22 +508,29 @@ namespace System.Collections.ObjectModel
#region ICollection Members
- void ICollection.CopyTo(Array array, int index) {
+ void ICollection.CopyTo(Array array, int index)
+ {
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(m_collection, array, index);
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- object ICollection.SyncRoot {
- get {
- if (m_syncRoot == null) {
+ object ICollection.SyncRoot
+ {
+ get
+ {
+ if (m_syncRoot == null)
+ {
ICollection c = m_collection as ICollection;
- if (c != null) {
+ if (c != null)
+ {
m_syncRoot = c.SyncRoot;
}
- else {
+ else
+ {
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
@@ -450,14 +544,16 @@ namespace System.Collections.ObjectModel
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
- public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> {
+ public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
+ {
private readonly ICollection<TValue> m_collection;
[NonSerialized]
private Object m_syncRoot;
internal ValueCollection(ICollection<TValue> collection)
{
- if (collection == null) {
+ if (collection == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
m_collection = collection;
@@ -485,11 +581,13 @@ namespace System.Collections.ObjectModel
m_collection.CopyTo(array, arrayIndex);
}
- public int Count {
+ public int Count
+ {
get { return m_collection.Count; }
}
- bool ICollection<TValue>.IsReadOnly {
+ bool ICollection<TValue>.IsReadOnly
+ {
get { return true; }
}
@@ -512,7 +610,8 @@ namespace System.Collections.ObjectModel
#region IEnumerable Members
- System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
+ System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
+ {
return ((IEnumerable)m_collection).GetEnumerator();
}
@@ -520,22 +619,29 @@ namespace System.Collections.ObjectModel
#region ICollection Members
- void ICollection.CopyTo(Array array, int index) {
+ void ICollection.CopyTo(Array array, int index)
+ {
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(m_collection, array, index);
}
- bool ICollection.IsSynchronized {
+ bool ICollection.IsSynchronized
+ {
get { return false; }
}
- object ICollection.SyncRoot {
- get {
- if (m_syncRoot == null) {
+ object ICollection.SyncRoot
+ {
+ get
+ {
+ if (m_syncRoot == null)
+ {
ICollection c = m_collection as ICollection;
- if (c != null) {
+ if (c != null)
+ {
m_syncRoot = c.SyncRoot;
}
- else {
+ else
+ {
System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null);
}
}
@@ -555,38 +661,46 @@ namespace System.Collections.ObjectModel
// Abstracted away to avoid redundant implementations.
internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index)
{
- if (array == null) {
+ if (array == null)
+ {
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
- if (array.Rank != 1) {
+ if (array.Rank != 1)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported);
}
- if (array.GetLowerBound(0) != 0) {
+ if (array.GetLowerBound(0) != 0)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound);
}
- if (index < 0) {
+ if (index < 0)
+ {
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
- if (array.Length - index < collection.Count) {
+ if (array.Length - index < collection.Count)
+ {
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
// Easy out if the ICollection<T> implements the non-generic ICollection
ICollection nonGenericCollection = collection as ICollection;
- if (nonGenericCollection != null) {
+ if (nonGenericCollection != null)
+ {
nonGenericCollection.CopyTo(array, index);
return;
}
T[] items = array as T[];
- if (items != null) {
+ if (items != null)
+ {
collection.CopyTo(items, index);
}
- else {
+ else
+ {
//
// Catch the obvious case assignment will fail.
// We can found all possible problems by doing the check though.
@@ -595,7 +709,8 @@ namespace System.Collections.ObjectModel
//
Type targetType = array.GetType().GetElementType();
Type sourceType = typeof(T);
- if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType))) {
+ if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
@@ -604,16 +719,20 @@ namespace System.Collections.ObjectModel
// widening of primitive types here.
//
object[] objects = array as object[];
- if (objects == null) {
+ if (objects == null)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
- try {
- foreach (var item in collection) {
+ try
+ {
+ foreach (var item in collection)
+ {
objects[index++] = item;
}
}
- catch (ArrayTypeMismatchException) {
+ catch (ArrayTypeMismatchException)
+ {
ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType();
}
}
diff --git a/src/mscorlib/src/System/Collections/StructuralComparisons.cs b/src/mscorlib/src/System/Collections/StructuralComparisons.cs
deleted file mode 100644
index 685af59c4b..0000000000
--- a/src/mscorlib/src/System/Collections/StructuralComparisons.cs
+++ /dev/null
@@ -1,89 +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;
-
-namespace System.Collections {
- public static class StructuralComparisons {
-
- private static volatile IComparer s_StructuralComparer;
- private static volatile IEqualityComparer s_StructuralEqualityComparer;
-
- public static IComparer StructuralComparer {
- get {
- IComparer comparer = s_StructuralComparer;
- if (comparer == null) {
- comparer = new StructuralComparer();
- s_StructuralComparer = comparer;
- }
- return comparer;
- }
- }
-
- public static IEqualityComparer StructuralEqualityComparer {
- get {
- IEqualityComparer comparer = s_StructuralEqualityComparer;
- if (comparer == null) {
- comparer = new StructuralEqualityComparer();
- s_StructuralEqualityComparer = comparer;
- }
- return comparer;
- }
- }
- }
-
- [Serializable]
- internal class StructuralEqualityComparer : IEqualityComparer {
- public new bool Equals(Object x, Object y) {
- if (x != null) {
-
- IStructuralEquatable seObj = x as IStructuralEquatable;
-
- if (seObj != null){
- return seObj.Equals(y, this);
- }
-
- if (y != null) {
- return x.Equals(y);
- } else {
- return false;
- }
- }
- if (y != null) return false;
- return true;
- }
-
- public int GetHashCode(Object obj) {
- if (obj == null) return 0;
-
- IStructuralEquatable seObj = obj as IStructuralEquatable;
-
- if (seObj != null) {
- return seObj.GetHashCode(this);
- }
-
- return obj.GetHashCode();
- }
- }
-
- [Serializable]
- internal class StructuralComparer : IComparer {
- public int Compare(Object x, Object y) {
-
- if (x == null) return y == null ? 0 : -1;
- if (y == null) return 1;
-
- IStructuralComparable scX = x as IStructuralComparable;
-
- if (scX != null) {
- return scX.CompareTo(y, this);
- }
-
- return Comparer.Default.Compare(x, y);
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs b/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs
deleted file mode 100644
index a7946f8203..0000000000
--- a/src/mscorlib/src/System/ComponentModel/EditorBrowsableAttribute.cs
+++ /dev/null
@@ -1,48 +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.
-
-namespace System.ComponentModel
-{
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface)]
- public sealed class EditorBrowsableAttribute : Attribute
- {
- private EditorBrowsableState browsableState;
-
- public EditorBrowsableAttribute(EditorBrowsableState state)
- {
- browsableState = state;
- }
-
- public EditorBrowsableAttribute () : this(EditorBrowsableState.Always) { }
-
- public EditorBrowsableState State
- {
- get { return browsableState; }
- }
-
- public override bool Equals(object obj)
- {
- if (obj == this)
- {
- return true;
- }
-
- EditorBrowsableAttribute other = obj as EditorBrowsableAttribute;
-
- return (other != null) && other.browsableState == browsableState;
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
- }
-
- public enum EditorBrowsableState
- {
- Always,
- Never,
- Advanced
- }
-}
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
deleted file mode 100644
index a19d0344b1..0000000000
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
+++ /dev/null
@@ -1,28 +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:
-**
-**
-===========================================================*/
-using System.Runtime.InteropServices;
-
-namespace System.Configuration.Assemblies {
-
- using System;
- [Serializable]
- public enum AssemblyHashAlgorithm
- {
- None = 0,
- MD5 = 0x8003,
- SHA1 = 0x8004,
- SHA256 = 0x800c,
- SHA384 = 0x800d,
- SHA512 = 0x800e,
- }
-}
diff --git a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs b/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
deleted file mode 100644
index b7e9c30c62..0000000000
--- a/src/mscorlib/src/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
+++ /dev/null
@@ -1,23 +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: defining the different flavor's assembly version compatibility
-**
-**
-===========================================================*/
-namespace System.Configuration.Assemblies {
-
- using System;
- [Serializable]
- public enum AssemblyVersionCompatibility
- {
- SameMachine = 1,
- SameProcess = 2,
- SameDomain = 3,
- }
-}
diff --git a/src/mscorlib/src/System/Convert.cs b/src/mscorlib/src/System/Convert.cs
deleted file mode 100644
index 0cd3c5d715..0000000000
--- a/src/mscorlib/src/System/Convert.cs
+++ /dev/null
@@ -1,2703 +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: Home for static conversion methods.
-**
-**
-===========================================================*/
-
-using System;
-using System.Globalization;
-using System.Threading;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Runtime.Versioning;
-using System.Security;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-
-
-namespace System {
-
- [Flags]
- public enum Base64FormattingOptions {
- None = 0,
- InsertLineBreaks = 1
- }
-
- // Returns the type code of this object. An implementation of this method
- // must not return TypeCode.Empty (which represents a null reference) or
- // TypeCode.Object (which represents an object that doesn't implement the
- // IConvertible interface). An implementation of this method should return
- // TypeCode.DBNull if the value of this object is a database null. For
- // example, a nullable integer type should return TypeCode.DBNull if the
- // value of the object is the database null. Otherwise, an implementation
- // of this method should return the TypeCode that best describes the
- // internal representation of the object.
- // The Value class provides conversion and querying methods for values. The
- // Value class contains static members only, and it is not possible to create
- // instances of the class.
- //
- // The statically typed conversion methods provided by the Value class are all
- // of the form:
- //
- // public static XXX ToXXX(YYY value)
- //
- // where XXX is the target type and YYY is the source type. The matrix below
- // shows the set of supported conversions. The set of conversions is symmetric
- // such that for every ToXXX(YYY) there is also a ToYYY(XXX).
- //
- // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Str
- // ----------------------------------------------------------------------
- // Boolean x x x x x x x x x x x x x
- // Char x x x x x x x x x x
- // SByte x x x x x x x x x x x x x x
- // Byte x x x x x x x x x x x x x x
- // Int16 x x x x x x x x x x x x x x
- // UInt16 x x x x x x x x x x x x x x
- // Int32 x x x x x x x x x x x x x x
- // UInt32 x x x x x x x x x x x x x x
- // Int64 x x x x x x x x x x x x x x
- // UInt64 x x x x x x x x x x x x x x
- // Single x x x x x x x x x x x x x
- // Double x x x x x x x x x x x x x
- // Decimal x x x x x x x x x x x x x
- // DateTime x x
- // String x x x x x x x x x x x x x x x
- // ----------------------------------------------------------------------
- //
- // For dynamic conversions, the Value class provides a set of methods of the
- // form:
- //
- // public static XXX ToXXX(object value)
- //
- // where XXX is the target type (Boolean, Char, SByte, Byte, Int16, UInt16,
- // Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime,
- // or String). The implementations of these methods all take the form:
- //
- // public static XXX toXXX(object value) {
- // return value == null? XXX.Default: ((IConvertible)value).ToXXX();
- // }
- //
- // The code first checks if the given value is a null reference (which is the
- // same as Value.Empty), in which case it returns the default value for type
- // XXX. Otherwise, a cast to IConvertible is performed, and the appropriate ToXXX()
- // method is invoked on the object. An InvalidCastException is thrown if the
- // cast to IConvertible fails, and that exception is simply allowed to propagate out
- // of the conversion method.
-
- // Constant representing the database null value. This value is used in
- // database applications to indicate the absense of a known value. Note
- // that Value.DBNull is NOT the same as a null object reference, which is
- // represented by Value.Empty.
- //
- // The Equals() method of DBNull always returns false, even when the
- // argument is itself DBNull.
- //
- // When passed Value.DBNull, the Value.GetTypeCode() method returns
- // TypeCode.DBNull.
- //
- // When passed Value.DBNull, the Value.ToXXX() methods all throw an
- // InvalidCastException.
-
- public static class Convert {
-
- //A typeof operation is fairly expensive (does a system call), so we'll cache these here
- //statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16]
- //will give you the type of an Int16.
- internal static readonly RuntimeType[] ConvertTypes = {
- (RuntimeType)typeof(System.Empty),
- (RuntimeType)typeof(Object),
- (RuntimeType)typeof(System.DBNull),
- (RuntimeType)typeof(Boolean),
- (RuntimeType)typeof(Char),
- (RuntimeType)typeof(SByte),
- (RuntimeType)typeof(Byte),
- (RuntimeType)typeof(Int16),
- (RuntimeType)typeof(UInt16),
- (RuntimeType)typeof(Int32),
- (RuntimeType)typeof(UInt32),
- (RuntimeType)typeof(Int64),
- (RuntimeType)typeof(UInt64),
- (RuntimeType)typeof(Single),
- (RuntimeType)typeof(Double),
- (RuntimeType)typeof(Decimal),
- (RuntimeType)typeof(DateTime),
- (RuntimeType)typeof(Object), //TypeCode is discontinuous so we need a placeholder.
- (RuntimeType)typeof(String)
- };
-
- // Need to special case Enum because typecode will be underlying type, e.g. Int32
- private static readonly RuntimeType EnumType = (RuntimeType)typeof(Enum);
-
- internal static readonly char[] base64Table = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O',
- 'P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d',
- 'e','f','g','h','i','j','k','l','m','n','o','p','q','r','s',
- 't','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
- '8','9','+','/','=' };
-
- private const Int32 base64LineBreakPosition = 76;
-
-#if _DEBUG
- private static bool TriggerAsserts = DoAsserts();
- private static bool DoAsserts() {
- Debug.Assert(ConvertTypes!=null, "[Convert.cctor]ConvertTypes!=null");
- Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
- Debug.Assert(ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty),
- "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)");
- Debug.Assert(ConvertTypes[(int)TypeCode.String]==typeof(String),
- "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)");
- Debug.Assert(ConvertTypes[(int)TypeCode.Int32]==typeof(int),
- "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
- return true;
- }
-#endif
-
- public static readonly Object DBNull = System.DBNull.Value;
-
- // Returns the type code for the given object. If the argument is null,
- // the result is TypeCode.Empty. If the argument is not a value (i.e. if
- // the object does not implement IConvertible), the result is TypeCode.Object.
- // Otherwise, the result is the type code of the object, as determined by
- // the object's implementation of IConvertible.
- [Pure]
- public static TypeCode GetTypeCode(object value) {
- if (value == null) return TypeCode.Empty;
- IConvertible temp = value as IConvertible;
- if (temp != null)
- {
- return temp.GetTypeCode();
- }
- return TypeCode.Object;
- }
-
- // Returns true if the given object is a database null. This operation
- // corresponds to "value.GetTypeCode() == TypeCode.DBNull".
- [Pure]
- public static bool IsDBNull(object value) {
- if (value == System.DBNull.Value) return true;
- IConvertible convertible = value as IConvertible;
- return convertible != null? convertible.GetTypeCode() == TypeCode.DBNull: false;
- }
-
- // Converts the given object to the given type. In general, this method is
- // equivalent to calling the Value.ToXXX(value) method for the given
- // typeCode and boxing the result.
- //
- // The method first checks if the given object implements IConvertible. If not,
- // the only permitted conversion is from a null to TypeCode.Empty, the
- // result of which is null.
- //
- // If the object does implement IConvertible, a check is made to see if the
- // object already has the given type code, in which case the object is
- // simply returned. Otherwise, the appropriate ToXXX() is invoked on the
- // object's implementation of IConvertible.
- public static Object ChangeType(Object value, TypeCode typeCode) {
- return ChangeType(value, typeCode, Thread.CurrentThread.CurrentCulture);
- }
-
- public static Object ChangeType(Object value, TypeCode typeCode, IFormatProvider provider) {
- if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) {
- return null;
- }
-
- IConvertible v = value as IConvertible;
- if (v == null) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
- }
-
- // This line is invalid for things like Enums that return a TypeCode
- // of Int32, but the object can't actually be cast to an Int32.
- // if (v.GetTypeCode() == typeCode) return value;
- switch (typeCode) {
- case TypeCode.Boolean:
- return v.ToBoolean(provider);
- case TypeCode.Char:
- return v.ToChar(provider);
- case TypeCode.SByte:
- return v.ToSByte(provider);
- case TypeCode.Byte:
- return v.ToByte(provider);
- case TypeCode.Int16:
- return v.ToInt16(provider);
- case TypeCode.UInt16:
- return v.ToUInt16(provider);
- case TypeCode.Int32:
- return v.ToInt32(provider);
- case TypeCode.UInt32:
- return v.ToUInt32(provider);
- case TypeCode.Int64:
- return v.ToInt64(provider);
- case TypeCode.UInt64:
- return v.ToUInt64(provider);
- case TypeCode.Single:
- return v.ToSingle(provider);
- case TypeCode.Double:
- return v.ToDouble(provider);
- case TypeCode.Decimal:
- return v.ToDecimal(provider);
- case TypeCode.DateTime:
- return v.ToDateTime(provider);
- case TypeCode.String:
- return v.ToString(provider);
- case TypeCode.Object:
- return value;
- case TypeCode.DBNull:
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_DBNull"));
- case TypeCode.Empty:
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_Empty"));
- default:
- throw new ArgumentException(Environment.GetResourceString("Arg_UnknownTypeCode"));
- }
- }
-
- internal static Object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) {
- Contract.Requires(value != null, "[Convert.DefaultToType]value!=null");
- if (targetType==null) {
- throw new ArgumentNullException(nameof(targetType));
- }
- Contract.EndContractBlock();
-
- RuntimeType rtTargetType = targetType as RuntimeType;
-
- if (rtTargetType != null)
- {
- if (value.GetType() == targetType)
- {
- return value;
- }
-
- if (rtTargetType == ConvertTypes[(int)TypeCode.Boolean])
- return value.ToBoolean(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Char])
- return value.ToChar(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.SByte])
- return value.ToSByte(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Byte])
- return value.ToByte(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Int16])
- return value.ToInt16(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.UInt16])
- return value.ToUInt16(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Int32])
- return value.ToInt32(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.UInt32])
- return value.ToUInt32(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Int64])
- return value.ToInt64(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.UInt64])
- return value.ToUInt64(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Single])
- return value.ToSingle(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Double])
- return value.ToDouble(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Decimal])
- return value.ToDecimal(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.DateTime])
- return value.ToDateTime(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.String])
- return value.ToString(provider);
- if (rtTargetType == ConvertTypes[(int)TypeCode.Object])
- return (Object)value;
- // Need to special case Enum because typecode will be underlying type, e.g. Int32
- if (rtTargetType == EnumType)
- return (Enum)value;
- if (rtTargetType == ConvertTypes[(int)TypeCode.DBNull])
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_DBNull"));
- if (rtTargetType == ConvertTypes[(int)TypeCode.Empty])
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_Empty"));
- }
-
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", value.GetType().FullName, targetType.FullName));
- }
-
- public static Object ChangeType(Object value, Type conversionType) {
- return ChangeType(value, conversionType, Thread.CurrentThread.CurrentCulture);
- }
-
- public static Object ChangeType(Object value, Type conversionType, IFormatProvider provider) {
- if( conversionType == null) {
- throw new ArgumentNullException(nameof(conversionType));
- }
- Contract.EndContractBlock();
-
- if( value == null ) {
- if(conversionType.IsValueType) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCastNullToValueType"));
- }
- return null;
- }
-
- IConvertible ic = value as IConvertible;
- if (ic == null) {
- if ( value.GetType() == conversionType) {
- return value;
- }
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_IConvertible"));
- }
-
- RuntimeType rtConversionType = conversionType as RuntimeType;
-
- if (rtConversionType==ConvertTypes[(int)TypeCode.Boolean])
- return ic.ToBoolean(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Char])
- return ic.ToChar(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.SByte])
- return ic.ToSByte(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Byte])
- return ic.ToByte(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Int16])
- return ic.ToInt16(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.UInt16])
- return ic.ToUInt16(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Int32])
- return ic.ToInt32(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.UInt32])
- return ic.ToUInt32(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Int64])
- return ic.ToInt64(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.UInt64])
- return ic.ToUInt64(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Single])
- return ic.ToSingle(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Double])
- return ic.ToDouble(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Decimal])
- return ic.ToDecimal(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.DateTime])
- return ic.ToDateTime(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.String])
- return ic.ToString(provider);
- if (rtConversionType==ConvertTypes[(int)TypeCode.Object])
- return (Object)value;
-
- return ic.ToType(conversionType, provider);
- }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowCharOverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_Char")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowByteOverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_Byte")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowSByteOverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_SByte")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowInt16OverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_Int16")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowUInt16OverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_UInt16")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowInt32OverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_Int32")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowUInt32OverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_UInt32")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowInt64OverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_Int64")); }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void ThrowUInt64OverflowException() { throw new OverflowException(Environment.GetResourceString("Overflow_UInt64")); }
-
- // Conversions to Boolean
- public static bool ToBoolean(Object value) {
- return value == null? false: ((IConvertible)value).ToBoolean(null);
- }
-
- public static bool ToBoolean(Object value, IFormatProvider provider) {
- return value == null? false: ((IConvertible)value).ToBoolean(provider);
- }
-
-
- public static bool ToBoolean(bool value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static bool ToBoolean(sbyte value) {
- return value != 0;
- }
-
- // To be consistent with IConvertible in the base data types else we get different semantics
- // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
- public static bool ToBoolean(char value) {
- return ((IConvertible)value).ToBoolean(null);
- }
-
- public static bool ToBoolean(byte value) {
- return value != 0;
- }
-
-
- public static bool ToBoolean(short value) {
- return value != 0;
- }
-
- [CLSCompliant(false)]
- public static bool ToBoolean(ushort value) {
- return value != 0;
- }
-
- public static bool ToBoolean(int value) {
- return value != 0;
- }
-
- [CLSCompliant(false)]
- public static bool ToBoolean(uint value) {
- return value != 0;
- }
-
- public static bool ToBoolean(long value) {
- return value != 0;
- }
-
- [CLSCompliant(false)]
- public static bool ToBoolean(ulong value) {
- return value != 0;
- }
-
- public static bool ToBoolean(String value) {
- if (value == null)
- return false;
- return Boolean.Parse(value);
- }
-
- public static bool ToBoolean(String value, IFormatProvider provider) {
- if (value == null)
- return false;
- return Boolean.Parse(value);
- }
-
- public static bool ToBoolean(float value)
- {
- return value != 0;
- }
-
- public static bool ToBoolean(double value)
- {
- return value != 0;
- }
-
- public static bool ToBoolean(decimal value)
- {
- return value != 0;
- }
-
- public static bool ToBoolean(DateTime value)
- {
- return ((IConvertible)value).ToBoolean(null);
- }
-
- // Disallowed conversions to Boolean
- // public static bool ToBoolean(TimeSpan value)
-
- // Conversions to Char
-
-
- public static char ToChar(object value) {
- return value == null? (char)0: ((IConvertible)value).ToChar(null);
- }
-
- public static char ToChar(object value, IFormatProvider provider) {
- return value == null? (char)0: ((IConvertible)value).ToChar(provider);
- }
-
- public static char ToChar(bool value) {
- return ((IConvertible)value).ToChar(null);
- }
-
- public static char ToChar(char value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static char ToChar(sbyte value) {
- if (value < 0) ThrowCharOverflowException();
- Contract.EndContractBlock();
- return (char)value;
- }
-
- public static char ToChar(byte value) {
- return (char)value;
- }
-
- public static char ToChar(short value) {
- if (value < 0) ThrowCharOverflowException();
- Contract.EndContractBlock();
- return (char)value;
- }
-
- [CLSCompliant(false)]
- public static char ToChar(ushort value) {
- return (char)value;
- }
-
- public static char ToChar(int value) {
- if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException();
- Contract.EndContractBlock();
- return (char)value;
- }
-
- [CLSCompliant(false)]
- public static char ToChar(uint value) {
- if (value > Char.MaxValue) ThrowCharOverflowException();
- Contract.EndContractBlock();
- return (char)value;
- }
-
- public static char ToChar(long value) {
- if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException();
- Contract.EndContractBlock();
- return (char)value;
- }
-
- [CLSCompliant(false)]
- public static char ToChar(ulong value) {
- if (value > Char.MaxValue) ThrowCharOverflowException();
- Contract.EndContractBlock();
- return (char)value;
- }
-
- //
- // @VariantSwitch
- // Remove FormatExceptions;
- //
- public static char ToChar(String value) {
- return ToChar(value, null);
- }
-
- public static char ToChar(String value, IFormatProvider provider) {
- if (value == null)
- throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
-
- if (value.Length != 1)
- throw new FormatException(Environment.GetResourceString(ResId.Format_NeedSingleChar));
-
- return value[0];
- }
-
- // To be consistent with IConvertible in the base data types else we get different semantics
- // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
- public static char ToChar(float value)
- {
- return ((IConvertible)value).ToChar(null);
- }
-
- // To be consistent with IConvertible in the base data types else we get different semantics
- // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
- public static char ToChar(double value)
- {
- return ((IConvertible)value).ToChar(null);
- }
-
- // To be consistent with IConvertible in the base data types else we get different semantics
- // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
- public static char ToChar(decimal value)
- {
- return ((IConvertible)value).ToChar(null);
- }
-
- public static char ToChar(DateTime value)
- {
- return ((IConvertible)value).ToChar(null);
- }
-
-
- // Disallowed conversions to Char
- // public static char ToChar(TimeSpan value)
-
- // Conversions to SByte
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(object value) {
- return value == null? (sbyte)0: ((IConvertible)value).ToSByte(null);
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(object value, IFormatProvider provider) {
- return value == null? (sbyte)0: ((IConvertible)value).ToSByte(provider);
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(bool value) {
- return value? (sbyte)Boolean.True: (sbyte)Boolean.False;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(sbyte value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(char value) {
- if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(byte value) {
- if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(short value) {
- if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(ushort value) {
- if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(int value) {
- if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(uint value) {
- if (value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(long value) {
- if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(ulong value) {
- if (value > (ulong)SByte.MaxValue) ThrowSByteOverflowException();
- Contract.EndContractBlock();
- return (sbyte)value;
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(float value) {
- return ToSByte((double)value);
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(double value) {
- return ToSByte(ToInt32(value));
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(decimal value) {
- return Decimal.ToSByte(Decimal.Round(value, 0));
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(String value) {
- if (value == null)
- return 0;
- return SByte.Parse(value, CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(String value, IFormatProvider provider) {
- return SByte.Parse(value, NumberStyles.Integer, provider);
- }
-
- [CLSCompliant(false)]
- public static sbyte ToSByte(DateTime value)
- {
- return ((IConvertible)value).ToSByte(null);
- }
-
- // Disallowed conversions to SByte
- // public static sbyte ToSByte(TimeSpan value)
-
- // Conversions to Byte
-
- public static byte ToByte(object value) {
- return value == null? (byte)0: ((IConvertible)value).ToByte(null);
- }
-
- public static byte ToByte(object value, IFormatProvider provider) {
- return value == null? (byte)0: ((IConvertible)value).ToByte(provider);
- }
-
- public static byte ToByte(bool value) {
- return value? (byte)Boolean.True: (byte)Boolean.False;
- }
-
- public static byte ToByte(byte value) {
- return value;
- }
-
- public static byte ToByte(char value) {
- if (value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- [CLSCompliant(false)]
- public static byte ToByte(sbyte value) {
- if (value < Byte.MinValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- public static byte ToByte(short value) {
- if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- [CLSCompliant(false)]
- public static byte ToByte(ushort value) {
- if (value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- public static byte ToByte(int value) {
- if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- [CLSCompliant(false)]
- public static byte ToByte(uint value) {
- if (value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- public static byte ToByte(long value) {
- if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- [CLSCompliant(false)]
- public static byte ToByte(ulong value) {
- if (value > Byte.MaxValue) ThrowByteOverflowException();
- Contract.EndContractBlock();
- return (byte)value;
- }
-
- public static byte ToByte(float value) {
- return ToByte((double)value);
- }
-
- public static byte ToByte(double value) {
- return ToByte(ToInt32(value));
- }
-
- public static byte ToByte(decimal value) {
- return Decimal.ToByte(Decimal.Round(value, 0));
- }
-
- public static byte ToByte(String value) {
- if (value == null)
- return 0;
- return Byte.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static byte ToByte(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return Byte.Parse(value, NumberStyles.Integer, provider);
- }
-
- public static byte ToByte(DateTime value)
- {
- return ((IConvertible)value).ToByte(null);
- }
-
-
- // Disallowed conversions to Byte
- // public static byte ToByte(TimeSpan value)
-
- // Conversions to Int16
-
- public static short ToInt16(object value) {
- return value == null? (short)0: ((IConvertible)value).ToInt16(null);
- }
-
- public static short ToInt16(object value, IFormatProvider provider) {
- return value == null? (short)0: ((IConvertible)value).ToInt16(provider);
- }
-
- public static short ToInt16(bool value) {
- return value? (short)Boolean.True: (short)Boolean.False;
- }
-
- public static short ToInt16(char value) {
- if (value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
- return (short)value;
- }
-
- [CLSCompliant(false)]
- public static short ToInt16(sbyte value) {
- return value;
- }
-
- public static short ToInt16(byte value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static short ToInt16(ushort value) {
- if (value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
- return (short)value;
- }
-
- public static short ToInt16(int value) {
- if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
- return (short)value;
- }
-
- [CLSCompliant(false)]
- public static short ToInt16(uint value) {
- if (value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
- return (short)value;
- }
-
- public static short ToInt16(short value) {
- return value;
- }
-
- public static short ToInt16(long value) {
- if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
- return (short)value;
- }
-
- [CLSCompliant(false)]
- public static short ToInt16(ulong value) {
- if (value > (ulong)Int16.MaxValue) ThrowInt16OverflowException();
- Contract.EndContractBlock();
- return (short)value;
- }
-
- public static short ToInt16(float value) {
- return ToInt16((double)value);
- }
-
- public static short ToInt16(double value) {
- return ToInt16(ToInt32(value));
- }
-
- public static short ToInt16(decimal value) {
- return Decimal.ToInt16(Decimal.Round(value, 0));
- }
-
- public static short ToInt16(String value) {
- if (value == null)
- return 0;
- return Int16.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static short ToInt16(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return Int16.Parse(value, NumberStyles.Integer, provider);
- }
-
- public static short ToInt16(DateTime value)
- {
- return ((IConvertible)value).ToInt16(null);
- }
-
-
- // Disallowed conversions to Int16
- // public static short ToInt16(TimeSpan value)
-
- // Conversions to UInt16
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(object value) {
- return value == null? (ushort)0: ((IConvertible)value).ToUInt16(null);
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(object value, IFormatProvider provider) {
- return value == null? (ushort)0: ((IConvertible)value).ToUInt16(provider);
- }
-
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(bool value) {
- return value? (ushort)Boolean.True: (ushort)Boolean.False;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(char value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(sbyte value) {
- if (value < 0) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
- return (ushort)value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(byte value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(short value) {
- if (value < 0) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
- return (ushort)value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(int value) {
- if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
- return (ushort)value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(ushort value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(uint value) {
- if (value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
- return (ushort)value;
- }
-
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(long value) {
- if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
- return (ushort)value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(ulong value) {
- if (value > UInt16.MaxValue) ThrowUInt16OverflowException();
- Contract.EndContractBlock();
- return (ushort)value;
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(float value) {
- return ToUInt16((double)value);
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(double value) {
- return ToUInt16(ToInt32(value));
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(decimal value) {
- return Decimal.ToUInt16(Decimal.Round(value, 0));
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(String value) {
- if (value == null)
- return 0;
- return UInt16.Parse(value, CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return UInt16.Parse(value, NumberStyles.Integer, provider);
- }
-
- [CLSCompliant(false)]
- public static ushort ToUInt16(DateTime value)
- {
- return ((IConvertible)value).ToUInt16(null);
- }
-
- // Disallowed conversions to UInt16
- // public static ushort ToUInt16(TimeSpan value)
-
- // Conversions to Int32
-
- public static int ToInt32(object value) {
- return value == null? 0: ((IConvertible)value).ToInt32(null);
- }
-
- public static int ToInt32(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToInt32(provider);
- }
-
-
- public static int ToInt32(bool value) {
- return value? Boolean.True: Boolean.False;
- }
-
- public static int ToInt32(char value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static int ToInt32(sbyte value) {
- return value;
- }
-
- public static int ToInt32(byte value) {
- return value;
- }
-
- public static int ToInt32(short value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static int ToInt32(ushort value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static int ToInt32(uint value) {
- if (value > Int32.MaxValue) ThrowInt32OverflowException();
- Contract.EndContractBlock();
- return (int)value;
- }
-
- public static int ToInt32(int value) {
- return value;
- }
-
- public static int ToInt32(long value) {
- if (value < Int32.MinValue || value > Int32.MaxValue) ThrowInt32OverflowException();
- Contract.EndContractBlock();
- return (int)value;
- }
-
- [CLSCompliant(false)]
- public static int ToInt32(ulong value) {
- if (value > Int32.MaxValue) ThrowInt32OverflowException();
- Contract.EndContractBlock();
- return (int)value;
- }
-
- public static int ToInt32(float value) {
- return ToInt32((double)value);
- }
-
- public static int ToInt32(double value) {
- if (value >= 0) {
- if (value < 2147483647.5) {
- int result = (int)value;
- double dif = value - result;
- if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
- return result;
- }
- }
- else {
- if (value >= -2147483648.5) {
- int result = (int)value;
- double dif = value - result;
- if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
- return result;
- }
- }
- throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
- }
-
- public static int ToInt32(decimal value) {
- return Decimal.FCallToInt32(value);
- }
-
- public static int ToInt32(String value) {
- if (value == null)
- return 0;
- return Int32.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static int ToInt32(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return Int32.Parse(value, NumberStyles.Integer, provider);
- }
-
- public static int ToInt32(DateTime value)
- {
- return ((IConvertible)value).ToInt32(null);
- }
-
-
- // Disallowed conversions to Int32
- // public static int ToInt32(TimeSpan value)
-
- // Conversions to UInt32
-
- [CLSCompliant(false)]
- public static uint ToUInt32(object value) {
- return value == null? 0: ((IConvertible)value).ToUInt32(null);
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToUInt32(provider);
- }
-
-
- [CLSCompliant(false)]
- public static uint ToUInt32(bool value) {
- return value? (uint)Boolean.True: (uint)Boolean.False;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(char value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(sbyte value) {
- if (value < 0) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
- return (uint)value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(byte value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(short value) {
- if (value < 0) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
- return (uint)value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(ushort value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(int value) {
- if (value < 0) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
- return (uint)value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(uint value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(long value) {
- if (value < 0 || value > UInt32.MaxValue) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
- return (uint)value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(ulong value) {
- if (value > UInt32.MaxValue) ThrowUInt32OverflowException();
- Contract.EndContractBlock();
- return (uint)value;
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(float value) {
- return ToUInt32((double)value);
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(double value) {
- if (value >= -0.5 && value < 4294967295.5) {
- uint result = (uint)value;
- double dif = value - result;
- if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
- return result;
- }
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(decimal value) {
- return Decimal.ToUInt32(Decimal.Round(value, 0));
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(String value) {
- if (value == null)
- return 0;
- return UInt32.Parse(value, CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return UInt32.Parse(value, NumberStyles.Integer, provider);
- }
-
- [CLSCompliant(false)]
- public static uint ToUInt32(DateTime value)
- {
- return ((IConvertible)value).ToUInt32(null);
- }
-
- // Disallowed conversions to UInt32
- // public static uint ToUInt32(TimeSpan value)
-
- // Conversions to Int64
-
- public static long ToInt64(object value) {
- return value == null? 0: ((IConvertible)value).ToInt64(null);
- }
-
- public static long ToInt64(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToInt64(provider);
- }
-
-
- public static long ToInt64(bool value) {
- return value? Boolean.True: Boolean.False;
- }
-
- public static long ToInt64(char value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static long ToInt64(sbyte value) {
- return value;
- }
-
- public static long ToInt64(byte value) {
- return value;
- }
-
- public static long ToInt64(short value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static long ToInt64(ushort value) {
- return value;
- }
-
- public static long ToInt64(int value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static long ToInt64(uint value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static long ToInt64(ulong value) {
- if (value > Int64.MaxValue) ThrowInt64OverflowException();
- Contract.EndContractBlock();
- return (long)value;
- }
-
- public static long ToInt64(long value) {
- return value;
- }
-
-
- public static long ToInt64(float value) {
- return ToInt64((double)value);
- }
-
- public static long ToInt64(double value) {
- return checked((long)Math.Round(value));
- }
-
- public static long ToInt64(decimal value) {
- return Decimal.ToInt64(Decimal.Round(value, 0));
- }
-
- public static long ToInt64(string value) {
- if (value == null)
- return 0;
- return Int64.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static long ToInt64(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return Int64.Parse(value, NumberStyles.Integer, provider);
- }
-
- public static long ToInt64(DateTime value)
- {
- return ((IConvertible)value).ToInt64(null);
- }
-
- // Disallowed conversions to Int64
- // public static long ToInt64(TimeSpan value)
-
- // Conversions to UInt64
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(object value) {
- return value == null? 0: ((IConvertible)value).ToUInt64(null);
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToUInt64(provider);
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(bool value) {
- return value? (ulong)Boolean.True: (ulong)Boolean.False;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(char value) {
- return value;
- }
-
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(sbyte value) {
- if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
- return (ulong)value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(byte value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(short value) {
- if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
- return (ulong)value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(ushort value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(int value) {
- if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
- return (ulong)value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(uint value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(long value) {
- if (value < 0) ThrowUInt64OverflowException();
- Contract.EndContractBlock();
- return (ulong)value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(UInt64 value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(float value) {
- return ToUInt64((double)value);
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(double value) {
- return checked((ulong)Math.Round(value));
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(decimal value) {
- return Decimal.ToUInt64(Decimal.Round(value, 0));
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(String value) {
- if (value == null)
- return 0;
- return UInt64.Parse(value, CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return UInt64.Parse(value, NumberStyles.Integer, provider);
- }
-
- [CLSCompliant(false)]
- public static ulong ToUInt64(DateTime value)
- {
- return ((IConvertible)value).ToUInt64(null);
- }
-
- // Disallowed conversions to UInt64
- // public static ulong ToUInt64(TimeSpan value)
-
- // Conversions to Single
-
- public static float ToSingle(object value) {
- return value == null? 0: ((IConvertible)value).ToSingle(null);
- }
-
- public static float ToSingle(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToSingle(provider);
- }
-
- [CLSCompliant(false)]
- public static float ToSingle(sbyte value) {
- return value;
- }
-
- public static float ToSingle(byte value) {
- return value;
- }
-
- public static float ToSingle(char value) {
- return ((IConvertible)value).ToSingle(null);
- }
-
- public static float ToSingle(short value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static float ToSingle(ushort value) {
- return value;
- }
-
- public static float ToSingle(int value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static float ToSingle(uint value) {
- return value;
- }
-
- public static float ToSingle(long value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static float ToSingle(ulong value) {
- return value;
- }
-
- public static float ToSingle(float value) {
- return value;
- }
-
- public static float ToSingle(double value) {
- return (float)value;
- }
-
- public static float ToSingle(decimal value) {
- return (float)value;
- }
-
- public static float ToSingle(String value) {
- if (value == null)
- return 0;
- return Single.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static float ToSingle(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return Single.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
- }
-
-
- public static float ToSingle(bool value)
- {
- return value? Boolean.True: Boolean.False;
- }
-
- public static float ToSingle(DateTime value)
- {
- return ((IConvertible)value).ToSingle(null);
- }
-
- // Disallowed conversions to Single
- // public static float ToSingle(TimeSpan value)
-
- // Conversions to Double
-
- public static double ToDouble(object value) {
- return value == null? 0: ((IConvertible)value).ToDouble(null);
- }
-
- public static double ToDouble(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToDouble(provider);
- }
-
-
- [CLSCompliant(false)]
- public static double ToDouble(sbyte value) {
- return value;
- }
-
- public static double ToDouble(byte value) {
- return value;
- }
-
- public static double ToDouble(short value) {
- return value;
- }
-
- public static double ToDouble(char value) {
- return ((IConvertible)value).ToDouble(null);
- }
-
- [CLSCompliant(false)]
- public static double ToDouble(ushort value) {
- return value;
- }
-
- public static double ToDouble(int value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static double ToDouble(uint value) {
- return value;
- }
-
- public static double ToDouble(long value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static double ToDouble(ulong value) {
- return value;
- }
-
- public static double ToDouble(float value) {
- return value;
- }
-
- public static double ToDouble(double value) {
- return value;
- }
-
- public static double ToDouble(decimal value) {
- return (double)value;
- }
-
- public static double ToDouble(String value) {
- if (value == null)
- return 0;
- return Double.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static double ToDouble(String value, IFormatProvider provider) {
- if (value == null)
- return 0;
- return Double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
- }
-
- public static double ToDouble(bool value) {
- return value? Boolean.True: Boolean.False;
- }
-
- public static double ToDouble(DateTime value)
- {
- return ((IConvertible)value).ToDouble(null);
- }
-
- // Disallowed conversions to Double
- // public static double ToDouble(TimeSpan value)
-
- // Conversions to Decimal
-
- public static decimal ToDecimal(object value) {
- return value == null? 0: ((IConvertible)value).ToDecimal(null);
- }
-
- public static decimal ToDecimal(object value, IFormatProvider provider) {
- return value == null? 0: ((IConvertible)value).ToDecimal(provider);
- }
-
- [CLSCompliant(false)]
- public static decimal ToDecimal(sbyte value) {
- return value;
- }
-
- public static decimal ToDecimal(byte value) {
- return value;
- }
-
- public static decimal ToDecimal(char value) {
- return ((IConvertible)value).ToDecimal(null);
- }
-
- public static decimal ToDecimal(short value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static decimal ToDecimal(ushort value) {
- return value;
- }
-
- public static decimal ToDecimal(int value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static decimal ToDecimal(uint value) {
- return value;
- }
-
- public static decimal ToDecimal(long value) {
- return value;
- }
-
- [CLSCompliant(false)]
- public static decimal ToDecimal(ulong value) {
- return value;
- }
-
- public static decimal ToDecimal(float value) {
- return (decimal)value;
- }
-
- public static decimal ToDecimal(double value) {
- return (decimal)value;
- }
-
- public static decimal ToDecimal(String value) {
- if (value == null)
- return 0m;
- return Decimal.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static Decimal ToDecimal(String value, IFormatProvider provider) {
- if (value == null)
- return 0m;
- return Decimal.Parse(value, NumberStyles.Number, provider);
- }
-
- public static decimal ToDecimal(decimal value) {
- return value;
- }
-
- public static decimal ToDecimal(bool value) {
- return value? Boolean.True: Boolean.False;
- }
-
- public static decimal ToDecimal(DateTime value)
- {
- return ((IConvertible)value).ToDecimal(null);
- }
-
- // Disallowed conversions to Decimal
- // public static decimal ToDecimal(TimeSpan value)
-
- // Conversions to DateTime
-
- public static DateTime ToDateTime(DateTime value) {
- return value;
- }
-
- public static DateTime ToDateTime(object value) {
- return value == null? DateTime.MinValue: ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(object value, IFormatProvider provider) {
- return value == null? DateTime.MinValue: ((IConvertible)value).ToDateTime(provider);
- }
-
- public static DateTime ToDateTime(String value) {
- if (value == null)
- return new DateTime(0);
- return DateTime.Parse(value, CultureInfo.CurrentCulture);
- }
-
- public static DateTime ToDateTime(String value, IFormatProvider provider) {
- if (value == null)
- return new DateTime(0);
- return DateTime.Parse(value, provider);
- }
-
- [CLSCompliant(false)]
- public static DateTime ToDateTime(sbyte value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(byte value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(short value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- [CLSCompliant(false)]
- public static DateTime ToDateTime(ushort value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(int value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- [CLSCompliant(false)]
- public static DateTime ToDateTime(uint value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(long value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- [CLSCompliant(false)]
- public static DateTime ToDateTime(ulong value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(bool value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(char value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(float value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(double value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- public static DateTime ToDateTime(decimal value) {
- return ((IConvertible)value).ToDateTime(null);
- }
-
- // Disallowed conversions to DateTime
- // public static DateTime ToDateTime(TimeSpan value)
-
- // Conversions to String
-
- public static string ToString(Object value) {
- return ToString(value,null);
- }
-
- public static string ToString(Object value, IFormatProvider provider) {
- IConvertible ic = value as IConvertible;
- if (ic != null)
- return ic.ToString(provider);
- IFormattable formattable = value as IFormattable;
- if (formattable != null)
- return formattable.ToString(null, provider);
- return value == null? String.Empty: value.ToString();
- }
-
- public static string ToString(bool value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString();
- }
-
- public static string ToString(bool value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(char value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return Char.ToString(value);
- }
-
- public static string ToString(char value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- [CLSCompliant(false)]
- public static string ToString(sbyte value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static string ToString(sbyte value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(byte value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(byte value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(short value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(short value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- [CLSCompliant(false)]
- public static string ToString(ushort value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static string ToString(ushort value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(int value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(int value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- [CLSCompliant(false)]
- public static string ToString(uint value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static string ToString(uint value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(long value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(long value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- [CLSCompliant(false)]
- public static string ToString(ulong value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- [CLSCompliant(false)]
- public static string ToString(ulong value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(float value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(float value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(double value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(double value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(decimal value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(CultureInfo.CurrentCulture);
- }
-
- public static string ToString(Decimal value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static string ToString(DateTime value) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString();
- }
-
- public static string ToString(DateTime value, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() != null);
- return value.ToString(provider);
- }
-
- public static String ToString(String value) {
- Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here.
- return value;
- }
-
- public static String ToString(String value,IFormatProvider provider) {
- Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here.
- return value; // avoid the null check
- }
-
-
- //
- // Conversions which understand Base XXX numbers.
- //
- // Parses value in base base. base can only
- // be 2, 8, 10, or 16. If base is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- public static byte ToByte (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- int r = ParseNumbers.StringToInt(value,fromBase,ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
- if (r < Byte.MinValue || r > Byte.MaxValue)
- ThrowByteOverflowException();
- return (byte) r;
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- [CLSCompliant(false)]
- public static sbyte ToSByte (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- int r = ParseNumbers.StringToInt(value,fromBase,ParseNumbers.IsTight | ParseNumbers.TreatAsI1);
- if (fromBase != 10 && r <= Byte.MaxValue)
- return (sbyte)r;
-
- if (r < SByte.MinValue || r > SByte.MaxValue)
- ThrowSByteOverflowException();
- return (sbyte) r;
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- public static short ToInt16 (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- int r = ParseNumbers.StringToInt(value,fromBase,ParseNumbers.IsTight | ParseNumbers.TreatAsI2);
- if (fromBase != 10 && r <= UInt16.MaxValue)
- return (short)r;
-
- if (r < Int16.MinValue || r > Int16.MaxValue)
- ThrowInt16OverflowException();
- return (short) r;
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- [CLSCompliant(false)]
- public static ushort ToUInt16 (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- int r = ParseNumbers.StringToInt(value,fromBase,ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
- if (r < UInt16.MinValue || r > UInt16.MaxValue)
- ThrowUInt16OverflowException();
- return (ushort) r;
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- public static int ToInt32 (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return ParseNumbers.StringToInt(value,fromBase,ParseNumbers.IsTight);
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- [CLSCompliant(false)]
- public static uint ToUInt32 (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return (uint) ParseNumbers.StringToInt(value,fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight);
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- public static long ToInt64 (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return ParseNumbers.StringToLong(value,fromBase,ParseNumbers.IsTight);
- }
-
- // Parses value in base fromBase. fromBase can only
- // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
- // by 0x; any other leading or trailing characters cause an error.
- //
- [CLSCompliant(false)]
- public static ulong ToUInt64 (String value, int fromBase) {
- if (fromBase!=2 && fromBase!=8 && fromBase!=10 && fromBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return (ulong) ParseNumbers.StringToLong(value,fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight);
- }
-
- // Convert the byte value to a string in base fromBase
- public static String ToString (byte value, int toBase) {
- if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1);
- }
-
- // Convert the Int16 value to a string in base fromBase
- public static String ToString (short value, int toBase) {
- if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2);
- }
-
- // Convert the Int32 value to a string in base toBase
- public static String ToString (int value, int toBase) {
- if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return ParseNumbers.IntToString(value, toBase, -1, ' ', 0);
- }
-
- // Convert the Int64 value to a string in base toBase
- public static String ToString (long value, int toBase) {
- if (toBase!=2 && toBase!=8 && toBase!=10 && toBase!=16) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidBase"));
- }
- Contract.EndContractBlock();
- return ParseNumbers.LongToString(value, toBase, -1, ' ', 0);
- }
-
- public static String ToBase64String(byte[] inArray) {
- if (inArray==null) {
- throw new ArgumentNullException(nameof(inArray));
- }
- Contract.Ensures(Contract.Result<string>() != null);
- Contract.EndContractBlock();
- return ToBase64String(inArray, 0, inArray.Length, Base64FormattingOptions.None);
- }
-
- public static String ToBase64String(byte[] inArray, Base64FormattingOptions options) {
- if (inArray==null) {
- throw new ArgumentNullException(nameof(inArray));
- }
- Contract.Ensures(Contract.Result<string>() != null);
- Contract.EndContractBlock();
- return ToBase64String(inArray, 0, inArray.Length, options);
- }
-
- public static String ToBase64String(byte[] inArray, int offset, int length) {
- return ToBase64String(inArray, offset, length, Base64FormattingOptions.None);
- }
-
- public static unsafe String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) {
- //Do data verfication
- if (inArray==null)
- throw new ArgumentNullException(nameof(inArray));
- if (length<0)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (offset<0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
- Contract.Ensures(Contract.Result<string>() != null);
- Contract.EndContractBlock();
-
- int inArrayLength;
- int stringLength;
-
- inArrayLength = inArray.Length;
- if (offset > (inArrayLength - length))
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
-
- if (inArrayLength == 0)
- return String.Empty;
-
- bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
- //Create the new string. This is the maximally required length.
- stringLength = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
-
- string returnString = string.FastAllocateString(stringLength);
- fixed (char* outChars = returnString){
- fixed (byte* inData = &inArray[0]) {
- int j = ConvertToBase64Array(outChars,inData,offset,length, insertLineBreaks);
- BCLDebug.Assert(returnString.Length == j, "returnString.Length == j");
- return returnString;
- }
- }
- }
-
- public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= outArray.Length);
- Contract.EndContractBlock();
-
- return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
- }
-
- public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) {
- //Do data verfication
- if (inArray==null)
- throw new ArgumentNullException(nameof(inArray));
- if (outArray==null)
- throw new ArgumentNullException(nameof(outArray));
- if (length<0)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- if (offsetIn<0)
- throw new ArgumentOutOfRangeException(nameof(offsetIn), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- if (offsetOut<0)
- throw new ArgumentOutOfRangeException(nameof(offsetOut), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
-
- if( options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
- }
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() <= outArray.Length);
- Contract.EndContractBlock();
-
-
- int retVal;
-
- int inArrayLength;
- int outArrayLength;
- int numElementsToCopy;
-
- inArrayLength = inArray.Length;
-
- if (offsetIn > (int)(inArrayLength - length))
- throw new ArgumentOutOfRangeException(nameof(offsetIn), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
-
- if (inArrayLength == 0)
- return 0;
-
- bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
- //This is the maximally required length that must be available in the char array
- outArrayLength = outArray.Length;
-
- // Length of the char buffer required
- numElementsToCopy = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
-
- if (offsetOut > (int)(outArrayLength - numElementsToCopy))
- throw new ArgumentOutOfRangeException(nameof(offsetOut), Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
-
- fixed (char* outChars = &outArray[offsetOut]) {
- fixed (byte* inData = &inArray[0]) {
- retVal = ConvertToBase64Array(outChars,inData,offsetIn,length, insertLineBreaks);
- }
- }
-
- return retVal;
- }
-
- private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks) {
- int lengthmod3 = length%3;
- int calcLength = offset + (length - lengthmod3);
- int j=0;
- int charcount = 0;
- //Convert three bytes at a time to base64 notation. This will consume 4 chars.
- int i;
-
- // get a pointer to the base64Table to avoid unnecessary range checking
- fixed(char* base64 = &base64Table[0]) {
- for (i=offset; i<calcLength; i+=3)
- {
- if (insertLineBreaks) {
- if (charcount == base64LineBreakPosition) {
- outChars[j++] = '\r';
- outChars[j++] = '\n';
- charcount = 0;
- }
- charcount += 4;
- }
- outChars[j] = base64[(inData[i]&0xfc)>>2];
- outChars[j+1] = base64[((inData[i]&0x03)<<4) | ((inData[i+1]&0xf0)>>4)];
- outChars[j+2] = base64[((inData[i+1]&0x0f)<<2) | ((inData[i+2]&0xc0)>>6)];
- outChars[j+3] = base64[(inData[i+2]&0x3f)];
- j += 4;
- }
-
- //Where we left off before
- i = calcLength;
-
- if (insertLineBreaks && (lengthmod3 !=0) && (charcount == base64LineBreakPosition)) {
- outChars[j++] = '\r';
- outChars[j++] = '\n';
- }
-
- switch(lengthmod3)
- {
- case 2: //One character padding needed
- outChars[j] = base64[(inData[i]&0xfc)>>2];
- outChars[j+1] = base64[((inData[i]&0x03)<<4)|((inData[i+1]&0xf0)>>4)];
- outChars[j+2] = base64[(inData[i+1]&0x0f)<<2];
- outChars[j+3] = base64[64]; //Pad
- j+=4;
- break;
- case 1: // Two character padding needed
- outChars[j] = base64[(inData[i]&0xfc)>>2];
- outChars[j+1] = base64[(inData[i]&0x03)<<4];
- outChars[j+2] = base64[64]; //Pad
- outChars[j+3] = base64[64]; //Pad
- j+=4;
- break;
- }
- }
-
- return j;
- }
-
- private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bool insertLineBreaks) {
- long outlen = ((long)inputLength) / 3 * 4; // the base length - we want integer division here.
- outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder
-
- if (outlen == 0)
- return 0;
-
- if (insertLineBreaks) {
- long newLines = outlen / base64LineBreakPosition;
- if ((outlen % base64LineBreakPosition) == 0) {
- --newLines;
- }
- outlen += newLines * 2; // the number of line break chars we'll add, "\r\n"
- }
-
- // If we overflow an int then we cannot allocate enough
- // memory to output the value so throw
- if (outlen > int.MaxValue)
- throw new OutOfMemoryException();
-
- return (int)outlen;
- }
-
-
- /// <summary>
- /// Converts the specified string, which encodes binary data as Base64 digits, to the equivalent byte array.
- /// </summary>
- /// <param name="s">The string to convert</param>
- /// <returns>The array of bytes represented by the specifed Base64 string.</returns>
- public static Byte[] FromBase64String(String s) {
-
- // "s" is an unfortunate parameter name, but we need to keep it for backward compat.
-
- if (s == null)
- throw new ArgumentNullException(nameof(s));
-
- Contract.EndContractBlock();
-
- unsafe {
- fixed (Char* sPtr = s) {
-
- return FromBase64CharPtr(sPtr, s.Length);
- }
- }
- }
-
-
- /// <summary>
- /// Converts the specified range of a Char array, which encodes binary data as Base64 digits, to the equivalent byte array.
- /// </summary>
- /// <param name="inArray">Chars representing Base64 encoding characters</param>
- /// <param name="offset">A position within the input array.</param>
- /// <param name="length">Number of element to convert.</param>
- /// <returns>The array of bytes represented by the specified Base64 encoding characters.</returns>
- public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length) {
-
- if (inArray == null)
- throw new ArgumentNullException(nameof(inArray));
-
- if (length < 0)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
-
- if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
-
- if (offset > inArray.Length - length)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
-
- Contract.EndContractBlock();
-
- unsafe {
- fixed (Char* inArrayPtr = inArray) {
-
- return FromBase64CharPtr(inArrayPtr + offset, length);
- }
- }
- }
-
-
-
- /// <summary>
- /// Convert Base64 encoding characters to bytes:
- /// - Compute result length exactly by actually walking the input;
- /// - Allocate new result array based on computation;
- /// - Decode input into the new array;
- /// </summary>
- /// <param name="inputPtr">Pointer to the first input char</param>
- /// <param name="inputLength">Number of input chars</param>
- /// <returns></returns>
- private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength) {
-
- // The validity of parameters much be checked by callers, thus we are Critical here.
-
- Debug.Assert(0 <= inputLength);
-
- // We need to get rid of any trailing white spaces.
- // Otherwise we would be rejecting input such as "abc= ":
- while (inputLength > 0)
- {
- Int32 lastChar = inputPtr[inputLength - 1];
- if (lastChar != (Int32) ' ' && lastChar != (Int32) '\n' && lastChar != (Int32) '\r' && lastChar != (Int32) '\t')
- break;
- inputLength--;
- }
-
- // Compute the output length:
- Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength);
-
- Debug.Assert(0 <= resultLength);
-
- // resultLength can be zero. We will still enter FromBase64_Decode and process the input.
- // It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab").
-
- // Create result byte blob:
- Byte[] decodedBytes = new Byte[resultLength];
-
- // Convert Base64 chars into bytes:
- Int32 actualResultLength;
- fixed (Byte* decodedBytesPtr = decodedBytes)
- actualResultLength = FromBase64_Decode(inputPtr, inputLength, decodedBytesPtr, resultLength);
-
- // Note that actualResultLength can differ from resultLength if the caller is modifying the array
- // as it is being converted. Silently ignore the failure.
- // Consider throwing exception in an non in-place release.
-
- // We are done:
- return decodedBytes;
- }
-
-
- /// <summary>
- /// Decode characters representing a Base64 encoding into bytes:
- /// Walk the input. Every time 4 chars are read, convert them to the 3 corresponding output bytes.
- /// This method is a bit lengthy on purpose. We are trying to avoid jumps to helpers in the loop
- /// to aid performance.
- /// </summary>
- /// <param name="inputPtr">Pointer to first input char</param>
- /// <param name="inputLength">Number of input chars</param>
- /// <param name="destPtr">Pointer to location for the first result byte</param>
- /// <param name="destLength">Max length of the preallocated result buffer</param>
- /// <returns>If the result buffer was not large enough to write all result bytes, return -1;
- /// Otherwise return the number of result bytes actually produced.</returns>
- private static unsafe Int32 FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) {
-
- // You may find this method weird to look at. It’s written for performance, not aesthetics.
- // You will find unrolled loops label jumps and bit manipulations.
-
- const UInt32 intA = (UInt32) 'A';
- const UInt32 inta = (UInt32) 'a';
- const UInt32 int0 = (UInt32) '0';
- const UInt32 intEq = (UInt32) '=';
- const UInt32 intPlus = (UInt32) '+';
- const UInt32 intSlash = (UInt32) '/';
- const UInt32 intSpace = (UInt32) ' ';
- const UInt32 intTab = (UInt32) '\t';
- const UInt32 intNLn = (UInt32) '\n';
- const UInt32 intCRt = (UInt32) '\r';
- const UInt32 intAtoZ = (UInt32) ('Z' - 'A'); // = ('z' - 'a')
- const UInt32 int0to9 = (UInt32) ('9' - '0');
-
- Char* inputPtr = startInputPtr;
- Byte* destPtr = startDestPtr;
-
- // Pointers to the end of input and output:
- Char* endInputPtr = inputPtr + inputLength;
- Byte* endDestPtr = destPtr + destLength;
-
- // Current char code/value:
- UInt32 currCode;
-
- // This 4-byte integer will contain the 4 codes of the current 4-char group.
- // Eeach char codes for 6 bits = 24 bits.
- // The remaining byte will be FF, we use it as a marker when 4 chars have been processed.
- UInt32 currBlockCodes = 0x000000FFu;
-
- unchecked { while (true) {
-
- // break when done:
- if (inputPtr >= endInputPtr)
- goto _AllInputConsumed;
-
- // Get current char:
- currCode = (UInt32) (*inputPtr);
- inputPtr++;
-
- // Determine current char code:
-
- if (currCode - intA <= intAtoZ)
- currCode -= intA;
-
- else if (currCode - inta <= intAtoZ)
- currCode -= (inta - 26u);
-
- else if (currCode - int0 <= int0to9)
- currCode -= (int0 - 52u);
-
- else {
- // Use the slower switch for less common cases:
- switch(currCode) {
-
- // Significant chars:
- case intPlus: currCode = 62u;
- break;
-
- case intSlash: currCode = 63u;
- break;
-
- // Legal no-value chars (we ignore these):
- case intCRt: case intNLn: case intSpace: case intTab:
- continue;
-
- // The equality char is only legal at the end of the input.
- // Jump after the loop to make it easier for the JIT register predictor to do a good job for the loop itself:
- case intEq:
- goto _EqualityCharEncountered;
-
- // Other chars are illegal:
- default:
- throw new FormatException(Environment.GetResourceString("Format_BadBase64Char"));
- }
- }
-
- // Ok, we got the code. Save it:
- currBlockCodes = (currBlockCodes << 6) | currCode;
-
- // Last bit in currBlockCodes will be on after in shifted right 4 times:
- if ((currBlockCodes & 0x80000000u) != 0u) {
-
- if ((Int32) (endDestPtr - destPtr) < 3)
- return -1;
-
- *(destPtr) = (Byte) (currBlockCodes >> 16);
- *(destPtr + 1) = (Byte) (currBlockCodes >> 8);
- *(destPtr + 2) = (Byte) (currBlockCodes);
- destPtr += 3;
-
- currBlockCodes = 0x000000FFu;
- }
-
- }} // unchecked while
-
- // 'd be nice to have an assert that we never get here, but CS0162: Unreachable code detected.
- // Debug.Assert(false, "We only leave the above loop by jumping; should never get here.");
-
- // We jump here out of the loop if we hit an '=':
- _EqualityCharEncountered:
-
- Debug.Assert(currCode == intEq);
-
- // Recall that inputPtr is now one position past where '=' was read.
- // '=' can only be at the last input pos:
- if (inputPtr == endInputPtr) {
-
- // Code is zero for trailing '=':
- currBlockCodes <<= 6;
-
- // The '=' did not complete a 4-group. The input must be bad:
- if ((currBlockCodes & 0x80000000u) == 0u)
- throw new FormatException(Environment.GetResourceString("Format_BadBase64CharArrayLength"));
-
- if ((int)(endDestPtr - destPtr) < 2) // Autch! We underestimated the output length!
- return -1;
-
- // We are good, store bytes form this past group. We had a single "=", so we take two bytes:
- *(destPtr++) = (Byte) (currBlockCodes >> 16);
- *(destPtr++) = (Byte) (currBlockCodes >> 8);
-
- currBlockCodes = 0x000000FFu;
-
- } else { // '=' can also be at the pre-last position iff the last is also a '=' excluding the white spaces:
-
- // We need to get rid of any intermediate white spaces.
- // Otherwise we would be rejecting input such as "abc= =":
- while (inputPtr < (endInputPtr - 1))
- {
- Int32 lastChar = *(inputPtr);
- if (lastChar != (Int32) ' ' && lastChar != (Int32) '\n' && lastChar != (Int32) '\r' && lastChar != (Int32) '\t')
- break;
- inputPtr++;
- }
-
- if (inputPtr == (endInputPtr - 1) && *(inputPtr) == '=') {
-
- // Code is zero for each of the two '=':
- currBlockCodes <<= 12;
-
- // The '=' did not complete a 4-group. The input must be bad:
- if ((currBlockCodes & 0x80000000u) == 0u)
- throw new FormatException(Environment.GetResourceString("Format_BadBase64CharArrayLength"));
-
- if ((Int32) (endDestPtr - destPtr) < 1) // Autch! We underestimated the output length!
- return -1;
-
- // We are good, store bytes form this past group. We had a "==", so we take only one byte:
- *(destPtr++) = (Byte) (currBlockCodes >> 16);
-
- currBlockCodes = 0x000000FFu;
-
- } else // '=' is not ok at places other than the end:
- throw new FormatException(Environment.GetResourceString("Format_BadBase64Char"));
-
- }
-
- // We get here either from above or by jumping out of the loop:
- _AllInputConsumed:
-
- // The last block of chars has less than 4 items
- if (currBlockCodes != 0x000000FFu)
- throw new FormatException(Environment.GetResourceString("Format_BadBase64CharArrayLength"));
-
- // Return how many bytes were actually recovered:
- return (Int32) (destPtr - startDestPtr);
-
- } // Int32 FromBase64_Decode(...)
-
-
- /// <summary>
- /// Compute the number of bytes encoded in the specified Base 64 char array:
- /// Walk the entire input counting white spaces and padding chars, then compute result length
- /// based on 3 bytes per 4 chars.
- /// </summary>
- private static unsafe Int32 FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength) {
-
- const UInt32 intEq = (UInt32) '=';
- const UInt32 intSpace = (UInt32) ' ';
-
- Debug.Assert(0 <= inputLength);
-
- Char* inputEndPtr = inputPtr + inputLength;
- Int32 usefulInputLength = inputLength;
- Int32 padding = 0;
-
- while (inputPtr < inputEndPtr) {
-
- UInt32 c = (UInt32) (*inputPtr);
- inputPtr++;
-
- // We want to be as fast as possible and filter out spaces with as few comparisons as possible.
- // We end up accepting a number of illegal chars as legal white-space chars.
- // This is ok: as soon as we hit them during actual decode we will recognise them as illegal and throw.
- if (c <= intSpace)
- usefulInputLength--;
-
- else if (c == intEq) {
- usefulInputLength--;
- padding++;
- }
- }
-
- Debug.Assert(0 <= usefulInputLength);
-
- // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input.
- // We will notice it at decode when we see a '=' at the wrong place.
- Debug.Assert(0 <= padding);
-
- // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the
- // last group that contains the '=':
- if (padding != 0) {
-
- if (padding == 1)
- padding = 2;
- else if (padding == 2)
- padding = 1;
- else
- throw new FormatException(Environment.GetResourceString("Format_BadBase64Char"));
- }
-
- // Done:
- return (usefulInputLength / 4) * 3 + padding;
- }
-
- } // class Convert
-} // namespace
-
diff --git a/src/mscorlib/src/System/Currency.cs b/src/mscorlib/src/System/Currency.cs
index 05a09802cd..13ec1b0c4e 100644
--- a/src/mscorlib/src/System/Currency.cs
+++ b/src/mscorlib/src/System/Currency.cs
@@ -2,37 +2,41 @@
// 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 {
-
- using System;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
+using System;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+
+namespace System
+{
[Serializable]
internal struct Currency
{
internal long m_value;
-
+
// Constructs a Currency from a Decimal value.
//
- public Currency(Decimal value) {
+ public Currency(Decimal value)
+ {
m_value = Decimal.ToCurrency(value).m_value;
}
-
+
// Constructs a Currency from a long value without scaling. The
// ignored parameter exists only to distinguish this constructor
// from the constructor that takes a long. Used only in the System
// package, especially in Variant.
- internal Currency(long value, int ignored) {
+ internal Currency(long value, int ignored)
+ {
m_value = value;
}
-
+
// Creates a Currency from an OLE Automation Currency. This method
// applies no scaling to the Currency value, essentially doing a bitwise
// copy.
//
- public static Currency FromOACurrency(long cy){
+ public static Currency FromOACurrency(long cy)
+ {
return new Currency(cy, 0);
}
@@ -40,20 +44,21 @@ namespace System {
// method applies no scaling to the Currency value, essentially doing
// a bitwise copy.
//
- public long ToOACurrency() {
+ public long ToOACurrency()
+ {
return m_value;
}
-
+
// Converts a Currency to a Decimal.
//
public static Decimal ToDecimal(Currency c)
{
- Decimal result = new Decimal ();
- FCallToDecimal (ref result, c);
+ Decimal result = new Decimal();
+ FCallToDecimal(ref result, c);
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallToDecimal(ref Decimal result,Currency c);
+ private static extern void FCallToDecimal(ref Decimal result, Currency c);
}
}
diff --git a/src/mscorlib/src/System/CurrentSystemTimeZone.Cache.cs b/src/mscorlib/src/System/CurrentSystemTimeZone.Cache.cs
new file mode 100644
index 0000000000..744c697124
--- /dev/null
+++ b/src/mscorlib/src/System/CurrentSystemTimeZone.Cache.cs
@@ -0,0 +1,35 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Collections;
+using System.Globalization;
+
+namespace System
+{
+ internal partial class CurrentSystemTimeZone
+ {
+ private DaylightTime GetCachedDaylightChanges(int year)
+ {
+ Object objYear = (Object)year;
+
+ if (!m_CachedDaylightChanges.Contains(objYear))
+ {
+ DaylightTime currentDaylightChanges = CreateDaylightChanges(year);
+ lock (m_CachedDaylightChanges)
+ {
+ if (!m_CachedDaylightChanges.Contains(objYear))
+ {
+ m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
+ }
+ }
+ }
+
+ return (DaylightTime)m_CachedDaylightChanges[objYear];
+ }
+
+ // The per-year information is cached in in this instance value. As a result it can
+ // be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object
+ private readonly Hashtable m_CachedDaylightChanges = new Hashtable();
+ }
+}
diff --git a/src/mscorlib/src/System/CurrentTimeZone.cs b/src/mscorlib/src/System/CurrentTimeZone.cs
deleted file mode 100644
index 804bbcccc4..0000000000
--- a/src/mscorlib/src/System/CurrentTimeZone.cs
+++ /dev/null
@@ -1,214 +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.
-
-/*============================================================
-**
-** Class: CurrentTimeZone
-**
-**
-** Purpose:
-** This class represents the current system timezone. It is
-** the only meaningful implementation of the TimeZone class
-** available in this version.
-**
-** The only TimeZone that we support in version 1 is the
-** CurrentTimeZone as determined by the system timezone.
-**
-**
-============================================================*/
-namespace System {
- using System;
- using System.Diagnostics.Contracts;
- using System.Text;
- using System.Collections;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
-
- [Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
- [Serializable]
- internal class CurrentSystemTimeZone : TimeZone
- {
- // The per-year information is cached in in this instance value. As a result it can
- // be cleaned up by CultureInfo.ClearCachedData, which will clear the instance of this object
- private readonly Hashtable m_CachedDaylightChanges = new Hashtable();
-
- // Standard offset in ticks to the Universal time if
- // no daylight saving is in used.
- // E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000.
- // (1 millisecond = 10000 ticks)
- private long m_ticksOffset;
- private String m_standardName;
- private String m_daylightName;
-
- internal CurrentSystemTimeZone()
- {
- TimeZoneInfo local = TimeZoneInfo.Local;
-
- m_ticksOffset = local.BaseUtcOffset.Ticks;
- m_standardName = local.StandardName;
- m_daylightName = local.DaylightName;
- }
-
- public override String StandardName
- {
- get
- {
- return m_standardName;
- }
- }
-
- public override String DaylightName
- {
- get
- {
- return m_daylightName;
- }
- }
-
- internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst)
- {
- // Get the daylight changes for the year of the specified time.
- TimeSpan offset = new TimeSpan(m_ticksOffset);
- DaylightTime daylightTime = GetDaylightChanges(time.Year);
- isAmbiguousLocalDst= false;
-
- if (daylightTime == null || daylightTime.Delta.Ticks == 0)
- {
- return offset.Ticks;
- }
-
- // The start and end times represent the range of universal times that are in DST for that year.
- // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
- // the unusual case of a negative daylight savings delta.
- DateTime startTime = daylightTime.Start - offset;
- DateTime endTime = daylightTime.End - offset - daylightTime.Delta;
- DateTime ambiguousStart;
- DateTime ambiguousEnd;
-
- if (daylightTime.Delta.Ticks > 0)
- {
- ambiguousStart = endTime - daylightTime.Delta;
- ambiguousEnd = endTime;
- }
- else
- {
- ambiguousStart = startTime;
- ambiguousEnd = startTime - daylightTime.Delta;
- }
-
- Boolean isDst = false;
- if (startTime > endTime)
- {
- // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
- // Note, the summer in the southern hemisphere begins late in the year.
- isDst = (time < endTime || time >= startTime);
- }
- else
- {
- // In northern hemisphere, the daylight saving time starts in the middle of the year.
- isDst = (time >= startTime && time < endTime);
- }
-
- if (isDst)
- {
- offset += daylightTime.Delta;
-
- // See if the resulting local time becomes ambiguous. This must be captured here or the
- // DateTime will not be able to round-trip back to UTC accurately.
- if (time >= ambiguousStart && time < ambiguousEnd )
- {
- isAmbiguousLocalDst = true;
- }
- }
- return offset.Ticks;
- }
-
- public override DateTime ToLocalTime(DateTime time)
- {
- if (time.Kind == DateTimeKind.Local)
- {
- return time;
- }
- Boolean isAmbiguousLocalDst = false;
- Int64 offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst);
- long tick = time.Ticks + offset;
- if (tick > DateTime.MaxTicks)
- {
- return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
- }
- if (tick < DateTime.MinTicks)
- {
- return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
- }
- return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
- }
-
- public override DaylightTime GetDaylightChanges(int year)
- {
- if (year < 1 || year > 9999)
- {
- throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 9999));
- }
- Contract.EndContractBlock();
-
- Object objYear = (Object) year;
-
- if (!m_CachedDaylightChanges.Contains(objYear))
- {
- DaylightTime currentDaylightChanges = null;
-
- if (TimeZoneInfo.Local.SupportsDaylightSavingTime)
- {
- DateTime start;
- DateTime end;
- TimeSpan delta;
-
- foreach (var rule in TimeZoneInfo.Local.GetAdjustmentRules())
- {
- if (rule.DateStart.Year <= year && rule.DateEnd.Year >= year && rule.DaylightDelta != TimeSpan.Zero)
- {
- start = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
- end = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
- delta = rule.DaylightDelta;
-
- currentDaylightChanges = new DaylightTime(start, end, delta);
- break;
- }
- }
- }
-
- if (currentDaylightChanges == null)
- {
- currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
- }
-
- lock (m_CachedDaylightChanges)
- {
- if (!m_CachedDaylightChanges.Contains(objYear))
- {
- m_CachedDaylightChanges.Add(objYear, currentDaylightChanges);
- }
- }
- }
-
- DaylightTime result = (DaylightTime)m_CachedDaylightChanges[objYear];
-
- return result;
- }
-
- public override TimeSpan GetUtcOffset(DateTime time)
- {
- if (time.Kind == DateTimeKind.Utc)
- {
- return TimeSpan.Zero;
- }
- else
- {
- return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset);
- }
- }
-
- } // class CurrentSystemTimeZone
-}
diff --git a/src/mscorlib/src/System/DBNull.cs b/src/mscorlib/src/System/DBNull.cs
deleted file mode 100644
index 65c85ba968..0000000000
--- a/src/mscorlib/src/System/DBNull.cs
+++ /dev/null
@@ -1,119 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-// Void
-// This class represents a Missing Variant
-////////////////////////////////////////////////////////////////////////////////
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- [Serializable]
- public sealed class DBNull : ISerializable, IConvertible {
-
- //Package private constructor
- private DBNull(){
- }
-
- private DBNull(SerializationInfo info, StreamingContext context) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DBNullSerial"));
- }
-
- public static readonly DBNull Value = new DBNull();
-
- public void GetObjectData(SerializationInfo info, StreamingContext context) {
- UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
- }
-
- public override String ToString() {
- return String.Empty;
- }
-
- public String ToString(IFormatProvider provider) {
- return String.Empty;
- }
-
- public TypeCode GetTypeCode() {
- return TypeCode.DBNull;
- }
-
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- decimal IConvertible.ToDecimal(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromDBNull"));
- }
-
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
- return Convert.DefaultToType((IConvertible)this, type, provider);
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/DataMisalignedException.cs b/src/mscorlib/src/System/DataMisalignedException.cs
deleted file mode 100644
index a3653e7219..0000000000
--- a/src/mscorlib/src/System/DataMisalignedException.cs
+++ /dev/null
@@ -1,39 +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 for a misaligned access exception
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class DataMisalignedException : SystemException
- {
- public DataMisalignedException()
- : base(SR.Arg_DataMisalignedException)
- {
- HResult = __HResults.COR_E_DATAMISALIGNED;
- }
-
- public DataMisalignedException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_DATAMISALIGNED;
- }
-
- public DataMisalignedException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_DATAMISALIGNED;
- }
-
- internal DataMisalignedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/DateTime.CoreCLR.cs b/src/mscorlib/src/System/DateTime.CoreCLR.cs
new file mode 100644
index 0000000000..69c595663b
--- /dev/null
+++ b/src/mscorlib/src/System/DateTime.CoreCLR.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.
+
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+
+namespace System
+{
+ public partial struct DateTime
+ {
+ public static DateTime UtcNow
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
+ // following code is tuned for speed. Don't change it without running benchmark.
+ long ticks = 0;
+ ticks = GetSystemTimeAsFileTime();
+
+ return new DateTime(((UInt64)(ticks + FileTimeOffset)) | KindUtc);
+ }
+ }
+
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal static extern long GetSystemTimeAsFileTime();
+ }
+}
diff --git a/src/mscorlib/src/System/DateTime.cs b/src/mscorlib/src/System/DateTime.cs
deleted file mode 100644
index 3de50336a9..0000000000
--- a/src/mscorlib/src/System/DateTime.cs
+++ /dev/null
@@ -1,1360 +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.
-
-namespace System {
-
- using System;
- using System.Threading;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Diagnostics.Contracts;
- using CultureInfo = System.Globalization.CultureInfo;
- using Calendar = System.Globalization.Calendar;
-
- // This value type represents a date and time. Every DateTime
- // object has a private field (Ticks) of type Int64 that stores the
- // date and time as the number of 100 nanosecond intervals since
- // 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar.
- //
- // Starting from V2.0, DateTime also stored some context about its time
- // zone in the form of a 3-state value representing Unspecified, Utc or
- // Local. This is stored in the two top bits of the 64-bit numeric value
- // with the remainder of the bits storing the tick count. This information
- // is only used during time zone conversions and is not part of the
- // identity of the DateTime. Thus, operations like Compare and Equals
- // ignore this state. This is to stay compatible with earlier behavior
- // and performance characteristics and to avoid forcing people into dealing
- // with the effects of daylight savings. Note, that this has little effect
- // on how the DateTime works except in a context where its specific time
- // zone is needed, such as during conversions and some parsing and formatting
- // cases.
- //
- // There is also 4th state stored that is a special type of Local value that
- // is used to avoid data loss when round-tripping between local and UTC time.
- // See below for more information on this 4th state, although it is
- // effectively hidden from most users, who just see the 3-state DateTimeKind
- // enumeration.
- //
- // For compatibility, DateTime does not serialize the Kind data when used in
- // binary serialization.
- //
- // For a description of various calendar issues, look at
- //
- // Calendar Studies web site, at
- // http://serendipity.nofadz.com/hermetic/cal_stud.htm.
- //
- //
- [StructLayout(LayoutKind.Auto)]
- [Serializable]
- public struct DateTime : IComparable, IFormattable, IConvertible, IComparable<DateTime>, IEquatable<DateTime>, ISerializable
- {
-
- // Number of 100ns ticks per time unit
- private const long TicksPerMillisecond = 10000;
- private const long TicksPerSecond = TicksPerMillisecond * 1000;
- private const long TicksPerMinute = TicksPerSecond * 60;
- private const long TicksPerHour = TicksPerMinute * 60;
- private const long TicksPerDay = TicksPerHour * 24;
-
- // Number of milliseconds per time unit
- private const int MillisPerSecond = 1000;
- private const int MillisPerMinute = MillisPerSecond * 60;
- private const int MillisPerHour = MillisPerMinute * 60;
- private const int MillisPerDay = MillisPerHour * 24;
-
- // Number of days in a non-leap year
- private const int DaysPerYear = 365;
- // Number of days in 4 years
- private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461
- // Number of days in 100 years
- private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524
- // Number of days in 400 years
- private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097
-
- // Number of days from 1/1/0001 to 12/31/1600
- private const int DaysTo1601 = DaysPer400Years * 4; // 584388
- // Number of days from 1/1/0001 to 12/30/1899
- private const int DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;
- // Number of days from 1/1/0001 to 12/31/1969
- internal const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162
- // Number of days from 1/1/0001 to 12/31/9999
- private const int DaysTo10000 = DaysPer400Years * 25 - 366; // 3652059
-
- internal const long MinTicks = 0;
- internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1;
- private const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
-
- private const long FileTimeOffset = DaysTo1601 * TicksPerDay;
- private const long DoubleDateOffset = DaysTo1899 * TicksPerDay;
- // The minimum OA date is 0100/01/01 (Note it's year 100).
- // The maximum OA date is 9999/12/31
- private const long OADateMinAsTicks = (DaysPer100Years - DaysPerYear) * TicksPerDay;
- // All OA dates must be greater than (not >=) OADateMinAsDouble
- private const double OADateMinAsDouble = -657435.0;
- // All OA dates must be less than (not <=) OADateMaxAsDouble
- private const double OADateMaxAsDouble = 2958466.0;
-
- private const int DatePartYear = 0;
- private const int DatePartDayOfYear = 1;
- private const int DatePartMonth = 2;
- private const int DatePartDay = 3;
-
- private static readonly int[] DaysToMonth365 = {
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
- private static readonly int[] DaysToMonth366 = {
- 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
-
- public static readonly DateTime MinValue = new DateTime(MinTicks, DateTimeKind.Unspecified);
- public static readonly DateTime MaxValue = new DateTime(MaxTicks, DateTimeKind.Unspecified);
-
- private const UInt64 TicksMask = 0x3FFFFFFFFFFFFFFF;
- private const UInt64 FlagsMask = 0xC000000000000000;
- private const UInt64 LocalMask = 0x8000000000000000;
- private const Int64 TicksCeiling = 0x4000000000000000;
- private const UInt64 KindUnspecified = 0x0000000000000000;
- private const UInt64 KindUtc = 0x4000000000000000;
- private const UInt64 KindLocal = 0x8000000000000000;
- private const UInt64 KindLocalAmbiguousDst = 0xC000000000000000;
- private const Int32 KindShift = 62;
-
- private const String TicksField = "ticks";
- private const String DateDataField = "dateData";
-
- // The data is stored as an unsigned 64-bit integeter
- // Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value
- // 12/31/9999 23:59:59.9999999
- // Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd
- // value for the rare case where the date time is local, but is in an overlapped daylight
- // savings time hour and it is in daylight savings time. This allows distinction of these
- // otherwise ambiguous local times and prevents data loss when round tripping from Local to
- // UTC time.
- private UInt64 dateData;
-
- // Constructs a DateTime from a tick count. The ticks
- // argument specifies the date as the number of 100-nanosecond intervals
- // that have elapsed since 1/1/0001 12:00am.
- //
- public DateTime(long ticks) {
- if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
- Contract.EndContractBlock();
- dateData = (UInt64)ticks;
- }
-
- private DateTime(UInt64 dateData) {
- this.dateData = dateData;
- }
-
- public DateTime(long ticks, DateTimeKind kind) {
- if (ticks < MinTicks || ticks > MaxTicks) {
- throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
- }
- if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
- }
- Contract.EndContractBlock();
- this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
- }
-
- internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst) {
- if (ticks < MinTicks || ticks > MaxTicks) {
- throw new ArgumentOutOfRangeException(nameof(ticks), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"));
- }
- Contract.Requires(kind == DateTimeKind.Local, "Internal Constructor is for local times only");
- Contract.EndContractBlock();
- dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal));
- }
-
- // Constructs a DateTime from a given year, month, and day. The
- // time-of-day of the resulting DateTime is always midnight.
- //
- public DateTime(int year, int month, int day) {
- this.dateData = (UInt64) DateToTicks(year, month, day);
- }
-
- // Constructs a DateTime from a given year, month, and day for
- // the specified calendar. The
- // time-of-day of the resulting DateTime is always midnight.
- //
- public DateTime(int year, int month, int day, Calendar calendar)
- : this(year, month, day, 0, 0, 0, calendar) {
- }
-
- // Constructs a DateTime from a given year, month, day, hour,
- // minute, and second.
- //
- public DateTime(int year, int month, int day, int hour, int minute, int second) {
- this.dateData = (UInt64)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second));
- }
-
- public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) {
- if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
- }
- Contract.EndContractBlock();
- Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
- this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
- }
-
- // Constructs a DateTime from a given year, month, day, hour,
- // minute, and second for the specified calendar.
- //
- public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar) {
- if (calendar == null)
- throw new ArgumentNullException(nameof(calendar));
- Contract.EndContractBlock();
- this.dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
- }
-
- // Constructs a DateTime from a given year, month, day, hour,
- // minute, and second.
- //
- public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) {
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
- }
- Contract.EndContractBlock();
- Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
- ticks += millisecond * TicksPerMillisecond;
- if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = (UInt64)ticks;
- }
-
- public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) {
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
- }
- if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
- }
- Contract.EndContractBlock();
- Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
- ticks += millisecond * TicksPerMillisecond;
- if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
- }
-
- // Constructs a DateTime from a given year, month, day, hour,
- // minute, and second for the specified calendar.
- //
- public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar) {
- if (calendar == null)
- throw new ArgumentNullException(nameof(calendar));
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
- }
- Contract.EndContractBlock();
- Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
- ticks += millisecond * TicksPerMillisecond;
- if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = (UInt64)ticks;
- }
-
- public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) {
- if (calendar == null)
- throw new ArgumentNullException(nameof(calendar));
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException(nameof(millisecond), Environment.GetResourceString("ArgumentOutOfRange_Range", 0, MillisPerSecond - 1));
- }
- if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeKind"), nameof(kind));
- }
- Contract.EndContractBlock();
- Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
- ticks += millisecond * TicksPerMillisecond;
- if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentException(Environment.GetResourceString("Arg_DateTimeRange"));
- this.dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
- }
-
- private DateTime(SerializationInfo info, StreamingContext context) {
- if (info==null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- Boolean foundTicks = false;
- Boolean foundDateData = false;
- Int64 serializedTicks = 0;
- UInt64 serializedDateData = 0;
-
-
- // Get the data
- SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while( enumerator.MoveNext()) {
- switch( enumerator.Name) {
- case TicksField:
- serializedTicks = Convert.ToInt64(enumerator.Value, CultureInfo.InvariantCulture);
- foundTicks = true;
- break;
- case DateDataField:
- serializedDateData = Convert.ToUInt64(enumerator.Value, CultureInfo.InvariantCulture);
- foundDateData = true;
- break;
- default:
- // Ignore other fields for forward compatibility.
- break;
- }
- }
- if (foundDateData) {
- this.dateData = serializedDateData;
- }
- else if (foundTicks) {
- this.dateData = (UInt64)serializedTicks;
- }
- else {
- throw new SerializationException(Environment.GetResourceString("Serialization_MissingDateTimeData"));
- }
- Int64 ticks = InternalTicks;
- if (ticks < MinTicks || ticks > MaxTicks) {
- throw new SerializationException(Environment.GetResourceString("Serialization_DateTimeTicksOutOfRange"));
- }
- }
-
-
-
- internal Int64 InternalTicks {
- get {
- return (Int64)(dateData & TicksMask);
- }
- }
-
- private UInt64 InternalKind {
- get {
- return (dateData & FlagsMask);
- }
- }
-
- // Returns the DateTime resulting from adding the given
- // TimeSpan to this DateTime.
- //
- public DateTime Add(TimeSpan value) {
- return AddTicks(value._ticks);
- }
-
- // Returns the DateTime resulting from adding a fractional number of
- // time units to this DateTime.
- private DateTime Add(double value, int scale) {
- long millis = (long)(value * scale + (value >= 0? 0.5: -0.5));
- if (millis <= -MaxMillis || millis >= MaxMillis)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
- return AddTicks(millis * TicksPerMillisecond);
- }
-
- // Returns the DateTime resulting from adding a fractional number of
- // days to this DateTime. The result is computed by rounding the
- // fractional number of days given by value to the nearest
- // millisecond, and adding that interval to this DateTime. The
- // value argument is permitted to be negative.
- //
- public DateTime AddDays(double value) {
- return Add(value, MillisPerDay);
- }
-
- // Returns the DateTime resulting from adding a fractional number of
- // hours to this DateTime. The result is computed by rounding the
- // fractional number of hours given by value to the nearest
- // millisecond, and adding that interval to this DateTime. The
- // value argument is permitted to be negative.
- //
- public DateTime AddHours(double value) {
- return Add(value, MillisPerHour);
- }
-
- // Returns the DateTime resulting from the given number of
- // milliseconds to this DateTime. The result is computed by rounding
- // the number of milliseconds given by value to the nearest integer,
- // and adding that interval to this DateTime. The value
- // argument is permitted to be negative.
- //
- public DateTime AddMilliseconds(double value) {
- return Add(value, 1);
- }
-
- // Returns the DateTime resulting from adding a fractional number of
- // minutes to this DateTime. The result is computed by rounding the
- // fractional number of minutes given by value to the nearest
- // millisecond, and adding that interval to this DateTime. The
- // value argument is permitted to be negative.
- //
- public DateTime AddMinutes(double value) {
- return Add(value, MillisPerMinute);
- }
-
- // Returns the DateTime resulting from adding the given number of
- // months to this DateTime. The result is computed by incrementing
- // (or decrementing) the year and month parts of this DateTime by
- // months months, and, if required, adjusting the day part of the
- // resulting date downwards to the last day of the resulting month in the
- // resulting year. The time-of-day part of the result is the same as the
- // time-of-day part of this DateTime.
- //
- // In more precise terms, considering this DateTime to be of the
- // form y / m / d + t, where y is the
- // year, m is the month, d is the day, and t is the
- // time-of-day, the result is y1 / m1 / d1 + t,
- // where y1 and m1 are computed by adding months months
- // to y and m, and d1 is the largest value less than
- // or equal to d that denotes a valid day in month m1 of year
- // y1.
- //
- public DateTime AddMonths(int months) {
- if (months < -120000 || months > 120000) throw new ArgumentOutOfRangeException(nameof(months), Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadMonths"));
- Contract.EndContractBlock();
- int y = GetDatePart(DatePartYear);
- int m = GetDatePart(DatePartMonth);
- int d = GetDatePart(DatePartDay);
- int i = m - 1 + months;
- if (i >= 0) {
- m = i % 12 + 1;
- y = y + i / 12;
- }
- else {
- m = 12 + (i + 1) % 12;
- y = y + (i - 11) / 12;
- }
- if (y < 1 || y > 9999) {
- throw new ArgumentOutOfRangeException(nameof(months), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
- }
- int days = DaysInMonth(y, m);
- if (d > days) d = days;
- return new DateTime((UInt64)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind);
- }
-
- // Returns the DateTime resulting from adding a fractional number of
- // seconds to this DateTime. The result is computed by rounding the
- // fractional number of seconds given by value to the nearest
- // millisecond, and adding that interval to this DateTime. The
- // value argument is permitted to be negative.
- //
- public DateTime AddSeconds(double value) {
- return Add(value, MillisPerSecond);
- }
-
- // Returns the DateTime resulting from adding the given number of
- // 100-nanosecond ticks to this DateTime. The value argument
- // is permitted to be negative.
- //
- public DateTime AddTicks(long value) {
- long ticks = InternalTicks;
- if (value > MaxTicks - ticks || value < MinTicks - ticks) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
- }
- return new DateTime((UInt64)(ticks + value) | InternalKind);
- }
-
- // Returns the DateTime resulting from adding the given number of
- // years to this DateTime. The result is computed by incrementing
- // (or decrementing) the year part of this DateTime by value
- // years. If the month and day of this DateTime is 2/29, and if the
- // resulting year is not a leap year, the month and day of the resulting
- // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
- // parts of the result are the same as those of this DateTime.
- //
- public DateTime AddYears(int value) {
- if (value < -10000 || value > 10000)
- {
- // DateTimeOffset.AddYears(int years) is implemented on top of DateTime.AddYears(int value). Use the more appropriate
- // parameter name out of the two for the exception.
- throw new ArgumentOutOfRangeException("years", Environment.GetResourceString("ArgumentOutOfRange_DateTimeBadYears"));
- }
- Contract.EndContractBlock();
- return AddMonths(value * 12);
- }
-
- // Compares two DateTime values, returning an integer that indicates
- // their relationship.
- //
- public static int Compare(DateTime t1, DateTime t2) {
- Int64 ticks1 = t1.InternalTicks;
- Int64 ticks2 = t2.InternalTicks;
- if (ticks1 > ticks2) return 1;
- if (ticks1 < ticks2) return -1;
- return 0;
- }
-
- // Compares this DateTime to a given object. This method provides an
- // implementation of the IComparable interface. The object
- // argument must be another DateTime, or otherwise an exception
- // occurs. Null is considered less than any instance.
- //
- // Returns a value less than zero if this object
- public int CompareTo(Object value) {
- if (value == null) return 1;
- if (!(value is DateTime)) {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTime"));
- }
-
- return Compare(this, (DateTime)value);
- }
-
- public int CompareTo(DateTime value) {
- return Compare(this, value);
- }
-
- // Returns the tick count corresponding to the given year, month, and day.
- // Will check the if the parameters are valid.
- private static long DateToTicks(int year, int month, int day) {
- if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) {
- int[] days = IsLeapYear(year)? DaysToMonth366: DaysToMonth365;
- if (day >= 1 && day <= days[month] - days[month - 1]) {
- int y = year - 1;
- int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
- return n * TicksPerDay;
- }
- }
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
-
- // Return the tick count corresponding to the given hour, minute, second.
- // Will check the if the parameters are valid.
- private static long TimeToTicks(int hour, int minute, int second)
- {
- //TimeSpan.TimeToTicks is a family access function which does no error checking, so
- //we need to put some error checking out here.
- if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
- {
- return (TimeSpan.TimeToTicks(hour, minute, second));
- }
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
- }
-
- // Returns the number of days in the month given by the year and
- // month arguments.
- //
- public static int DaysInMonth(int year, int month) {
- if (month < 1 || month > 12) throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- Contract.EndContractBlock();
- // IsLeapYear checks the year argument
- int[] days = IsLeapYear(year)? DaysToMonth366: DaysToMonth365;
- return days[month] - days[month - 1];
- }
-
- // Converts an OLE Date to a tick count.
- // This function is duplicated in COMDateTime.cpp
- internal static long DoubleDateToTicks(double value) {
- // The check done this way will take care of NaN
- if (!(value < OADateMaxAsDouble) || !(value > OADateMinAsDouble))
- throw new ArgumentException(Environment.GetResourceString("Arg_OleAutDateInvalid"));
-
- // Conversion to long will not cause an overflow here, as at this point the "value" is in between OADateMinAsDouble and OADateMaxAsDouble
- long millis = (long)(value * MillisPerDay + (value >= 0? 0.5: -0.5));
- // The interesting thing here is when you have a value like 12.5 it all positive 12 days and 12 hours from 01/01/1899
- // However if you a value of -12.25 it is minus 12 days but still positive 6 hours, almost as though you meant -11.75 all negative
- // This line below fixes up the millis in the negative case
- if (millis < 0) {
- millis -= (millis % MillisPerDay) * 2;
- }
-
- millis += DoubleDateOffset / TicksPerMillisecond;
-
- if (millis < 0 || millis >= MaxMillis) throw new ArgumentException(Environment.GetResourceString("Arg_OleAutDateScale"));
- return millis * TicksPerMillisecond;
- }
-
- // Checks if this DateTime is equal to a given object. Returns
- // true if the given object is a boxed DateTime and its value
- // is equal to the value of this DateTime. Returns false
- // otherwise.
- //
- public override bool Equals(Object value) {
- if (value is DateTime) {
- return InternalTicks == ((DateTime)value).InternalTicks;
- }
- return false;
- }
-
- public bool Equals(DateTime value) {
- return InternalTicks == value.InternalTicks;
- }
-
- // Compares two DateTime values for equality. Returns true if
- // the two DateTime values are equal, or false if they are
- // not equal.
- //
- public static bool Equals(DateTime t1, DateTime t2) {
- return t1.InternalTicks == t2.InternalTicks;
- }
-
- public static DateTime FromBinary(Int64 dateData) {
- if ((dateData & (unchecked( (Int64) LocalMask))) != 0) {
- // Local times need to be adjusted as you move from one time zone to another,
- // just as they are when serializing in text. As such the format for local times
- // changes to store the ticks of the UTC time, but with flags that look like a
- // local date.
- Int64 ticks = dateData & (unchecked((Int64)TicksMask));
- // Negative ticks are stored in the top part of the range and should be converted back into a negative number
- if (ticks > TicksCeiling - TicksPerDay) {
- ticks = ticks - TicksCeiling;
- }
- // Convert the ticks back to local. If the UTC ticks are out of range, we need to default to
- // the UTC offset from MinValue and MaxValue to be consistent with Parse.
- Boolean isAmbiguousLocalDst = false;
- Int64 offsetTicks;
- if (ticks < MinTicks) {
- offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
- }
- else if (ticks > MaxTicks) {
- offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MaxValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
- }
- else {
- // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
- // time is in a repeated hour so that it can be passed to the DateTime constructor.
- DateTime utcDt = new DateTime(ticks, DateTimeKind.Utc);
- Boolean isDaylightSavings = false;
- offsetTicks = TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
- }
- ticks += offsetTicks;
- // Another behaviour of parsing is to cause small times to wrap around, so that they can be used
- // to compare times of day
- if (ticks < 0) {
- ticks += TicksPerDay;
- }
- if (ticks < MinTicks || ticks > MaxTicks) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), nameof(dateData));
- }
- return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
- }
- else {
- return DateTime.FromBinaryRaw(dateData);
- }
- }
-
- // A version of ToBinary that uses the real representation and does not adjust local times. This is needed for
- // scenarios where the serialized data must maintain compatibility
- internal static DateTime FromBinaryRaw(Int64 dateData) {
- Int64 ticks = dateData & (Int64)TicksMask;
- if (ticks < MinTicks || ticks > MaxTicks)
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), nameof(dateData));
- return new DateTime((UInt64)dateData);
- }
-
- // Creates a DateTime from a Windows filetime. A Windows filetime is
- // a long representing the date and time as the number of
- // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
- //
- public static DateTime FromFileTime(long fileTime) {
- return FromFileTimeUtc(fileTime).ToLocalTime();
- }
-
- public static DateTime FromFileTimeUtc(long fileTime) {
- if (fileTime < 0 || fileTime > MaxTicks - FileTimeOffset) {
- throw new ArgumentOutOfRangeException(nameof(fileTime), Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
- }
- Contract.EndContractBlock();
-
- // This is the ticks in Universal time for this fileTime.
- long universalTicks = fileTime + FileTimeOffset;
- return new DateTime(universalTicks, DateTimeKind.Utc);
- }
-
- // Creates a DateTime from an OLE Automation Date.
- //
- public static DateTime FromOADate(double d) {
- return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified);
- }
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
-
- // Serialize both the old and the new format
- info.AddValue(TicksField, InternalTicks);
- info.AddValue(DateDataField, dateData);
- }
-
- public Boolean IsDaylightSavingTime() {
- if (Kind == DateTimeKind.Utc) {
- return false;
- }
- return TimeZoneInfo.Local.IsDaylightSavingTime(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
-
- public static DateTime SpecifyKind(DateTime value, DateTimeKind kind) {
- return new DateTime(value.InternalTicks, kind);
- }
-
- public Int64 ToBinary() {
- if (Kind == DateTimeKind.Local) {
- // Local times need to be adjusted as you move from one time zone to another,
- // just as they are when serializing in text. As such the format for local times
- // changes to store the ticks of the UTC time, but with flags that look like a
- // local date.
-
- // To match serialization in text we need to be able to handle cases where
- // the UTC value would be out of range. Unused parts of the ticks range are
- // used for this, so that values just past max value are stored just past the
- // end of the maximum range, and values just below minimum value are stored
- // at the end of the ticks area, just below 2^62.
- TimeSpan offset = TimeZoneInfo.GetLocalUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- Int64 ticks = Ticks;
- Int64 storedTicks = ticks - offset.Ticks;
- if (storedTicks < 0) {
- storedTicks = TicksCeiling + storedTicks;
- }
- return storedTicks | (unchecked((Int64) LocalMask));
- }
- else {
- return (Int64)dateData;
- }
- }
-
- // Returns the date part of this DateTime. The resulting value
- // corresponds to this DateTime with the time-of-day part set to
- // zero (midnight).
- //
- public DateTime Date {
- get {
- Int64 ticks = InternalTicks;
- return new DateTime((UInt64)(ticks - ticks % TicksPerDay) | InternalKind);
- }
- }
-
- // Returns a given date part of this DateTime. This method is used
- // to compute the year, day-of-year, month, or day part.
- private int GetDatePart(int part) {
- Int64 ticks = InternalTicks;
- // n = number of days since 1/1/0001
- int n = (int)(ticks / TicksPerDay);
- // y400 = number of whole 400-year periods since 1/1/0001
- int y400 = n / DaysPer400Years;
- // n = day number within 400-year period
- n -= y400 * DaysPer400Years;
- // y100 = number of whole 100-year periods within 400-year period
- int y100 = n / DaysPer100Years;
- // Last 100-year period has an extra day, so decrement result if 4
- if (y100 == 4) y100 = 3;
- // n = day number within 100-year period
- n -= y100 * DaysPer100Years;
- // y4 = number of whole 4-year periods within 100-year period
- int y4 = n / DaysPer4Years;
- // n = day number within 4-year period
- n -= y4 * DaysPer4Years;
- // y1 = number of whole years within 4-year period
- int y1 = n / DaysPerYear;
- // Last year has an extra day, so decrement result if 4
- if (y1 == 4) y1 = 3;
- // If year was requested, compute and return it
- if (part == DatePartYear) {
- return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
- }
- // n = day number within year
- n -= y1 * DaysPerYear;
- // If day-of-year was requested, return it
- if (part == DatePartDayOfYear) return n + 1;
- // Leap year calculation looks different from IsLeapYear since y1, y4,
- // and y100 are relative to year 1, not year 0
- bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
- int[] days = leapYear? DaysToMonth366: DaysToMonth365;
- // All months have less than 32 days, so n >> 5 is a good conservative
- // estimate for the month
- int m = (n >> 5) + 1;
- // m = 1-based month number
- while (n >= days[m]) m++;
- // If month was requested, return it
- if (part == DatePartMonth) return m;
- // Return 1-based day-of-month
- return n - days[m - 1] + 1;
- }
-
- // Returns the day-of-month part of this DateTime. The returned
- // value is an integer between 1 and 31.
- //
- public int Day {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1);
- Contract.Ensures(Contract.Result<int>() <= 31);
- return GetDatePart(DatePartDay);
- }
- }
-
- // Returns the day-of-week part of this DateTime. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
- public DayOfWeek DayOfWeek {
- get {
- Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
- Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
- return (DayOfWeek)((InternalTicks / TicksPerDay + 1) % 7);
- }
- }
-
- // Returns the day-of-year part of this DateTime. The returned value
- // is an integer between 1 and 366.
- //
- public int DayOfYear {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1);
- Contract.Ensures(Contract.Result<int>() <= 366); // leap year
- return GetDatePart(DatePartDayOfYear);
- }
- }
-
- // Returns the hash code for this DateTime.
- //
- public override int GetHashCode() {
- Int64 ticks = InternalTicks;
- return unchecked((int)ticks) ^ (int)(ticks >> 32);
- }
-
- // Returns the hour part of this DateTime. The returned value is an
- // integer between 0 and 23.
- //
- public int Hour {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 24);
- return (int)((InternalTicks / TicksPerHour) % 24);
- }
- }
-
- internal Boolean IsAmbiguousDaylightSavingTime() {
- return (InternalKind == KindLocalAmbiguousDst);
- }
-
- [Pure]
- public DateTimeKind Kind {
- get {
- switch (InternalKind) {
- case KindUnspecified:
- return DateTimeKind.Unspecified;
- case KindUtc:
- return DateTimeKind.Utc;
- default:
- return DateTimeKind.Local;
- }
- }
- }
-
- // Returns the millisecond part of this DateTime. The returned value
- // is an integer between 0 and 999.
- //
- public int Millisecond {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 1000);
- return (int)((InternalTicks/ TicksPerMillisecond) % 1000);
- }
- }
-
- // Returns the minute part of this DateTime. The returned value is
- // an integer between 0 and 59.
- //
- public int Minute {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 60);
- return (int)((InternalTicks / TicksPerMinute) % 60);
- }
- }
-
- // Returns the month part of this DateTime. The returned value is an
- // integer between 1 and 12.
- //
- public int Month {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1);
- return GetDatePart(DatePartMonth);
- }
- }
-
- // Returns a DateTime representing the current date and time. The
- // resolution of the returned value depends on the system timer. For
- // Windows NT 3.5 and later the timer resolution is approximately 10ms,
- // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
- // it is approximately 55ms.
- //
- public static DateTime Now {
- get {
- Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
-
- DateTime utc = UtcNow;
- Boolean isAmbiguousLocalDst = false;
- Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks;
- long tick = utc.Ticks + offset;
- if (tick>DateTime.MaxTicks) {
- return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
- }
- if (tick<DateTime.MinTicks) {
- return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
- }
- return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
- }
- }
-
- public static DateTime UtcNow {
- get {
- Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
- // following code is tuned for speed. Don't change it without running benchmark.
- long ticks = 0;
- ticks = GetSystemTimeAsFileTime();
-
- return new DateTime( ((UInt64)(ticks + FileTimeOffset)) | KindUtc);
- }
- }
-
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern long GetSystemTimeAsFileTime();
-
-
-
- // Returns the second part of this DateTime. The returned value is
- // an integer between 0 and 59.
- //
- public int Second {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 60);
- return (int)((InternalTicks / TicksPerSecond) % 60);
- }
- }
-
- // Returns the tick count for this DateTime. The returned value is
- // the number of 100-nanosecond intervals that have elapsed since 1/1/0001
- // 12:00am.
- //
- public long Ticks {
- get {
- return InternalTicks;
- }
- }
-
- // Returns the time-of-day part of this DateTime. The returned value
- // is a TimeSpan that indicates the time elapsed since midnight.
- //
- public TimeSpan TimeOfDay {
- get {
- return new TimeSpan(InternalTicks % TicksPerDay);
- }
- }
-
- // Returns a DateTime representing the current date. The date part
- // of the returned value is the current date, and the time-of-day part of
- // the returned value is zero (midnight).
- //
- public static DateTime Today {
- get {
- return DateTime.Now.Date;
- }
- }
-
- // Returns the year part of this DateTime. The returned value is an
- // integer between 1 and 9999.
- //
- public int Year {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
- return GetDatePart(DatePartYear);
- }
- }
-
- // Checks whether a given year is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
- public static bool IsLeapYear(int year) {
- if (year < 1 || year > 9999) {
- throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Year"));
- }
- Contract.EndContractBlock();
- return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
- }
-
- // Constructs a DateTime from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTime Parse(String s) {
- return (DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None));
- }
-
- // Constructs a DateTime from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTime Parse(String s, IFormatProvider provider) {
- return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None));
- }
-
- public static DateTime Parse(String s, IFormatProvider provider, DateTimeStyles styles) {
- DateTimeFormatInfo.ValidateStyles(styles, nameof(styles));
- return (DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles));
- }
-
- // Constructs a DateTime from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTime ParseExact(String s, String format, IFormatProvider provider) {
- return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None));
- }
-
- // Constructs a DateTime from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTime ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style) {
- DateTimeFormatInfo.ValidateStyles(style, nameof(style));
- return (DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style));
- }
-
- public static DateTime ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style) {
- DateTimeFormatInfo.ValidateStyles(style, nameof(style));
- return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style);
- }
-
- public TimeSpan Subtract(DateTime value) {
- return new TimeSpan(InternalTicks - value.InternalTicks);
- }
-
- public DateTime Subtract(TimeSpan value) {
- long ticks = InternalTicks;
- long valueTicks = value._ticks;
- if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
- }
- return new DateTime((UInt64)(ticks - valueTicks) | InternalKind);
- }
-
- // This function is duplicated in COMDateTime.cpp
- private static double TicksToOADate(long value) {
- if (value == 0)
- return 0.0; // Returns OleAut's zero'ed date value.
- if (value < TicksPerDay) // This is a fix for VB. They want the default day to be 1/1/0001 rathar then 12/30/1899.
- value += DoubleDateOffset; // We could have moved this fix down but we would like to keep the bounds check.
- if (value < OADateMinAsTicks)
- throw new OverflowException(Environment.GetResourceString("Arg_OleAutDateInvalid"));
- // Currently, our max date == OA's max date (12/31/9999), so we don't
- // need an overflow check in that direction.
- long millis = (value - DoubleDateOffset) / TicksPerMillisecond;
- if (millis < 0) {
- long frac = millis % MillisPerDay;
- if (frac != 0) millis -= (MillisPerDay + frac) * 2;
- }
- return (double)millis / MillisPerDay;
- }
-
- // Converts the DateTime instance into an OLE Automation compatible
- // double date.
- public double ToOADate() {
- return TicksToOADate(InternalTicks);
- }
-
- public long ToFileTime() {
- // Treats the input as local if it is not specified
- return ToUniversalTime().ToFileTimeUtc();
- }
-
- public long ToFileTimeUtc() {
- // Treats the input as universal if it is not specified
- long ticks = ((InternalKind & LocalMask) != 0) ? ToUniversalTime().InternalTicks : this.InternalTicks;
- ticks -= FileTimeOffset;
- if (ticks < 0) {
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
- }
- return ticks;
- }
-
- public DateTime ToLocalTime()
- {
- return ToLocalTime(false);
- }
-
- internal DateTime ToLocalTime(bool throwOnOverflow)
- {
- if (Kind == DateTimeKind.Local) {
- return this;
- }
- Boolean isDaylightSavings = false;
- Boolean isAmbiguousLocalDst = false;
- Int64 offset = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
- long tick = Ticks + offset;
- if (tick > DateTime.MaxTicks)
- {
- if (throwOnOverflow)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
- else
- return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
- }
- if (tick < DateTime.MinTicks)
- {
- if (throwOnOverflow)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
- else
- return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
- }
- return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
- }
-
- public String ToLongDateString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, "D", DateTimeFormatInfo.CurrentInfo);
- }
-
- public String ToLongTimeString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, "T", DateTimeFormatInfo.CurrentInfo);
- }
-
- public String ToShortDateString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, "d", DateTimeFormatInfo.CurrentInfo);
- }
-
- public String ToShortTimeString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, "t", DateTimeFormatInfo.CurrentInfo);
- }
-
- public override String ToString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, null, DateTimeFormatInfo.CurrentInfo);
- }
-
- public String ToString(String format) {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, format, DateTimeFormatInfo.CurrentInfo);
- }
-
- public String ToString(IFormatProvider provider) {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, null, DateTimeFormatInfo.GetInstance(provider));
- }
-
- public String ToString(String format, IFormatProvider provider) {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(this, format, DateTimeFormatInfo.GetInstance(provider));
- }
-
- public DateTime ToUniversalTime() {
- return TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
-
- public static Boolean TryParse(String s, out DateTime result) {
- return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result);
- }
-
- public static Boolean TryParse(String s, IFormatProvider provider, DateTimeStyles styles, out DateTime result) {
- DateTimeFormatInfo.ValidateStyles(styles, nameof(styles));
- return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result);
- }
-
- public static Boolean TryParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- DateTimeFormatInfo.ValidateStyles(style, nameof(style));
- return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result);
- }
-
- public static Boolean TryParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style, out DateTime result) {
- DateTimeFormatInfo.ValidateStyles(style, nameof(style));
- return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result);
- }
-
- public static DateTime operator +(DateTime d, TimeSpan t) {
- long ticks = d.InternalTicks;
- long valueTicks = t._ticks;
- if (valueTicks > MaxTicks - ticks || valueTicks < MinTicks - ticks) {
- throw new ArgumentOutOfRangeException(nameof(t), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
- }
- return new DateTime((UInt64)(ticks + valueTicks) | d.InternalKind);
- }
-
- public static DateTime operator -(DateTime d, TimeSpan t) {
- long ticks = d.InternalTicks;
- long valueTicks = t._ticks;
- if (ticks - MinTicks < valueTicks || ticks - MaxTicks > valueTicks) {
- throw new ArgumentOutOfRangeException(nameof(t), Environment.GetResourceString("ArgumentOutOfRange_DateArithmetic"));
- }
- return new DateTime((UInt64)(ticks - valueTicks) | d.InternalKind);
- }
-
- public static TimeSpan operator -(DateTime d1, DateTime d2) {
- return new TimeSpan(d1.InternalTicks - d2.InternalTicks);
- }
-
- public static bool operator ==(DateTime d1, DateTime d2) {
- return d1.InternalTicks == d2.InternalTicks;
- }
-
- public static bool operator !=(DateTime d1, DateTime d2) {
- return d1.InternalTicks != d2.InternalTicks;
- }
-
- public static bool operator <(DateTime t1, DateTime t2) {
- return t1.InternalTicks < t2.InternalTicks;
- }
-
- public static bool operator <=(DateTime t1, DateTime t2) {
- return t1.InternalTicks <= t2.InternalTicks;
- }
-
- public static bool operator >(DateTime t1, DateTime t2) {
- return t1.InternalTicks > t2.InternalTicks;
- }
-
- public static bool operator >=(DateTime t1, DateTime t2) {
- return t1.InternalTicks >= t2.InternalTicks;
- }
-
-
- // Returns a string array containing all of the known date and time options for the
- // current culture. The strings returned are properly formatted date and
- // time strings for the current instance of DateTime.
- public String[] GetDateTimeFormats()
- {
- Contract.Ensures(Contract.Result<String[]>() != null);
- return (GetDateTimeFormats(CultureInfo.CurrentCulture));
- }
-
- // Returns a string array containing all of the known date and time options for the
- // using the information provided by IFormatProvider. The strings returned are properly formatted date and
- // time strings for the current instance of DateTime.
- public String[] GetDateTimeFormats(IFormatProvider provider)
- {
- Contract.Ensures(Contract.Result<String[]>() != null);
- return (DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider)));
- }
-
-
- // Returns a string array containing all of the date and time options for the
- // given format format and current culture. The strings returned are properly formatted date and
- // time strings for the current instance of DateTime.
- public String[] GetDateTimeFormats(char format)
- {
- Contract.Ensures(Contract.Result<String[]>() != null);
- return (GetDateTimeFormats(format, CultureInfo.CurrentCulture));
- }
-
- // Returns a string array containing all of the date and time options for the
- // given format format and given culture. The strings returned are properly formatted date and
- // time strings for the current instance of DateTime.
- public String[] GetDateTimeFormats(char format, IFormatProvider provider)
- {
- Contract.Ensures(Contract.Result<String[]>() != null);
- return (DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider)));
- }
-
- //
- // IConvertible implementation
- //
-
- public TypeCode GetTypeCode() {
- return TypeCode.DateTime;
- }
-
-
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Boolean"));
- }
-
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Char"));
- }
-
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "SByte"));
- }
-
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Byte"));
- }
-
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Int16"));
- }
-
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "UInt16"));
- }
-
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Int32"));
- }
-
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "UInt32"));
- }
-
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Int64"));
- }
-
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "UInt64"));
- }
-
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Single"));
- }
-
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Double"));
- }
-
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "DateTime", "Decimal"));
- }
-
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- return this;
- }
-
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
- return Convert.DefaultToType((IConvertible)this, type, provider);
- }
-
- // Tries to construct a DateTime from a given year, month, day, hour,
- // minute, second and millisecond.
- //
- internal static Boolean TryCreate(int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result) {
- result = DateTime.MinValue;
- if (year < 1 || year > 9999 || month < 1 || month > 12) {
- return false;
- }
- int[] days = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
- if (day < 1 || day > days[month] - days[month - 1]) {
- return false;
- }
- if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60) {
- return false;
- }
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
- return false;
- }
- long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
-
- ticks += millisecond * TicksPerMillisecond;
- if (ticks < MinTicks || ticks > MaxTicks) {
- return false;
- }
- result = new DateTime(ticks, DateTimeKind.Unspecified);
- return true;
- }
- }
-}
diff --git a/src/mscorlib/src/System/DateTimeKind.cs b/src/mscorlib/src/System/DateTimeKind.cs
deleted file mode 100644
index 6b5e690df0..0000000000
--- a/src/mscorlib/src/System/DateTimeKind.cs
+++ /dev/null
@@ -1,17 +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.
-
-namespace System
-{
- // This enum is used to indentify DateTime instances in cases when they are known to be in local time,
- // UTC time or if this information has not been specified or is not applicable.
-
- [Serializable]
- public enum DateTimeKind
- {
- Unspecified = 0,
- Utc = 1,
- Local = 2,
- }
-}
diff --git a/src/mscorlib/src/System/DateTimeOffset.cs b/src/mscorlib/src/System/DateTimeOffset.cs
deleted file mode 100644
index d64ba1582e..0000000000
--- a/src/mscorlib/src/System/DateTimeOffset.cs
+++ /dev/null
@@ -1,830 +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.
-
-namespace System {
-
- using System;
- using System.Threading;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- // DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
- // ie. how far away the time is from GMT. The DateTime is stored whole, and the offset
- // is stored as an Int16 internally to save space, but presented as a TimeSpan.
- //
- // The range is constrained so that both the represented clock time and the represented
- // UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime
- // for actual UTC times, and a slightly constrained range on one end when an offset is
- // present.
- //
- // This class should be substitutable for date time in most cases; so most operations
- // effectively work on the clock time. However, the underlying UTC time is what counts
- // for the purposes of identity, sorting and subtracting two instances.
- //
- //
- // There are theoretically two date times stored, the UTC and the relative local representation
- // or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable
- // for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this
- // out and for internal readability.
-
- [StructLayout(LayoutKind.Auto)]
- [Serializable]
- public struct DateTimeOffset : IComparable, IFormattable,
- IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback
- {
- // Constants
- internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14;
- internal const Int64 MinOffset = -MaxOffset;
-
- private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000
- private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800
- private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000
-
- internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
- internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
-
- // Static Fields
- public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
- public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero);
-
- // Instance Fields
- private DateTime m_dateTime;
- private Int16 m_offsetMinutes;
-
- // Constructors
-
- // Constructs a DateTimeOffset from a tick count and offset
- public DateTimeOffset(long ticks, TimeSpan offset) {
- m_offsetMinutes = ValidateOffset(offset);
- // Let the DateTime constructor do the range checks
- DateTime dateTime = new DateTime(ticks);
- m_dateTime = ValidateDate(dateTime, offset);
- }
-
- // Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
- // extracts the local offset. For UTC, creates a UTC instance with a zero offset.
- public DateTimeOffset(DateTime dateTime) {
- TimeSpan offset;
- if (dateTime.Kind != DateTimeKind.Utc) {
- // Local and Unspecified are both treated as Local
- offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
- else {
- offset = new TimeSpan(0);
- }
- m_offsetMinutes = ValidateOffset(offset);
- m_dateTime = ValidateDate(dateTime, offset);
- }
-
- // Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time
- // consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that
- // the offset corresponds to the local.
- public DateTimeOffset(DateTime dateTime, TimeSpan offset) {
- if (dateTime.Kind == DateTimeKind.Local) {
- if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), nameof(offset));
- }
- }
- else if (dateTime.Kind == DateTimeKind.Utc) {
- if (offset != TimeSpan.Zero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), nameof(offset));
- }
- }
- m_offsetMinutes = ValidateOffset(offset);
- m_dateTime = ValidateDate(dateTime, offset);
- }
-
- // Constructs a DateTimeOffset from a given year, month, day, hour,
- // minute, second and offset.
- public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) {
- m_offsetMinutes = ValidateOffset(offset);
- m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset);
- }
-
- // Constructs a DateTimeOffset from a given year, month, day, hour,
- // minute, second, millsecond and offset
- public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) {
- m_offsetMinutes = ValidateOffset(offset);
- m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset);
- }
-
-
- // Constructs a DateTimeOffset from a given year, month, day, hour,
- // minute, second, millsecond, Calendar and offset.
- public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) {
- m_offsetMinutes = ValidateOffset(offset);
- m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset);
- }
-
- // 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.
- //
- public static DateTimeOffset Now {
- get {
- return new DateTimeOffset(DateTime.Now);
- }
- }
-
- public static DateTimeOffset UtcNow {
- get {
- return new DateTimeOffset(DateTime.UtcNow);
- }
- }
-
- public DateTime DateTime {
- get {
- return ClockDateTime;
- }
- }
-
- public DateTime UtcDateTime {
- [Pure]
- get {
- Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
- return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
- }
- }
-
- public DateTime LocalDateTime {
- [Pure]
- get {
- Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
- return UtcDateTime.ToLocalTime();
- }
- }
-
- // Adjust to a given offset with the same UTC time. Can throw ArgumentException
- //
- public DateTimeOffset ToOffset(TimeSpan offset) {
- return new DateTimeOffset((m_dateTime + offset).Ticks, offset);
- }
-
-
- // Instance Properties
-
- // The clock or visible time represented. This is just a wrapper around the internal date because this is
- // the chosen storage mechanism. Going through this helper is good for readability and maintainability.
- // This should be used for display but not identity.
- private DateTime ClockDateTime {
- get {
- return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
- }
- }
-
- // Returns the date part of this DateTimeOffset. The resulting value
- // corresponds to this DateTimeOffset with the time-of-day part set to
- // zero (midnight).
- //
- public DateTime Date {
- get {
- return ClockDateTime.Date;
- }
- }
-
- // Returns the day-of-month part of this DateTimeOffset. The returned
- // value is an integer between 1 and 31.
- //
- public int Day {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1);
- Contract.Ensures(Contract.Result<int>() <= 31);
- return ClockDateTime.Day;
- }
- }
-
- // Returns the day-of-week part of this DateTimeOffset. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
- public DayOfWeek DayOfWeek {
- get {
- Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
- Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
- return ClockDateTime.DayOfWeek;
- }
- }
-
- // Returns the day-of-year part of this DateTimeOffset. The returned value
- // is an integer between 1 and 366.
- //
- public int DayOfYear {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1);
- Contract.Ensures(Contract.Result<int>() <= 366); // leap year
- return ClockDateTime.DayOfYear;
- }
- }
-
- // Returns the hour part of this DateTimeOffset. The returned value is an
- // integer between 0 and 23.
- //
- public int Hour {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 24);
- return ClockDateTime.Hour;
- }
- }
-
-
- // Returns the millisecond part of this DateTimeOffset. The returned value
- // is an integer between 0 and 999.
- //
- public int Millisecond {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 1000);
- return ClockDateTime.Millisecond;
- }
- }
-
- // Returns the minute part of this DateTimeOffset. The returned value is
- // an integer between 0 and 59.
- //
- public int Minute {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 60);
- return ClockDateTime.Minute;
- }
- }
-
- // Returns the month part of this DateTimeOffset. The returned value is an
- // integer between 1 and 12.
- //
- public int Month {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1);
- return ClockDateTime.Month;
- }
- }
-
- public TimeSpan Offset {
- get {
- return new TimeSpan(0, m_offsetMinutes, 0);
- }
- }
-
- // Returns the second part of this DateTimeOffset. The returned value is
- // an integer between 0 and 59.
- //
- public int Second {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- Contract.Ensures(Contract.Result<int>() < 60);
- return ClockDateTime.Second;
- }
- }
-
- // Returns the tick count for this DateTimeOffset. The returned value is
- // the number of 100-nanosecond intervals that have elapsed since 1/1/0001
- // 12:00am.
- //
- public long Ticks {
- get {
- return ClockDateTime.Ticks;
- }
- }
-
- public long UtcTicks {
- get {
- return UtcDateTime.Ticks;
- }
- }
-
- // Returns the time-of-day part of this DateTimeOffset. The returned value
- // is a TimeSpan that indicates the time elapsed since midnight.
- //
- public TimeSpan TimeOfDay {
- get {
- return ClockDateTime.TimeOfDay;
- }
- }
-
- // Returns the year part of this DateTimeOffset. The returned value is an
- // integer between 1 and 9999.
- //
- public int Year {
- get {
- Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
- return ClockDateTime.Year;
- }
- }
-
- // Returns the DateTimeOffset resulting from adding the given
- // TimeSpan to this DateTimeOffset.
- //
- public DateTimeOffset Add(TimeSpan timeSpan) {
- return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset);
- }
-
- // Returns the DateTimeOffset resulting from adding a fractional number of
- // days to this DateTimeOffset. The result is computed by rounding the
- // fractional number of days given by value to the nearest
- // millisecond, and adding that interval to this DateTimeOffset. The
- // value argument is permitted to be negative.
- //
- public DateTimeOffset AddDays(double days) {
- return new DateTimeOffset(ClockDateTime.AddDays(days), Offset);
- }
-
- // Returns the DateTimeOffset resulting from adding a fractional number of
- // hours to this DateTimeOffset. The result is computed by rounding the
- // fractional number of hours given by value to the nearest
- // millisecond, and adding that interval to this DateTimeOffset. The
- // value argument is permitted to be negative.
- //
- public DateTimeOffset AddHours(double hours) {
- return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset);
- }
-
- // Returns the DateTimeOffset resulting from the given number of
- // milliseconds to this DateTimeOffset. The result is computed by rounding
- // the number of milliseconds given by value to the nearest integer,
- // and adding that interval to this DateTimeOffset. The value
- // argument is permitted to be negative.
- //
- public DateTimeOffset AddMilliseconds(double milliseconds) {
- return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset);
- }
-
- // Returns the DateTimeOffset resulting from adding a fractional number of
- // minutes to this DateTimeOffset. The result is computed by rounding the
- // fractional number of minutes given by value to the nearest
- // millisecond, and adding that interval to this DateTimeOffset. The
- // value argument is permitted to be negative.
- //
- public DateTimeOffset AddMinutes(double minutes) {
- return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
- }
-
- public DateTimeOffset AddMonths(int months) {
- return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset);
- }
-
- // Returns the DateTimeOffset resulting from adding a fractional number of
- // seconds to this DateTimeOffset. The result is computed by rounding the
- // fractional number of seconds given by value to the nearest
- // millisecond, and adding that interval to this DateTimeOffset. The
- // value argument is permitted to be negative.
- //
- public DateTimeOffset AddSeconds(double seconds) {
- return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset);
- }
-
- // Returns the DateTimeOffset resulting from adding the given number of
- // 100-nanosecond ticks to this DateTimeOffset. The value argument
- // is permitted to be negative.
- //
- public DateTimeOffset AddTicks(long ticks) {
- return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset);
- }
-
- // Returns the DateTimeOffset resulting from adding the given number of
- // years to this DateTimeOffset. The result is computed by incrementing
- // (or decrementing) the year part of this DateTimeOffset by value
- // years. If the month and day of this DateTimeOffset is 2/29, and if the
- // resulting year is not a leap year, the month and day of the resulting
- // DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day
- // parts of the result are the same as those of this DateTimeOffset.
- //
- public DateTimeOffset AddYears(int years) {
- return new DateTimeOffset(ClockDateTime.AddYears(years), Offset);
- }
-
- // Compares two DateTimeOffset values, returning an integer that indicates
- // their relationship.
- //
- public static int Compare(DateTimeOffset first, DateTimeOffset second) {
- return DateTime.Compare(first.UtcDateTime, second.UtcDateTime);
- }
-
- // Compares this DateTimeOffset to a given object. This method provides an
- // implementation of the IComparable interface. The object
- // argument must be another DateTimeOffset, or otherwise an exception
- // occurs. Null is considered less than any instance.
- //
- int IComparable.CompareTo(Object obj) {
- if (obj == null) return 1;
- if (!(obj is DateTimeOffset)) {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset"));
- }
-
- DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
- DateTime utc = UtcDateTime;
- if (utc > objUtc) return 1;
- if (utc < objUtc) return -1;
- return 0;
- }
-
- public int CompareTo(DateTimeOffset other) {
- DateTime otherUtc = other.UtcDateTime;
- DateTime utc = UtcDateTime;
- if (utc > otherUtc) return 1;
- if (utc < otherUtc) return -1;
- return 0;
- }
-
-
- // Checks if this DateTimeOffset is equal to a given object. Returns
- // true if the given object is a boxed DateTimeOffset and its value
- // is equal to the value of this DateTimeOffset. Returns false
- // otherwise.
- //
- public override bool Equals(Object obj) {
- if (obj is DateTimeOffset) {
- return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
- }
- return false;
- }
-
- public bool Equals(DateTimeOffset other) {
- return UtcDateTime.Equals(other.UtcDateTime);
- }
-
- public bool EqualsExact(DateTimeOffset other) {
- //
- // returns true when the ClockDateTime, Kind, and Offset match
- //
- // currently the Kind should always be Unspecified, but there is always the possibility that a future version
- // of DateTimeOffset overloads the Kind field
- //
- return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind);
- }
-
- // Compares two DateTimeOffset values for equality. Returns true if
- // the two DateTimeOffset values are equal, or false if they are
- // not equal.
- //
- public static bool Equals(DateTimeOffset first, DateTimeOffset second) {
- return DateTime.Equals(first.UtcDateTime, second.UtcDateTime);
- }
-
- // Creates a DateTimeOffset from a Windows filetime. A Windows filetime is
- // a long representing the date and time as the number of
- // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
- //
- public static DateTimeOffset FromFileTime(long fileTime) {
- return new DateTimeOffset(DateTime.FromFileTime(fileTime));
- }
-
- public static DateTimeOffset FromUnixTimeSeconds(long seconds) {
- if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) {
- throw new ArgumentOutOfRangeException(nameof(seconds),
- string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), UnixMinSeconds, UnixMaxSeconds));
- }
-
- long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks;
- return new DateTimeOffset(ticks, TimeSpan.Zero);
- }
-
- public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) {
- const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
- const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
-
- if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) {
- throw new ArgumentOutOfRangeException(nameof(milliseconds),
- string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds));
- }
-
- long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks;
- return new DateTimeOffset(ticks, TimeSpan.Zero);
- }
-
- // ----- SECTION: private serialization instance methods ----------------*
-
- void IDeserializationCallback.OnDeserialization(Object sender) {
- try {
- m_offsetMinutes = ValidateOffset(Offset);
- m_dateTime = ValidateDate(ClockDateTime, Offset);
- }
- catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
- }
- }
-
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info == null) {
- throw new ArgumentNullException(nameof(info));
- }
-
- Contract.EndContractBlock();
-
- info.AddValue("DateTime", m_dateTime);
- info.AddValue("OffsetMinutes", m_offsetMinutes);
- }
-
-
- DateTimeOffset(SerializationInfo info, StreamingContext context) {
- if (info == null) {
- throw new ArgumentNullException(nameof(info));
- }
-
- m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
- m_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16));
- }
-
- // Returns the hash code for this DateTimeOffset.
- //
- public override int GetHashCode() {
- return UtcDateTime.GetHashCode();
- }
-
- // Constructs a DateTimeOffset from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTimeOffset Parse(String input) {
- TimeSpan offset;
- DateTime dateResult = DateTimeParse.Parse(input,
- DateTimeFormatInfo.CurrentInfo,
- DateTimeStyles.None,
- out offset);
- return new DateTimeOffset(dateResult.Ticks, offset);
- }
-
- // Constructs a DateTimeOffset from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) {
- return Parse(input, formatProvider, DateTimeStyles.None);
- }
-
- public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
- styles = ValidateStyles(styles, nameof(styles));
- TimeSpan offset;
- DateTime dateResult = DateTimeParse.Parse(input,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out offset);
- return new DateTimeOffset(dateResult.Ticks, offset);
- }
-
- // Constructs a DateTimeOffset from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) {
- return ParseExact(input, format, formatProvider, DateTimeStyles.None);
- }
-
- // Constructs a DateTimeOffset from a string. The string must specify a
- // date and optionally a time in a culture-specific or universal format.
- // Leading and trailing whitespace characters are allowed.
- //
- public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) {
- styles = ValidateStyles(styles, nameof(styles));
- TimeSpan offset;
- DateTime dateResult = DateTimeParse.ParseExact(input,
- format,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out offset);
- return new DateTimeOffset(dateResult.Ticks, offset);
- }
-
- public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) {
- styles = ValidateStyles(styles, nameof(styles));
- TimeSpan offset;
- DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
- formats,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out offset);
- return new DateTimeOffset(dateResult.Ticks, offset);
- }
-
- public TimeSpan Subtract(DateTimeOffset value) {
- return UtcDateTime.Subtract(value.UtcDateTime);
- }
-
- public DateTimeOffset Subtract(TimeSpan value) {
- return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
- }
-
-
- public long ToFileTime() {
- return UtcDateTime.ToFileTime();
- }
-
- public long ToUnixTimeSeconds() {
- // Truncate sub-second precision before offsetting by the Unix Epoch to avoid
- // the last digit being off by one for dates that result in negative Unix times.
- //
- // For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0
- // ticks = 621355967990010000
- // ticksFromEpoch = ticks - UnixEpochTicks = -9990000
- // secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0
- //
- // Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division,
- // whereas we actually always want to round *down* when converting to Unix time. This happens
- // automatically for positive Unix time values. Now the example becomes:
- // seconds = ticks / TimeSpan.TicksPerSecond = 62135596799
- // secondsFromEpoch = seconds - UnixEpochSeconds = -1
- //
- // In other words, we want to consistently round toward the time 1/1/0001 00:00:00,
- // rather than toward the Unix Epoch (1/1/1970 00:00:00).
- long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond;
- return seconds - UnixEpochSeconds;
- }
-
- public long ToUnixTimeMilliseconds() {
- // Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid
- // the last digit being off by one for dates that result in negative Unix times
- long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond;
- return milliseconds - UnixEpochMilliseconds;
- }
-
- public DateTimeOffset ToLocalTime() {
- return ToLocalTime(false);
- }
-
- internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
- {
- return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
- }
-
- public override String ToString() {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset);
- }
-
- public String ToString(String format) {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset);
- }
-
- public String ToString(IFormatProvider formatProvider) {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
- }
-
- public String ToString(String format, IFormatProvider formatProvider) {
- Contract.Ensures(Contract.Result<String>() != null);
- return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
- }
-
- public DateTimeOffset ToUniversalTime() {
- return new DateTimeOffset(UtcDateTime);
- }
-
- public static Boolean TryParse(String input, out DateTimeOffset result) {
- TimeSpan offset;
- DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParse(input,
- DateTimeFormatInfo.CurrentInfo,
- DateTimeStyles.None,
- out dateResult,
- out offset);
- result = new DateTimeOffset(dateResult.Ticks, offset);
- return parsed;
- }
-
- public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) {
- styles = ValidateStyles(styles, nameof(styles));
- TimeSpan offset;
- DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParse(input,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out dateResult,
- out offset);
- result = new DateTimeOffset(dateResult.Ticks, offset);
- return parsed;
- }
-
- public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
- out DateTimeOffset result) {
- styles = ValidateStyles(styles, nameof(styles));
- TimeSpan offset;
- DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParseExact(input,
- format,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out dateResult,
- out offset);
- result = new DateTimeOffset(dateResult.Ticks, offset);
- return parsed;
- }
-
- public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
- out DateTimeOffset result) {
- styles = ValidateStyles(styles, nameof(styles));
- TimeSpan offset;
- DateTime dateResult;
- Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
- formats,
- DateTimeFormatInfo.GetInstance(formatProvider),
- styles,
- out dateResult,
- out offset);
- result = new DateTimeOffset(dateResult.Ticks, offset);
- return parsed;
- }
-
- // Ensures the TimeSpan is valid to go in a DateTimeOffset.
- private static Int16 ValidateOffset(TimeSpan offset) {
- Int64 ticks = offset.Ticks;
- if (ticks % TimeSpan.TicksPerMinute != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), nameof(offset));
- }
- if (ticks < MinOffset || ticks > MaxOffset) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("Argument_OffsetOutOfRange"));
- }
- return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
- }
-
- // Ensures that the time and offset are in range.
- private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
- // The key validation is that both the UTC and clock times fit. The clock time is validated
- // by the DateTime constructor.
- Debug.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
- // This operation cannot overflow because offset should have already been validated to be within
- // 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
- Int64 utcTicks = dateTime.Ticks - offset.Ticks;
- if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("Argument_UTCOutOfRange"));
- }
- // make sure the Kind is set to Unspecified
- //
- return new DateTime(utcTicks, DateTimeKind.Unspecified);
- }
-
- private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) {
- if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
- }
- if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
- }
- if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName);
- }
-
- Contract.EndContractBlock();
- // RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime
- style &= ~DateTimeStyles.RoundtripKind;
-
- // AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
- style &= ~DateTimeStyles.AssumeLocal;
-
- return style;
- }
-
- // Operators
-
- public static implicit operator DateTimeOffset (DateTime dateTime) {
- return new DateTimeOffset(dateTime);
- }
-
- public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
- return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
- }
-
-
- public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
- return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
- }
-
- public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime - right.UtcDateTime;
- }
-
- public static bool operator ==(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime == right.UtcDateTime;
- }
-
- public static bool operator !=(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime != right.UtcDateTime;
- }
-
- public static bool operator <(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime < right.UtcDateTime;
- }
-
- public static bool operator <=(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime <= right.UtcDateTime;
- }
-
- public static bool operator >(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime > right.UtcDateTime;
- }
-
- public static bool operator >=(DateTimeOffset left, DateTimeOffset right) {
- return left.UtcDateTime >= right.UtcDateTime;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/DayOfWeek.cs b/src/mscorlib/src/System/DayOfWeek.cs
deleted file mode 100644
index 5d84257158..0000000000
--- a/src/mscorlib/src/System/DayOfWeek.cs
+++ /dev/null
@@ -1,27 +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: Enum for the day of the week.
-**
-**
-============================================================*/
-
-namespace System
-{
- [Serializable]
- public enum DayOfWeek
- {
- Sunday = 0,
- Monday = 1,
- Tuesday = 2,
- Wednesday = 3,
- Thursday = 4,
- Friday = 5,
- Saturday = 6,
- }
-}
diff --git a/src/mscorlib/src/System/Decimal.cs b/src/mscorlib/src/System/Decimal.cs
index a01ed19753..ce59a99334 100644
--- a/src/mscorlib/src/System/Decimal.cs
+++ b/src/mscorlib/src/System/Decimal.cs
@@ -2,17 +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.
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
+using System.Runtime.Serialization;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// Implements the Decimal data type. The Decimal data type can
// represent values ranging from -79,228,162,514,264,337,593,543,950,335 to
// 79,228,162,514,264,337,593,543,950,335 with 28 significant digits. The
@@ -60,31 +61,30 @@ namespace System {
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct Decimal : IFormattable, IComparable, IConvertible, IComparable<Decimal>, IEquatable<Decimal>, IDeserializationCallback
{
-
// Sign mask for the flags field. A value of zero in this bit indicates a
// positive Decimal value, and a value of one in this bit indicates a
// negative Decimal value.
//
// Look at OleAut's DECIMAL_NEG constant to check for negative values
// in native code.
- private const int SignMask = unchecked((int)0x80000000);
+ private const int SignMask = unchecked((int)0x80000000);
private const byte DECIMAL_NEG = 0x80;
private const byte DECIMAL_ADD = 0x00;
-
+
// Scale mask for the flags field. This byte in the flags field contains
// the power of 10 to divide the Decimal value by. The scale byte must
// contain a value between 0 and 28 inclusive.
private const int ScaleMask = 0x00FF0000;
-
+
// Number of bits scale is shifted by.
private const int ScaleShift = 16;
-
+
// The maximum power of 10 that a 32 bit integer can store
private const Int32 MaxInt32Scale = 9;
// Fast access for 10^n where n is 0-9
private static UInt32[] Powers10 = new UInt32[] {
- 1,
+ 1,
10,
100,
1000,
@@ -94,21 +94,21 @@ namespace System {
10000000,
100000000,
1000000000
- };
-
+ };
+
// Constant representing the Decimal value 0.
public const Decimal Zero = 0m;
-
+
// Constant representing the Decimal value 1.
public const Decimal One = 1m;
-
+
// Constant representing the Decimal value -1.
public const Decimal MinusOne = -1m;
-
+
// Constant representing the largest possible Decimal value. The value of
// this constant is 79,228,162,514,264,337,593,543,950,335.
public const Decimal MaxValue = 79228162514264337593543950335m;
-
+
// Constant representing the smallest possible Decimal value. The value of
// this constant is -79,228,162,514,264,337,593,543,950,335.
public const Decimal MinValue = -79228162514264337593543950335m;
@@ -120,8 +120,8 @@ namespace System {
// Constant representing the positive number that is the closest possible
// Decimal value to +0m.
- private const Decimal NearPositiveZero = +0.000000000000000000000000001m;
-
+ private const Decimal NearPositiveZero = +0.000000000000000000000000001m;
+
// The lo, mid, hi, and flags fields contain the representation of the
// Decimal value. The lo, mid, and hi fields contain the 96-bit integer
// part of the Decimal. Bits 0-15 (the lower word) of the flags field are
@@ -137,8 +137,8 @@ namespace System {
private int hi;
private int lo;
private int mid;
-
-
+
+
// Constructs a zero Decimal.
//public Decimal() {
// lo = 0;
@@ -146,17 +146,20 @@ namespace System {
// hi = 0;
// flags = 0;
//}
-
+
// Constructs a Decimal from an integer value.
//
- public Decimal(int value) {
+ public Decimal(int value)
+ {
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
- int value_copy = value;
- if (value_copy >= 0) {
+ int value_copy = value;
+ if (value_copy >= 0)
+ {
flags = 0;
}
- else {
+ else
+ {
flags = SignMask;
value_copy = -value_copy;
}
@@ -164,27 +167,31 @@ namespace System {
mid = 0;
hi = 0;
}
-
+
// Constructs a Decimal from an unsigned integer value.
//
[CLSCompliant(false)]
- public Decimal(uint value) {
+ public Decimal(uint value)
+ {
flags = 0;
- lo = (int) value;
+ lo = (int)value;
mid = 0;
hi = 0;
}
-
+
// Constructs a Decimal from a long value.
//
- public Decimal(long value) {
+ public Decimal(long value)
+ {
// JIT today can't inline methods that contains "starg" opcode.
// For more details, see DevDiv Bugs 81184: x86 JIT CQ: Removing the inline striction of "starg".
long value_copy = value;
- if (value_copy >= 0) {
+ if (value_copy >= 0)
+ {
flags = 0;
}
- else {
+ else
+ {
flags = SignMask;
value_copy = -value_copy;
}
@@ -192,30 +199,32 @@ namespace System {
mid = (int)(value_copy >> 32);
hi = 0;
}
-
+
// Constructs a Decimal from an unsigned long value.
//
- [CLSCompliant(false)]
- public Decimal(ulong value) {
+ [CLSCompliant(false)]
+ public Decimal(ulong value)
+ {
flags = 0;
lo = (int)value;
mid = (int)(value >> 32);
hi = 0;
}
-
+
// Constructs a Decimal from a float value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Decimal(float value);
-
+
// Constructs a Decimal from a double value.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern Decimal(double value);
-
+
// Constructs a Decimal from a Currency value.
//
- internal Decimal(Currency value) {
+ internal Decimal(Currency value)
+ {
this = Currency.ToDecimal(value);
}
@@ -225,13 +234,13 @@ namespace System {
{
return new Currency(value).ToOACurrency();
}
-
+
public static Decimal FromOACurrency(long cy)
{
return Currency.ToDecimal(Currency.FromOACurrency(cy));
}
-
+
// Constructs a Decimal from an integer array containing a binary
// representation. The bits argument must be a non-null integer
// array with four elements. bits[0], bits[1], and
@@ -251,21 +260,25 @@ namespace System {
// The possible binary representations of a particular value are all
// equally valid, and all are numerically equivalent.
//
- public Decimal(int[] bits) {
- this.lo = 0;
- this.mid = 0;
- this.hi = 0;
- this.flags = 0;
+ public Decimal(int[] bits)
+ {
+ lo = 0;
+ mid = 0;
+ hi = 0;
+ flags = 0;
SetBits(bits);
}
- private void SetBits(int[] bits) {
- if (bits==null)
+ private void SetBits(int[] bits)
+ {
+ if (bits == null)
throw new ArgumentNullException(nameof(bits));
Contract.EndContractBlock();
- if (bits.Length == 4) {
+ if (bits.Length == 4)
+ {
int f = bits[3];
- if ((f & ~(SignMask | ScaleMask)) == 0 && (f & ScaleMask) <= (28 << 16)) {
+ if ((f & ~(SignMask | ScaleMask)) == 0 && (f & ScaleMask) <= (28 << 16))
+ {
lo = bits[0];
mid = bits[1];
hi = bits[2];
@@ -273,94 +286,108 @@ namespace System {
return;
}
}
- throw new ArgumentException(Environment.GetResourceString("Arg_DecBitCtor"));
+ throw new ArgumentException(SR.Arg_DecBitCtor);
}
-
+
// Constructs a Decimal from its constituent parts.
//
- public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) {
+ public Decimal(int lo, int mid, int hi, bool isNegative, byte scale)
+ {
if (scale > 28)
- throw new ArgumentOutOfRangeException(nameof(scale), Environment.GetResourceString("ArgumentOutOfRange_DecimalScale"));
+ throw new ArgumentOutOfRangeException(nameof(scale), SR.ArgumentOutOfRange_DecimalScale);
Contract.EndContractBlock();
this.lo = lo;
this.mid = mid;
this.hi = hi;
- this.flags = ((int)scale) << 16;
+ flags = ((int)scale) << 16;
if (isNegative)
- this.flags |= SignMask;
+ flags |= SignMask;
}
[OnSerializing]
- void OnSerializing(StreamingContext ctx) {
+ private void OnSerializing(StreamingContext ctx)
+ {
// OnSerializing is called before serialization of an object
- try {
- SetBits( GetBits(this) );
- } catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Overflow_Decimal"), e);
- }
+ try
+ {
+ SetBits(GetBits(this));
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(SR.Overflow_Decimal, e);
+ }
}
- void IDeserializationCallback.OnDeserialization(Object sender) {
+ void IDeserializationCallback.OnDeserialization(Object sender)
+ {
// OnDeserialization is called after each instance of this class is deserialized.
// This callback method performs decimal validation after being deserialized.
- try {
- SetBits( GetBits(this) );
- } catch (ArgumentException e) {
- throw new SerializationException(Environment.GetResourceString("Overflow_Decimal"), e);
- }
+ try
+ {
+ SetBits(GetBits(this));
+ }
+ catch (ArgumentException e)
+ {
+ throw new SerializationException(SR.Overflow_Decimal, e);
+ }
}
-
+
// Constructs a Decimal from its constituent parts.
- private Decimal(int lo, int mid, int hi, int flags) {
- if ((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)) {
+ private Decimal(int lo, int mid, int hi, int flags)
+ {
+ if ((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16))
+ {
this.lo = lo;
this.mid = mid;
this.hi = hi;
this.flags = flags;
return;
}
- throw new ArgumentException(Environment.GetResourceString("Arg_DecBitCtor"));
+ throw new ArgumentException(SR.Arg_DecBitCtor);
}
-
+
// Returns the absolute value of the given Decimal. If d is
// positive, the result is d. If d is negative, the result
// is -d.
//
- internal static Decimal Abs(Decimal d) {
+ internal static Decimal Abs(Decimal d)
+ {
return new Decimal(d.lo, d.mid, d.hi, d.flags & ~SignMask);
}
-
+
// Adds two Decimal values.
//
public static Decimal Add(Decimal d1, Decimal d2)
{
- FCallAddSub (ref d1, ref d2, DECIMAL_ADD);
+ FCallAddSub(ref d1, ref d2, DECIMAL_ADD);
return d1;
}
-
+
// FCallAddSub adds or subtracts two decimal values. On return, d1 contains the result
// of the operation. Passing in DECIMAL_ADD or DECIMAL_NEG for bSign indicates
// addition or subtraction, respectively.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallAddSub(ref Decimal d1, ref Decimal d2, byte bSign);
-
+
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards positive infinity.
- public static Decimal Ceiling(Decimal d) {
+ public static Decimal Ceiling(Decimal d)
+ {
return (-(Decimal.Floor(-d)));
- }
-
+ }
+
// Compares two Decimal values, returning an integer that indicates their
// relationship.
//
- public static int Compare(Decimal d1, Decimal d2) {
+ public static int Compare(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int FCallCompare(ref Decimal d1, ref Decimal d2);
-
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
@@ -372,9 +399,9 @@ namespace System {
if (value == null)
return 1;
if (!(value is Decimal))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"));
-
- Decimal other = (Decimal)value;
+ throw new ArgumentException(SR.Arg_MustBeDecimal);
+
+ Decimal other = (Decimal)value;
return FCallCompare(ref this, ref other);
}
@@ -382,12 +409,12 @@ namespace System {
{
return FCallCompare(ref this, ref value);
}
-
+
// Divides two Decimal values.
//
public static Decimal Divide(Decimal d1, Decimal d2)
{
- FCallDivide (ref d1, ref d2);
+ FCallDivide(ref d1, ref d2);
return d1;
}
@@ -397,13 +424,15 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallDivide(ref Decimal d1, ref Decimal d2);
-
+
// Checks if this Decimal is equal to a given object. Returns true
// if the given object is a boxed Decimal and its value is equal to the
// value of this Decimal. Returns false otherwise.
//
- public override bool Equals(Object value) {
- if (value is Decimal) {
+ public override bool Equals(Object value)
+ {
+ if (value is Decimal)
+ {
Decimal other = (Decimal)value;
return FCallCompare(ref this, ref other) == 0;
}
@@ -419,52 +448,57 @@ namespace System {
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override int GetHashCode();
-
+
// Compares two Decimal values for equality. Returns true if the two
// Decimal values are equal, or false if they are not equal.
//
- public static bool Equals(Decimal d1, Decimal d2) {
+ public static bool Equals(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) == 0;
}
-
+
// Rounds a Decimal to an integer value. The Decimal argument is rounded
// towards negative infinity.
//
public static Decimal Floor(Decimal d)
{
- FCallFloor (ref d);
+ FCallFloor(ref d);
return d;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void FCallFloor(ref Decimal d);
+ private static extern void FCallFloor(ref Decimal d);
// Converts this Decimal to a string. The resulting string consists of an
// optional minus sign ("-") followed to a sequence of digits ("0" - "9"),
// optionally followed by a decimal point (".") and another sequence of
// digits.
//
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo);
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider));
- }
+ }
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider));
}
-
+
// Converts a string to a Decimal. The string must consist of an optional
// minus sign ("-") followed by a sequence of digits ("0" - "9"). The
// sequence of digits may optionally contain a single decimal point (".")
@@ -472,29 +506,35 @@ namespace System {
// Parse also allows a currency symbol, a trailing negative sign, and
// parentheses in the number.
//
- public static Decimal Parse(String s) {
+ public static Decimal Parse(String s)
+ {
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
-
- public static Decimal Parse(String s, NumberStyles style) {
+
+ public static Decimal Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo);
}
- public static Decimal Parse(String s, IFormatProvider provider) {
+ public static Decimal Parse(String s, IFormatProvider provider)
+ {
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider));
}
-
- public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider) {
+
+ public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider));
}
-
- public static Boolean TryParse(String s, out Decimal result) {
+
+ public static Boolean TryParse(String s, out Decimal result)
+ {
return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result);
}
- public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result) {
+ public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
@@ -509,160 +549,181 @@ namespace System {
// indicates the sign of the Decimal value, 0 meaning positive and 1
// meaning negative.
//
- public static int[] GetBits(Decimal d) {
- return new int[] {d.lo, d.mid, d.hi, d.flags};
+ public static int[] GetBits(Decimal d)
+ {
+ return new int[] { d.lo, d.mid, d.hi, d.flags };
}
- internal static void GetBytes(Decimal d, byte [] buffer) {
+ internal static void GetBytes(Decimal d, byte[] buffer)
+ {
Contract.Requires((buffer != null && buffer.Length >= 16), "[GetBytes]buffer != null && buffer.Length >= 16");
- buffer[0] = (byte) d.lo;
- buffer[1] = (byte) (d.lo >> 8);
- buffer[2] = (byte) (d.lo >> 16);
- buffer[3] = (byte) (d.lo >> 24);
-
- buffer[4] = (byte) d.mid;
- buffer[5] = (byte) (d.mid >> 8);
- buffer[6] = (byte) (d.mid >> 16);
- buffer[7] = (byte) (d.mid >> 24);
-
- buffer[8] = (byte) d.hi;
- buffer[9] = (byte) (d.hi >> 8);
- buffer[10] = (byte) (d.hi >> 16);
- buffer[11] = (byte) (d.hi >> 24);
-
- buffer[12] = (byte) d.flags;
- buffer[13] = (byte) (d.flags >> 8);
- buffer[14] = (byte) (d.flags >> 16);
- buffer[15] = (byte) (d.flags >> 24);
- }
-
- internal static decimal ToDecimal(byte [] buffer) {
+ buffer[0] = (byte)d.lo;
+ buffer[1] = (byte)(d.lo >> 8);
+ buffer[2] = (byte)(d.lo >> 16);
+ buffer[3] = (byte)(d.lo >> 24);
+
+ buffer[4] = (byte)d.mid;
+ buffer[5] = (byte)(d.mid >> 8);
+ buffer[6] = (byte)(d.mid >> 16);
+ buffer[7] = (byte)(d.mid >> 24);
+
+ buffer[8] = (byte)d.hi;
+ buffer[9] = (byte)(d.hi >> 8);
+ buffer[10] = (byte)(d.hi >> 16);
+ buffer[11] = (byte)(d.hi >> 24);
+
+ buffer[12] = (byte)d.flags;
+ buffer[13] = (byte)(d.flags >> 8);
+ buffer[14] = (byte)(d.flags >> 16);
+ buffer[15] = (byte)(d.flags >> 24);
+ }
+
+ internal static decimal ToDecimal(byte[] buffer)
+ {
Contract.Requires((buffer != null && buffer.Length >= 16), "[ToDecimal]buffer != null && buffer.Length >= 16");
int lo = ((int)buffer[0]) | ((int)buffer[1] << 8) | ((int)buffer[2] << 16) | ((int)buffer[3] << 24);
int mid = ((int)buffer[4]) | ((int)buffer[5] << 8) | ((int)buffer[6] << 16) | ((int)buffer[7] << 24);
int hi = ((int)buffer[8]) | ((int)buffer[9] << 8) | ((int)buffer[10] << 16) | ((int)buffer[11] << 24);
int flags = ((int)buffer[12]) | ((int)buffer[13] << 8) | ((int)buffer[14] << 16) | ((int)buffer[15] << 24);
- return new Decimal(lo,mid,hi,flags);
+ return new Decimal(lo, mid, hi, flags);
}
-
+
// This method does a 'raw' and 'unchecked' addition of a UInt32 to a Decimal in place.
// 'raw' means that it operates on the internal 96-bit unsigned integer value and
// ingores the sign and scale. This means that it is not equivalent to just adding
// that number, as the sign and scale are effectively applied to the UInt32 value also.
// 'unchecked' means that it does not fail if you overflow the 96 bit value.
- private static void InternalAddUInt32RawUnchecked(ref Decimal value, UInt32 i) {
- UInt32 v;
+ private static void InternalAddUInt32RawUnchecked(ref Decimal value, UInt32 i)
+ {
+ UInt32 v;
UInt32 sum;
v = (UInt32)value.lo;
sum = v + i;
value.lo = (Int32)sum;
- if (sum < v || sum < i) {
+ if (sum < v || sum < i)
+ {
v = (UInt32)value.mid;
sum = v + 1;
value.mid = (Int32)sum;
- if (sum < v || sum < 1) {
- value.hi = (Int32) ((UInt32)value.hi + 1);
- }
+ if (sum < v || sum < 1)
+ {
+ value.hi = (Int32)((UInt32)value.hi + 1);
+ }
}
- }
+ }
// This method does an in-place division of a decimal by a UInt32, returning the remainder.
// Although it does not operate on the sign or scale, this does not result in any
// caveat for the result. It is equivalent to dividing by that number.
- private static UInt32 InternalDivRemUInt32(ref Decimal value, UInt32 divisor) {
+ private static UInt32 InternalDivRemUInt32(ref Decimal value, UInt32 divisor)
+ {
UInt32 remainder = 0;
UInt64 n;
- if (value.hi != 0) {
- n = ((UInt32) value.hi);
+ if (value.hi != 0)
+ {
+ n = ((UInt32)value.hi);
value.hi = (Int32)((UInt32)(n / divisor));
remainder = (UInt32)(n % divisor);
}
- if (value.mid != 0 || remainder != 0) {
- n = ((UInt64)remainder << 32) | (UInt32) value.mid;
+ if (value.mid != 0 || remainder != 0)
+ {
+ n = ((UInt64)remainder << 32) | (UInt32)value.mid;
value.mid = (Int32)((UInt32)(n / divisor));
- remainder = (UInt32)(n % divisor);
+ remainder = (UInt32)(n % divisor);
}
- if (value.lo != 0 || remainder != 0) {
- n = ((UInt64)remainder << 32) | (UInt32) value.lo;
+ if (value.lo != 0 || remainder != 0)
+ {
+ n = ((UInt64)remainder << 32) | (UInt32)value.lo;
value.lo = (Int32)((UInt32)(n / divisor));
- remainder = (UInt32)(n % divisor);
+ remainder = (UInt32)(n % divisor);
}
return remainder;
}
-
+
// Does an in-place round the specified number of digits, rounding mid-point values
// away from zero
- private static void InternalRoundFromZero(ref Decimal d, int decimalCount) {
+ private static void InternalRoundFromZero(ref Decimal d, int decimalCount)
+ {
Int32 scale = (d.flags & ScaleMask) >> ScaleShift;
Int32 scaleDifference = scale - decimalCount;
- if (scaleDifference <= 0) {
+ if (scaleDifference <= 0)
+ {
return;
}
// Divide the value by 10^scaleDifference
UInt32 lastRemainder;
UInt32 lastDivisor;
- do {
+ do
+ {
Int32 diffChunk = (scaleDifference > MaxInt32Scale) ? MaxInt32Scale : scaleDifference;
lastDivisor = Powers10[diffChunk];
lastRemainder = InternalDivRemUInt32(ref d, lastDivisor);
scaleDifference -= diffChunk;
} while (scaleDifference > 0);
-
+
// Round away from zero at the mid point
- if (lastRemainder >= (lastDivisor >> 1)) {
+ if (lastRemainder >= (lastDivisor >> 1))
+ {
InternalAddUInt32RawUnchecked(ref d, 1);
}
-
+
// the scale becomes the desired decimal count
d.flags = ((decimalCount << ScaleShift) & ScaleMask) | (d.flags & SignMask);
}
-
+
// Returns the larger of two Decimal values.
//
- internal static Decimal Max(Decimal d1, Decimal d2) {
- return FCallCompare(ref d1, ref d2) >= 0? d1: d2;
+ internal static Decimal Max(Decimal d1, Decimal d2)
+ {
+ return FCallCompare(ref d1, ref d2) >= 0 ? d1 : d2;
}
-
+
// Returns the smaller of two Decimal values.
//
- internal static Decimal Min(Decimal d1, Decimal d2) {
- return FCallCompare(ref d1, ref d2) < 0? d1: d2;
+ internal static Decimal Min(Decimal d1, Decimal d2)
+ {
+ return FCallCompare(ref d1, ref d2) < 0 ? d1 : d2;
}
-
- public static Decimal Remainder(Decimal d1, Decimal d2) {
+
+ public static Decimal Remainder(Decimal d1, Decimal d2)
+ {
// OleAut doesn't provide a VarDecMod.
-
+
// In the operation x % y the sign of y does not matter. Result will have the sign of x.
- d2.flags = (d2.flags & ~SignMask) | (d1.flags & SignMask);
+ d2.flags = (d2.flags & ~SignMask) | (d1.flags & SignMask);
// This piece of code is to work around the fact that Dividing a decimal with 28 digits number by decimal which causes
// causes the result to be 28 digits, can cause to be incorrectly rounded up.
// eg. Decimal.MaxValue / 2 * Decimal.MaxValue will overflow since the division by 2 was rounded instead of being truncked.
- if (Abs(d1) < Abs(d2)) {
+ if (Abs(d1) < Abs(d2))
+ {
return d1;
}
d1 -= d2;
- if (d1 == 0) {
+ if (d1 == 0)
+ {
// The sign of D1 will be wrong here. Fall through so that we still get a DivideByZeroException
d1.flags = (d1.flags & ~SignMask) | (d2.flags & SignMask);
}
-
+
// Formula: d1 - (RoundTowardsZero(d1 / d2) * d2)
- Decimal dividedResult = Truncate(d1/d2);
+ Decimal dividedResult = Truncate(d1 / d2);
Decimal multipliedResult = dividedResult * d2;
Decimal result = d1 - multipliedResult;
// See if the result has crossed 0
- if ((d1.flags & SignMask) != (result.flags & SignMask)) {
-
- if (NearNegativeZero <= result && result <= NearPositiveZero) {
+ if ((d1.flags & SignMask) != (result.flags & SignMask))
+ {
+ if (NearNegativeZero <= result && result <= NearPositiveZero)
+ {
// Certain Remainder operations on decimals with 28 significant digits round
// to [+-]0.000000000000000000000000001m instead of [+-]0m during the intermediate calculations.
// 'zero' results just need their sign corrected.
result.flags = (result.flags & ~SignMask) | (d1.flags & SignMask);
}
- else {
+ else
+ {
// If the division rounds up because it runs out of digits, the multiplied result can end up with a larger
// absolute value and the result of the formula crosses 0. To correct it can add the divisor back.
result += d2;
@@ -671,12 +732,12 @@ namespace System {
return result;
}
-
+
// Multiplies two Decimal values.
//
public static Decimal Multiply(Decimal d1, Decimal d2)
{
- FCallMultiply (ref d1, ref d2);
+ FCallMultiply(ref d1, ref d2);
return d1;
}
@@ -685,11 +746,12 @@ namespace System {
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallMultiply(ref Decimal d1, ref Decimal d2);
-
+
// Returns the negated value of the given Decimal. If d is non-zero,
// the result is -d. If d is zero, the result is zero.
//
- public static Decimal Negate(Decimal d) {
+ public static Decimal Negate(Decimal d)
+ {
return new Decimal(d.lo, d.mid, d.hi, d.flags ^ SignMask);
}
@@ -700,33 +762,39 @@ namespace System {
//
// By default a mid-point value is rounded to the nearest even number. If the mode is
// passed in, it can also round away from zero.
-
- public static Decimal Round(Decimal d) {
+
+ public static Decimal Round(Decimal d)
+ {
return Round(d, 0);
}
-
+
public static Decimal Round(Decimal d, int decimals)
{
- FCallRound (ref d, decimals);
+ FCallRound(ref d, decimals);
return d;
}
- public static Decimal Round(Decimal d, MidpointRounding mode) {
+ public static Decimal Round(Decimal d, MidpointRounding mode)
+ {
return Round(d, 0, mode);
}
- public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) {
+ public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
+ {
if ((decimals < 0) || (decimals > 28))
- throw new ArgumentOutOfRangeException(nameof(decimals), Environment.GetResourceString("ArgumentOutOfRange_DecimalRound"));
- if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, nameof(MidpointRounding)), nameof(mode));
+ throw new ArgumentOutOfRangeException(nameof(decimals), SR.ArgumentOutOfRange_DecimalRound);
+ if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
}
Contract.EndContractBlock();
- if (mode == MidpointRounding.ToEven) {
- FCallRound (ref d, decimals);
+ if (mode == MidpointRounding.ToEven)
+ {
+ FCallRound(ref d, decimals);
}
- else {
+ else
+ {
InternalRoundFromZero(ref d, decimals);
}
return d;
@@ -734,7 +802,7 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallRound(ref Decimal d, int decimals);
-
+
// Subtracts two Decimal values.
//
public static Decimal Subtract(Decimal d1, Decimal d2)
@@ -747,67 +815,75 @@ namespace System {
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
- public static byte ToByte(Decimal value) {
+ public static byte ToByte(Decimal value)
+ {
uint temp;
- try {
- temp = ToUInt32(value);
+ try
+ {
+ temp = ToUInt32(value);
}
- catch (OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Byte"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_Byte, e);
}
- if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Byte"));
+ if (temp < Byte.MinValue || temp > Byte.MaxValue) throw new OverflowException(SR.Overflow_Byte);
return (byte)temp;
-
}
-
+
// Converts a Decimal to a signed byte. The Decimal value is rounded
// towards zero to the nearest integer value, and the result of this
// operation is returned as a byte.
//
- [CLSCompliant(false)]
- public static sbyte ToSByte(Decimal value) {
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(Decimal value)
+ {
int temp;
- try {
- temp = ToInt32(value);
+ try
+ {
+ temp = ToInt32(value);
}
- catch (OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_SByte"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_SByte, e);
}
- if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_SByte"));
+ if (temp < SByte.MinValue || temp > SByte.MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)temp;
}
-
+
// Converts a Decimal to a short. The Decimal value is
// rounded towards zero to the nearest integer value, and the result of
// this operation is returned as a short.
//
- public static short ToInt16(Decimal value) {
+ public static short ToInt16(Decimal value)
+ {
int temp;
- try {
- temp = ToInt32(value);
+ try
+ {
+ temp = ToInt32(value);
}
- catch (OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int16"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_Int16, e);
}
- if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
+ if (temp < Int16.MinValue || temp > Int16.MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)temp;
}
-
-
+
+
// Converts a Decimal to a Currency. Since a Currency
// has fewer significant digits than a Decimal, this operation may
// produce round-off errors.
//
internal static Currency ToCurrency(Decimal d)
{
- Currency result = new Currency ();
- FCallToCurrency (ref result, d);
+ Currency result = new Currency();
+ FCallToCurrency(ref result, d);
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallToCurrency(ref Currency result, Decimal d);
-
+
// Converts a Decimal to a double. Since a double has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
@@ -816,92 +892,107 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int FCallToInt32(Decimal d);
-
+
// Converts a Decimal to an integer. The Decimal value is rounded towards
// zero to the nearest integer value, and the result of this operation is
// returned as an integer.
//
- public static int ToInt32(Decimal d) {
- if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
- if (d.hi == 0 && d.mid == 0) {
+ public static int ToInt32(Decimal d)
+ {
+ if ((d.flags & ScaleMask) != 0) FCallTruncate(ref d);
+ if (d.hi == 0 && d.mid == 0)
+ {
int i = d.lo;
- if (d.flags >= 0) {
+ if (d.flags >= 0)
+ {
if (i >= 0) return i;
}
- else {
+ else
+ {
i = -i;
if (i <= 0) return i;
}
}
- throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
+ throw new OverflowException(SR.Overflow_Int32);
}
-
+
// Converts a Decimal to a long. The Decimal value is rounded towards zero
// to the nearest integer value, and the result of this operation is
// returned as a long.
//
- public static long ToInt64(Decimal d) {
- if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
- if (d.hi == 0) {
+ public static long ToInt64(Decimal d)
+ {
+ if ((d.flags & ScaleMask) != 0) FCallTruncate(ref d);
+ if (d.hi == 0)
+ {
long l = d.lo & 0xFFFFFFFFL | (long)d.mid << 32;
- if (d.flags >= 0) {
+ if (d.flags >= 0)
+ {
if (l >= 0) return l;
}
- else {
+ else
+ {
l = -l;
if (l <= 0) return l;
}
}
- throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
+ throw new OverflowException(SR.Overflow_Int64);
}
-
+
// Converts a Decimal to an ushort. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an ushort.
//
- [CLSCompliant(false)]
- public static ushort ToUInt16(Decimal value) {
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(Decimal value)
+ {
uint temp;
- try {
- temp = ToUInt32(value);
+ try
+ {
+ temp = ToUInt32(value);
}
- catch (OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_UInt16, e);
}
- if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"));
+ if (temp < UInt16.MinValue || temp > UInt16.MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)temp;
}
-
+
// Converts a Decimal to an unsigned integer. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as an unsigned integer.
//
- [CLSCompliant(false)]
- public static uint ToUInt32(Decimal d) {
- if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
- if (d.hi == 0 && d.mid == 0) {
- uint i = (uint) d.lo;
- if (d.flags >= 0 || i == 0)
+ [CLSCompliant(false)]
+ public static uint ToUInt32(Decimal d)
+ {
+ if ((d.flags & ScaleMask) != 0) FCallTruncate(ref d);
+ if (d.hi == 0 && d.mid == 0)
+ {
+ uint i = (uint)d.lo;
+ if (d.flags >= 0 || i == 0)
return i;
}
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
+ throw new OverflowException(SR.Overflow_UInt32);
}
-
+
// Converts a Decimal to an unsigned long. The Decimal
// value is rounded towards zero to the nearest integer value, and the
// result of this operation is returned as a long.
//
- [CLSCompliant(false)]
- public static ulong ToUInt64(Decimal d) {
- if ((d.flags & ScaleMask) != 0) FCallTruncate (ref d);
- if (d.hi == 0) {
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(Decimal d)
+ {
+ if ((d.flags & ScaleMask) != 0) FCallTruncate(ref d);
+ if (d.hi == 0)
+ {
ulong l = ((ulong)(uint)d.lo) | ((ulong)(uint)d.mid << 32);
if (d.flags >= 0 || l == 0)
return l;
}
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt64"));
+ throw new OverflowException(SR.Overflow_UInt64);
}
-
+
// Converts a Decimal to a float. Since a float has fewer significant
// digits than a Decimal, this operation may produce round-off errors.
//
@@ -914,180 +1005,219 @@ namespace System {
//
public static Decimal Truncate(Decimal d)
{
- FCallTruncate (ref d);
+ FCallTruncate(ref d);
return d;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void FCallTruncate(ref Decimal d);
-
-
- public static implicit operator Decimal(byte value) {
+
+
+ public static implicit operator Decimal(byte value)
+ {
return new Decimal(value);
}
-
+
[CLSCompliant(false)]
- public static implicit operator Decimal(sbyte value) {
+ public static implicit operator Decimal(sbyte value)
+ {
return new Decimal(value);
}
-
- public static implicit operator Decimal(short value) {
+
+ public static implicit operator Decimal(short value)
+ {
return new Decimal(value);
}
-
+
[CLSCompliant(false)]
- public static implicit operator Decimal(ushort value) {
+ public static implicit operator Decimal(ushort value)
+ {
return new Decimal(value);
}
- public static implicit operator Decimal(char value) {
+ public static implicit operator Decimal(char value)
+ {
return new Decimal(value);
}
-
- public static implicit operator Decimal(int value) {
+
+ public static implicit operator Decimal(int value)
+ {
return new Decimal(value);
}
-
+
[CLSCompliant(false)]
- public static implicit operator Decimal(uint value) {
+ public static implicit operator Decimal(uint value)
+ {
return new Decimal(value);
}
-
- public static implicit operator Decimal(long value) {
+
+ public static implicit operator Decimal(long value)
+ {
return new Decimal(value);
}
-
+
[CLSCompliant(false)]
- public static implicit operator Decimal(ulong value) {
+ public static implicit operator Decimal(ulong value)
+ {
return new Decimal(value);
}
-
-
- public static explicit operator Decimal(float value) {
+
+
+ public static explicit operator Decimal(float value)
+ {
return new Decimal(value);
}
-
- public static explicit operator Decimal(double value) {
+
+ public static explicit operator Decimal(double value)
+ {
return new Decimal(value);
}
-
- public static explicit operator byte(Decimal value) {
+
+ public static explicit operator byte(Decimal value)
+ {
return ToByte(value);
}
-
+
[CLSCompliant(false)]
- public static explicit operator sbyte(Decimal value) {
+ public static explicit operator sbyte(Decimal value)
+ {
return ToSByte(value);
}
-
- public static explicit operator char(Decimal value) {
+
+ public static explicit operator char(Decimal value)
+ {
UInt16 temp;
- try {
+ try
+ {
temp = ToUInt16(value);
- }
- catch (OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Char"), e);
+ }
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_Char, e);
}
return (char)temp;
}
- public static explicit operator short(Decimal value) {
+ public static explicit operator short(Decimal value)
+ {
return ToInt16(value);
}
-
+
[CLSCompliant(false)]
- public static explicit operator ushort(Decimal value) {
+ public static explicit operator ushort(Decimal value)
+ {
return ToUInt16(value);
}
-
- public static explicit operator int(Decimal value) {
+
+ public static explicit operator int(Decimal value)
+ {
return ToInt32(value);
}
-
+
[CLSCompliant(false)]
- public static explicit operator uint(Decimal value) {
+ public static explicit operator uint(Decimal value)
+ {
return ToUInt32(value);
}
-
- public static explicit operator long(Decimal value) {
+
+ public static explicit operator long(Decimal value)
+ {
return ToInt64(value);
}
-
+
[CLSCompliant(false)]
- public static explicit operator ulong(Decimal value) {
+ public static explicit operator ulong(Decimal value)
+ {
return ToUInt64(value);
}
-
- public static explicit operator float(Decimal value) {
+
+ public static explicit operator float(Decimal value)
+ {
return ToSingle(value);
}
-
- public static explicit operator double(Decimal value) {
+
+ public static explicit operator double(Decimal value)
+ {
return ToDouble(value);
}
-
- public static Decimal operator +(Decimal d) {
+
+ public static Decimal operator +(Decimal d)
+ {
return d;
}
-
- public static Decimal operator -(Decimal d) {
+
+ public static Decimal operator -(Decimal d)
+ {
return Negate(d);
}
-
- public static Decimal operator ++(Decimal d) {
+
+ public static Decimal operator ++(Decimal d)
+ {
return Add(d, One);
}
-
- public static Decimal operator --(Decimal d) {
+
+ public static Decimal operator --(Decimal d)
+ {
return Subtract(d, One);
}
-
- public static Decimal operator +(Decimal d1, Decimal d2) {
+
+ public static Decimal operator +(Decimal d1, Decimal d2)
+ {
FCallAddSub(ref d1, ref d2, DECIMAL_ADD);
return d1;
}
-
- public static Decimal operator -(Decimal d1, Decimal d2) {
+
+ public static Decimal operator -(Decimal d1, Decimal d2)
+ {
FCallAddSub(ref d1, ref d2, DECIMAL_NEG);
return d1;
}
-
- public static Decimal operator *(Decimal d1, Decimal d2) {
- FCallMultiply (ref d1, ref d2);
+
+ public static Decimal operator *(Decimal d1, Decimal d2)
+ {
+ FCallMultiply(ref d1, ref d2);
return d1;
}
-
- public static Decimal operator /(Decimal d1, Decimal d2) {
- FCallDivide (ref d1, ref d2);
+
+ public static Decimal operator /(Decimal d1, Decimal d2)
+ {
+ FCallDivide(ref d1, ref d2);
return d1;
}
-
- public static Decimal operator %(Decimal d1, Decimal d2) {
+
+ public static Decimal operator %(Decimal d1, Decimal d2)
+ {
return Remainder(d1, d2);
}
-
- public static bool operator ==(Decimal d1, Decimal d2) {
+
+ public static bool operator ==(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) == 0;
}
- public static bool operator !=(Decimal d1, Decimal d2) {
+ public static bool operator !=(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) != 0;
}
- public static bool operator <(Decimal d1, Decimal d2) {
+ public static bool operator <(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) < 0;
}
- public static bool operator <=(Decimal d1, Decimal d2) {
+ public static bool operator <=(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) <= 0;
}
- public static bool operator >(Decimal d1, Decimal d2) {
+ public static bool operator >(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) > 0;
}
- public static bool operator >=(Decimal d1, Decimal d2) {
+ public static bool operator >=(Decimal d1, Decimal d2)
+ {
return FCallCompare(ref d1, ref d2) >= 0;
}
@@ -1095,83 +1225,84 @@ namespace System {
// IConvertible implementation
//
- public TypeCode GetTypeCode() {
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Decimal;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
- return Convert.ToBoolean(this);
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
+ return Convert.ToBoolean(this);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Decimal", "Char"));
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "Char"));
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(this);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(this);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(this);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(this);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(this);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(this);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(this);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(this);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(this);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(this);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return this;
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Decimal", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/DefaultBinder.CanConvert.cs b/src/mscorlib/src/System/DefaultBinder.CanConvert.cs
new file mode 100644
index 0000000000..09c7298a3d
--- /dev/null
+++ b/src/mscorlib/src/System/DefaultBinder.CanConvert.cs
@@ -0,0 +1,30 @@
+// 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.Runtime.CompilerServices;
+
+namespace System
+{
+ internal partial class DefaultBinder : Binder
+ {
+ // CanChangePrimitive
+ // This will determine if the source can be converted to the target type
+ private static bool CanChangePrimitive(Type source, Type target) => CanConvertPrimitive((RuntimeType)source, (RuntimeType)target);
+
+ // CanChangePrimitiveObjectToType
+ private static bool CanChangePrimitiveObjectToType(object source, Type type) => CanConvertPrimitiveObjectToType(source, (RuntimeType)type);
+
+ // CanConvertPrimitive
+ // This will determine if the source can be converted to the target type
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool CanConvertPrimitive(RuntimeType source, RuntimeType target);
+
+ // CanConvertPrimitiveObjectToType
+ // This method will determine if the primitive object can be converted
+ // to a type.
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ private static extern bool CanConvertPrimitiveObjectToType(object source, RuntimeType type);
+ }
+}
diff --git a/src/mscorlib/src/System/DefaultBinder.cs b/src/mscorlib/src/System/DefaultBinder.cs
deleted file mode 100644
index b4681c406d..0000000000
--- a/src/mscorlib/src/System/DefaultBinder.cs
+++ /dev/null
@@ -1,1162 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// This class represents the Default COM+ binder.
-//
-//
-namespace System {
-
- using System;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using CultureInfo = System.Globalization.CultureInfo;
- //Marked serializable even though it has no state.
- [Serializable]
- internal class DefaultBinder : Binder
- {
- // This method is passed a set of methods and must choose the best
- // fit. The methods all have the same number of arguments and the object
- // array args. On exit, this method will choice the best fit method
- // and coerce the args to match that method. By match, we mean all primitive
- // arguments are exact matchs and all object arguments are exact or subclasses
- // of the target. If the target OR is an interface, the object must implement
- // that interface. There are a couple of exceptions
- // thrown when a method cannot be returned. If no method matchs the args and
- // ArgumentException is thrown. If multiple methods match the args then
- // an AmbiguousMatchException is thrown.
- //
- // The most specific match will be selected.
- //
- public override MethodBase BindToMethod(
- BindingFlags bindingAttr, MethodBase[] match, ref Object[] args,
- ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, out Object state)
- {
- if (match == null || match.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
- Contract.EndContractBlock();
-
- MethodBase[] candidates = (MethodBase[]) match.Clone();
-
- int i;
- int j;
-
- state = null;
-
- #region Map named parameters to candidate parameter postions
- // 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
- // named parameters (names) may change the order. If names
- // is not provided, then we assume the default mapping (0,1,...)
- int[][] paramOrder = new int[candidates.Length][];
-
- for (i = 0; i < candidates.Length; i++)
- {
- ParameterInfo[] par = candidates[i].GetParametersNoCopy();
-
- // args.Length + 1 takes into account the possibility of a last paramArray that can be omitted
- paramOrder[i] = new int[(par.Length > args.Length) ? par.Length : args.Length];
-
- if (names == null)
- {
- // Default mapping
- for (j = 0; j < args.Length; j++)
- paramOrder[i][j] = j;
- }
- else
- {
- // Named parameters, reorder the mapping. If CreateParamOrder fails, it means that the method
- // doesn't have a name that matchs one of the named parameters so we don't consider it any further.
- if (!CreateParamOrder(paramOrder[i], par, names))
- candidates[i] = null;
- }
- }
- #endregion
-
- Type[] paramArrayTypes = new Type[candidates.Length];
-
- Type[] argTypes = new Type[args.Length];
-
- #region Cache the type of the provided arguments
- // object that contain a null are treated as if they were typeless (but match either object
- // references or value classes). We mark this condition by placing a null in the argTypes array.
- for (i = 0; i < args.Length; i++)
- {
- if (args[i] != null)
- {
- argTypes[i] = args[i].GetType();
- }
- }
- #endregion
-
-
- // Find the method that matches...
- int CurIdx = 0;
- bool defaultValueBinding = ((bindingAttr & BindingFlags.OptionalParamBinding) != 0);
-
- Type paramArrayType = null;
-
- #region Filter methods by parameter count and type
- for (i = 0; i < candidates.Length; i++)
- {
- paramArrayType = null;
-
- // If we have named parameters then we may have a hole in the candidates array.
- if (candidates[i] == null)
- continue;
-
- // Validate the parameters.
- ParameterInfo[] par = candidates[i].GetParametersNoCopy();
-
- #region Match method by parameter count
- if (par.Length == 0)
- {
- #region No formal parameters
- if (args.Length != 0)
- {
- if ((candidates[i].CallingConvention & CallingConventions.VarArgs) == 0)
- continue;
- }
-
- // This is a valid routine so we move it up the candidates list.
- paramOrder[CurIdx] = paramOrder[i];
- candidates[CurIdx++] = candidates[i];
-
- continue;
- #endregion
- }
- else if (par.Length > args.Length)
- {
- #region Shortage of provided parameters
- // If the number of parameters is greater than the number of args then
- // we are in the situation were we may be using default values.
- for (j = args.Length; j < par.Length - 1; j++)
- {
- if (par[j].DefaultValue == System.DBNull.Value)
- break;
- }
-
- if (j != par.Length - 1)
- continue;
-
- if (par[j].DefaultValue == System.DBNull.Value)
- {
- if (!par[j].ParameterType.IsArray)
- continue;
-
- if (!par[j].IsDefined(typeof(ParamArrayAttribute), true))
- continue;
-
- paramArrayType = par[j].ParameterType.GetElementType();
- }
- #endregion
- }
- else if (par.Length < args.Length)
- {
- #region Excess provided parameters
- // test for the ParamArray case
- int lastArgPos = par.Length - 1;
-
- if (!par[lastArgPos].ParameterType.IsArray)
- continue;
-
- if (!par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true))
- continue;
-
- if (paramOrder[i][lastArgPos] != lastArgPos)
- continue;
-
- paramArrayType = par[lastArgPos].ParameterType.GetElementType();
- #endregion
- }
- else
- {
- #region Test for paramArray, save paramArray type
- int lastArgPos = par.Length - 1;
-
- if (par[lastArgPos].ParameterType.IsArray
- && par[lastArgPos].IsDefined(typeof(ParamArrayAttribute), true)
- && paramOrder[i][lastArgPos] == lastArgPos)
- {
- if (!par[lastArgPos].ParameterType.IsAssignableFrom(argTypes[lastArgPos]))
- paramArrayType = par[lastArgPos].ParameterType.GetElementType();
- }
- #endregion
- }
- #endregion
-
- Type pCls = null;
- int argsToCheck = (paramArrayType != null) ? par.Length - 1 : args.Length;
-
- #region Match method by parameter type
- for (j = 0; j < argsToCheck; j++)
- {
- #region Classic argument coersion checks
- // get the formal type
- pCls = par[j].ParameterType;
-
- if (pCls.IsByRef)
- pCls = pCls.GetElementType();
-
- // the type is the same
- if (pCls == argTypes[paramOrder[i][j]])
- continue;
-
- // a default value is available
- if (defaultValueBinding && args[paramOrder[i][j]] == Type.Missing)
- continue;
-
- // the argument was null, so it matches with everything
- if (args[paramOrder[i][j]] == null)
- continue;
-
- // the type is Object, so it will match everything
- if (pCls == typeof(Object))
- continue;
-
- // now do a "classic" type check
- if (pCls.IsPrimitive)
- {
- if (argTypes[paramOrder[i][j]] == null || !CanConvertPrimitiveObjectToType(args[paramOrder[i][j]],(RuntimeType)pCls))
- {
- break;
- }
- }
- else
- {
- if (argTypes[paramOrder[i][j]] == null)
- continue;
-
- if (!pCls.IsAssignableFrom(argTypes[paramOrder[i][j]]))
- {
- if (argTypes[paramOrder[i][j]].IsCOMObject)
- {
- if (pCls.IsInstanceOfType(args[paramOrder[i][j]]))
- continue;
- }
- break;
- }
- }
- #endregion
- }
-
- if (paramArrayType != null && j == par.Length - 1)
- {
- #region Check that excess arguments can be placed in the param array
- for (; j < args.Length; j++)
- {
- if (paramArrayType.IsPrimitive)
- {
- if (argTypes[j] == null || !CanConvertPrimitiveObjectToType(args[j], (RuntimeType)paramArrayType))
- break;
- }
- else
- {
- if (argTypes[j] == null)
- continue;
-
- if (!paramArrayType.IsAssignableFrom(argTypes[j]))
- {
- if (argTypes[j].IsCOMObject)
- {
- if (paramArrayType.IsInstanceOfType(args[j]))
- continue;
- }
-
- break;
- }
- }
- }
- #endregion
- }
- #endregion
-
- if (j == args.Length)
- {
- #region This is a valid routine so we move it up the candidates list
- paramOrder[CurIdx] = paramOrder[i];
- paramArrayTypes[CurIdx] = paramArrayType;
- candidates[CurIdx++] = candidates[i];
- #endregion
- }
- }
- #endregion
-
- // If we didn't find a method
- if (CurIdx == 0)
- throw new MissingMethodException(Environment.GetResourceString("MissingMember"));
-
- if (CurIdx == 1)
- {
- #region Found only one method
- if (names != null)
- {
- state = new BinderState((int[])paramOrder[0].Clone(), args.Length, paramArrayTypes[0] != null);
- ReorderParams(paramOrder[0],args);
- }
-
- // If the parameters and the args are not the same length or there is a paramArray
- // then we need to create a argument array.
- ParameterInfo[] parms = candidates[0].GetParametersNoCopy();
-
- if (parms.Length == args.Length)
- {
- if (paramArrayTypes[0] != null)
- {
- Object[] objs = new Object[parms.Length];
- int lastPos = parms.Length - 1;
- Array.Copy(args, 0, objs, 0, lastPos);
- objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], 1);
- ((Array)objs[lastPos]).SetValue(args[lastPos], 0);
- args = objs;
- }
- }
- else if (parms.Length > args.Length)
- {
- Object[] objs = new Object[parms.Length];
-
- for (i=0;i<args.Length;i++)
- objs[i] = args[i];
-
- for (;i<parms.Length - 1;i++)
- objs[i] = parms[i].DefaultValue;
-
- if (paramArrayTypes[0] != null)
- objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[0], 0); // create an empty array for the
-
- else
- objs[i] = parms[i].DefaultValue;
-
- args = objs;
- }
- else
- {
- if ((candidates[0].CallingConvention & CallingConventions.VarArgs) == 0)
- {
- Object[] objs = new Object[parms.Length];
- int paramArrayPos = parms.Length - 1;
- Array.Copy(args, 0, objs, 0, paramArrayPos);
- objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[0], args.Length - paramArrayPos);
- Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
- args = objs;
- }
- }
- #endregion
-
- return candidates[0];
- }
-
- int currentMin = 0;
- bool ambig = false;
- for (i = 1; i < CurIdx; i++)
- {
- #region Walk all of the methods looking the most specific method to invoke
- int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder[currentMin], paramArrayTypes[currentMin],
- candidates[i], paramOrder[i], paramArrayTypes[i], argTypes, args);
-
- if (newMin == 0)
- {
- ambig = true;
- }
- else if (newMin == 2)
- {
- currentMin = i;
- ambig = false;
- }
- #endregion
- }
-
- if (ambig)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
-
- // Reorder (if needed)
- if (names != null) {
- state = new BinderState((int[])paramOrder[currentMin].Clone(), args.Length, paramArrayTypes[currentMin] != null);
- ReorderParams(paramOrder[currentMin], args);
- }
-
- // If the parameters and the args are not the same length or there is a paramArray
- // then we need to create a argument array.
- ParameterInfo[] parameters = candidates[currentMin].GetParametersNoCopy();
- if (parameters.Length == args.Length)
- {
- if (paramArrayTypes[currentMin] != null)
- {
- Object[] objs = new Object[parameters.Length];
- int lastPos = parameters.Length - 1;
- Array.Copy(args, 0, objs, 0, lastPos);
- objs[lastPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 1);
- ((Array)objs[lastPos]).SetValue(args[lastPos], 0);
- args = objs;
- }
- }
- else if (parameters.Length > args.Length)
- {
- Object[] objs = new Object[parameters.Length];
-
- for (i=0;i<args.Length;i++)
- objs[i] = args[i];
-
- for (;i<parameters.Length - 1;i++)
- objs[i] = parameters[i].DefaultValue;
-
- if (paramArrayTypes[currentMin] != null)
- {
- objs[i] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], 0);
- }
- else
- {
- objs[i] = parameters[i].DefaultValue;
- }
-
- args = objs;
- }
- else
- {
- if ((candidates[currentMin].CallingConvention & CallingConventions.VarArgs) == 0)
- {
- Object[] objs = new Object[parameters.Length];
- int paramArrayPos = parameters.Length - 1;
- Array.Copy(args, 0, objs, 0, paramArrayPos);
- objs[paramArrayPos] = Array.UnsafeCreateInstance(paramArrayTypes[currentMin], args.Length - paramArrayPos);
- Array.Copy(args, paramArrayPos, (System.Array)objs[paramArrayPos], 0, args.Length - paramArrayPos);
- args = objs;
- }
- }
-
- return candidates[currentMin];
- }
-
-
- // Given a set of fields that match the base criteria, select a field.
- // if value is null then we have no way to select a field
- public override FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match, Object value,CultureInfo cultureInfo)
- {
- if (match == null) {
- throw new ArgumentNullException(nameof(match));
- }
-
- int i;
- // Find the method that match...
- int CurIdx = 0;
-
- Type valueType = null;
-
- FieldInfo[] candidates = (FieldInfo[]) match.Clone();
-
- // If we are a FieldSet, then use the value's type to disambiguate
- if ((bindingAttr & BindingFlags.SetField) != 0) {
- valueType = value.GetType();
-
- for (i=0;i<candidates.Length;i++) {
- Type pCls = candidates[i].FieldType;
- if (pCls == valueType) {
- candidates[CurIdx++] = candidates[i];
- continue;
- }
- if (value == Empty.Value) {
- // the object passed in was null which would match any non primitive non value type
- if (pCls.IsClass) {
- candidates[CurIdx++] = candidates[i];
- continue;
- }
- }
- if (pCls == typeof(Object)) {
- candidates[CurIdx++] = candidates[i];
- continue;
- }
- if (pCls.IsPrimitive) {
- if (CanConvertPrimitiveObjectToType(value,(RuntimeType)pCls)) {
- candidates[CurIdx++] = candidates[i];
- continue;
- }
- }
- else {
- if (pCls.IsAssignableFrom(valueType)) {
- candidates[CurIdx++] = candidates[i];
- continue;
- }
- }
- }
- if (CurIdx == 0)
- throw new MissingFieldException(Environment.GetResourceString("MissingField"));
- if (CurIdx == 1)
- return candidates[0];
- }
-
- // Walk all of the methods looking the most specific method to invoke
- int currentMin = 0;
- bool ambig = false;
- for (i=1;i<CurIdx;i++) {
- int newMin = FindMostSpecificField(candidates[currentMin], candidates[i]);
- if (newMin == 0)
- ambig = true;
- else {
- if (newMin == 2) {
- currentMin = i;
- ambig = false;
- }
- }
- }
- if (ambig)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
- return candidates[currentMin];
- }
-
- // Given a set of methods that match the base criteria, select a method based
- // upon an array of types. This method should return null if no method matchs
- // the criteria.
- public override MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
- {
- int i;
- int j;
-
- Type[] realTypes = new Type[types.Length];
- for (i=0;i<types.Length;i++) {
- realTypes[i] = types[i].UnderlyingSystemType;
- if (!(realTypes[i] is RuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(types));
- }
- types = realTypes;
-
- // We don't automatically jump out on exact match.
- if (match == null || match.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
-
- MethodBase[] candidates = (MethodBase[]) match.Clone();
-
- // Find all the methods that can be described by the types parameter.
- // Remove all of them that cannot.
- int CurIdx = 0;
- for (i=0;i<candidates.Length;i++) {
- ParameterInfo[] par = candidates[i].GetParametersNoCopy();
- if (par.Length != types.Length)
- continue;
- for (j=0;j<types.Length;j++) {
- Type pCls = par[j].ParameterType;
- if (pCls == types[j])
- continue;
- if (pCls == typeof(Object))
- continue;
- if (pCls.IsPrimitive) {
- if (!(types[j].UnderlyingSystemType is RuntimeType) ||
- !CanConvertPrimitive((RuntimeType)types[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
- break;
- }
- else {
- if (!pCls.IsAssignableFrom(types[j]))
- break;
- }
- }
- if (j == types.Length)
- candidates[CurIdx++] = candidates[i];
- }
- if (CurIdx == 0)
- return null;
- if (CurIdx == 1)
- return candidates[0];
-
- // Walk all of the methods looking the most specific method to invoke
- int currentMin = 0;
- bool ambig = false;
- int[] paramOrder = new int[types.Length];
- for (i=0;i<types.Length;i++)
- paramOrder[i] = i;
- for (i=1;i<CurIdx;i++) {
- int newMin = FindMostSpecificMethod(candidates[currentMin], paramOrder, null, candidates[i], paramOrder, null, types, null);
- if (newMin == 0)
- ambig = true;
- else {
- if (newMin == 2) {
- currentMin = i;
- ambig = false;
- currentMin = i;
- }
- }
- }
- if (ambig)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
- return candidates[currentMin];
- }
-
- // Given a set of properties that match the base criteria, select one.
- public override PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,Type returnType,
- Type[] indexes,ParameterModifier[] modifiers)
- {
- // Allow a null indexes array. But if it is not null, every element must be non-null as well.
- if (indexes != null && !Contract.ForAll(indexes, delegate(Type t) { return t != null; }))
- {
- throw new ArgumentNullException(nameof(indexes));
- }
- if (match == null || match.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(match));
- Contract.EndContractBlock();
-
- PropertyInfo[] candidates = (PropertyInfo[]) match.Clone();
-
- int i,j = 0;
-
- // Find all the properties that can be described by type indexes parameter
- int CurIdx = 0;
- int indexesLength = (indexes != null) ? indexes.Length : 0;
- for (i=0;i<candidates.Length;i++) {
-
- if (indexes != null)
- {
- ParameterInfo[] par = candidates[i].GetIndexParameters();
- if (par.Length != indexesLength)
- continue;
-
- for (j=0;j<indexesLength;j++) {
- Type pCls = par[j]. ParameterType;
-
- // If the classes exactly match continue
- if (pCls == indexes[j])
- continue;
- if (pCls == typeof(Object))
- continue;
-
- if (pCls.IsPrimitive) {
- if (!(indexes[j].UnderlyingSystemType is RuntimeType) ||
- !CanConvertPrimitive((RuntimeType)indexes[j].UnderlyingSystemType,(RuntimeType)pCls.UnderlyingSystemType))
- break;
- }
- else {
- if (!pCls.IsAssignableFrom(indexes[j]))
- break;
- }
- }
- }
-
- if (j == indexesLength) {
- if (returnType != null) {
- if (candidates[i].PropertyType.IsPrimitive) {
- if (!(returnType.UnderlyingSystemType is RuntimeType) ||
- !CanConvertPrimitive((RuntimeType)returnType.UnderlyingSystemType,(RuntimeType)candidates[i].PropertyType.UnderlyingSystemType))
- continue;
- }
- else {
- if (!candidates[i].PropertyType.IsAssignableFrom(returnType))
- continue;
- }
- }
- candidates[CurIdx++] = candidates[i];
- }
- }
- if (CurIdx == 0)
- return null;
- if (CurIdx == 1)
- return candidates[0];
-
- // Walk all of the properties looking the most specific method to invoke
- int currentMin = 0;
- bool ambig = false;
- int[] paramOrder = new int[indexesLength];
- for (i=0;i<indexesLength;i++)
- paramOrder[i] = i;
- for (i=1;i<CurIdx;i++) {
- int newMin = FindMostSpecificType(candidates[currentMin].PropertyType, candidates[i].PropertyType,returnType);
- if (newMin == 0 && indexes != null)
- newMin = FindMostSpecific(candidates[currentMin].GetIndexParameters(),
- paramOrder,
- null,
- candidates[i].GetIndexParameters(),
- paramOrder,
- null,
- indexes,
- null);
- if (newMin == 0)
- {
- newMin = FindMostSpecificProperty(candidates[currentMin], candidates[i]);
- if (newMin == 0)
- ambig = true;
- }
- if (newMin == 2) {
- ambig = false;
- currentMin = i;
- }
- }
-
- if (ambig)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
- return candidates[currentMin];
- }
-
- // ChangeType
- // The default binder doesn't support any change type functionality.
- // This is because the default is built into the low level invoke code.
- public override Object ChangeType(Object value,Type type,CultureInfo cultureInfo)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ChangeType"));
- }
-
- public override void ReorderArgumentArray(ref Object[] args, Object state)
- {
- BinderState binderState = (BinderState)state;
- ReorderParams(binderState.m_argsMap, args);
- if (binderState.m_isParamArray) {
- int paramArrayPos = args.Length - 1;
- if (args.Length == binderState.m_originalSize)
- args[paramArrayPos] = ((Object[])args[paramArrayPos])[0];
- else {
- // must be args.Length < state.originalSize
- Object[] newArgs = new Object[args.Length];
- Array.Copy(args, 0, newArgs, 0, paramArrayPos);
- for (int i = paramArrayPos, j = 0; i < newArgs.Length; i++, j++) {
- newArgs[i] = ((Object[])args[paramArrayPos])[j];
- }
- args = newArgs;
- }
- }
- else {
- if (args.Length > binderState.m_originalSize) {
- Object[] newArgs = new Object[binderState.m_originalSize];
- Array.Copy(args, 0, newArgs, 0, binderState.m_originalSize);
- args = newArgs;
- }
- }
- }
-
- // Return any exact bindings that may exist. (This method is not defined on the
- // Binder and is used by RuntimeType.)
- public static MethodBase ExactBinding(MethodBase[] match,Type[] types,ParameterModifier[] modifiers)
- {
- if (match==null)
- throw new ArgumentNullException(nameof(match));
- Contract.EndContractBlock();
- MethodBase[] aExactMatches = new MethodBase[match.Length];
- int cExactMatches = 0;
-
- for (int i=0;i<match.Length;i++) {
- ParameterInfo[] par = match[i].GetParametersNoCopy();
- if (par.Length == 0) {
- continue;
- }
- int j;
- for (j=0;j<types.Length;j++) {
- Type pCls = par[j]. ParameterType;
-
- // If the classes exactly match continue
- if (!pCls.Equals(types[j]))
- break;
- }
- if (j < types.Length)
- continue;
-
- // Add the exact match to the array of exact matches.
- aExactMatches[cExactMatches] = match[i];
- cExactMatches++;
- }
-
- if (cExactMatches == 0)
- return null;
-
- if (cExactMatches == 1)
- return aExactMatches[0];
-
- return FindMostDerivedNewSlotMeth(aExactMatches, cExactMatches);
- }
-
- // Return any exact bindings that may exist. (This method is not defined on the
- // Binder and is used by RuntimeType.)
- public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match,Type returnType,Type[] types,ParameterModifier[] modifiers)
- {
- if (match==null)
- throw new ArgumentNullException(nameof(match));
- Contract.EndContractBlock();
-
- PropertyInfo bestMatch = null;
- int typesLength = (types != null) ? types.Length : 0;
- for (int i=0;i<match.Length;i++) {
- ParameterInfo[] par = match[i].GetIndexParameters();
- int j;
- for (j=0;j<typesLength;j++) {
- Type pCls = par[j].ParameterType;
-
- // If the classes exactly match continue
- if (pCls != types[j])
- break;
- }
- if (j < typesLength)
- continue;
- if (returnType != null && returnType != match[i].PropertyType)
- continue;
-
- if (bestMatch != null)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
-
- bestMatch = match[i];
- }
- return bestMatch;
- }
-
- private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1,
- ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2,
- Type[] types, Object[] args)
- {
- // A method using params is always less specific than one not using params
- if (paramArrayType1 != null && paramArrayType2 == null) return 2;
- if (paramArrayType2 != null && paramArrayType1 == null) return 1;
-
- // now either p1 and p2 both use params or neither does.
-
- bool p1Less = false;
- bool p2Less = false;
-
- for (int i = 0; i < types.Length; i++)
- {
- if (args != null && args[i] == Type.Missing)
- continue;
-
- Type c1, c2;
-
- // If a param array is present, then either
- // the user re-ordered the parameters in which case
- // the argument to the param array is either an array
- // in which case the params is conceptually ignored and so paramArrayType1 == null
- // or the argument to the param array is a single element
- // in which case paramOrder[i] == p1.Length - 1 for that element
- // or the user did not re-order the parameters in which case
- // the paramOrder array could contain indexes larger than p.Length - 1 (see VSW 577286)
- // so any index >= p.Length - 1 is being put in the param array
-
- if (paramArrayType1 != null && paramOrder1[i] >= p1.Length - 1)
- c1 = paramArrayType1;
- else
- c1 = p1[paramOrder1[i]].ParameterType;
-
- if (paramArrayType2 != null && paramOrder2[i] >= p2.Length - 1)
- c2 = paramArrayType2;
- else
- c2 = p2[paramOrder2[i]].ParameterType;
-
- if (c1 == c2) continue;
-
- switch (FindMostSpecificType(c1, c2, types[i])) {
- case 0: return 0;
- case 1: p1Less = true; break;
- case 2: p2Less = true; break;
- }
- }
-
- // Two way p1Less and p2Less can be equal. All the arguments are the
- // same they both equal false, otherwise there were things that both
- // were the most specific type on....
- if (p1Less == p2Less)
- {
- // if we cannot tell which is a better match based on parameter types (p1Less == p2Less),
- // let's see which one has the most matches without using the params array (the longer one wins).
- if (!p1Less && args != null)
- {
- if (p1.Length > p2.Length)
- {
- return 1;
- }
- else if (p2.Length > p1.Length)
- {
- return 2;
- }
- }
-
- return 0;
- }
- else
- {
- return (p1Less == true) ? 1 : 2;
- }
- }
-
- private static int FindMostSpecificType(Type c1, Type c2, Type t)
- {
- // If the two types are exact move on...
- if (c1 == c2)
- return 0;
-
- if (c1 == t)
- return 1;
-
- if (c2 == t)
- return 2;
-
- bool c1FromC2;
- bool c2FromC1;
-
- if (c1.IsByRef || c2.IsByRef)
- {
- if (c1.IsByRef && c2.IsByRef)
- {
- c1 = c1.GetElementType();
- c2 = c2.GetElementType();
- }
- else if (c1.IsByRef)
- {
- if (c1.GetElementType() == c2)
- return 2;
-
- c1 = c1.GetElementType();
- }
- else
- {
- if (c2.GetElementType() == c1)
- return 1;
-
- c2 = c2.GetElementType();
- }
- }
-
-
- if (c1.IsPrimitive && c2.IsPrimitive)
- {
- c1FromC2 = CanConvertPrimitive((RuntimeType)c2, (RuntimeType)c1);
- c2FromC1 = CanConvertPrimitive((RuntimeType)c1, (RuntimeType)c2);
- }
- else
- {
- c1FromC2 = c1.IsAssignableFrom(c2);
- c2FromC1 = c2.IsAssignableFrom(c1);
- }
-
- if (c1FromC2 == c2FromC1)
- return 0;
-
- if (c1FromC2)
- {
- return 2;
- }
- else
- {
- return 1;
- }
- }
-
- private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1,
- MethodBase m2, int[] paramOrder2, Type paramArrayType2,
- Type[] types, Object[] args)
- {
- // Find the most specific method based on the parameters.
- int res = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1,
- m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args);
-
- // If the match was not ambigous then return the result.
- if (res != 0)
- return res;
-
- // Check to see if the methods have the exact same name and signature.
- if (CompareMethodSigAndName(m1, m2))
- {
- // Determine the depth of the declaring types for both methods.
- int hierarchyDepth1 = GetHierarchyDepth(m1.DeclaringType);
- int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType);
-
- // The most derived method is the most specific one.
- if (hierarchyDepth1 == hierarchyDepth2)
- {
- return 0;
- }
- else if (hierarchyDepth1 < hierarchyDepth2)
- {
- return 2;
- }
- else
- {
- return 1;
- }
- }
-
- // The match is ambigous.
- return 0;
- }
-
- private static int FindMostSpecificField(FieldInfo cur1,FieldInfo cur2)
- {
- // Check to see if the fields have the same name.
- if (cur1.Name == cur2.Name)
- {
- int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
- int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
-
- if (hierarchyDepth1 == hierarchyDepth2) {
- Debug.Assert(cur1.IsStatic != cur2.IsStatic, "hierarchyDepth1 == hierarchyDepth2");
- return 0;
- }
- else if (hierarchyDepth1 < hierarchyDepth2)
- return 2;
- else
- return 1;
- }
-
- // The match is ambigous.
- return 0;
- }
-
- private static int FindMostSpecificProperty(PropertyInfo cur1,PropertyInfo cur2)
- {
- // Check to see if the fields have the same name.
- if (cur1.Name == cur2.Name)
- {
- int hierarchyDepth1 = GetHierarchyDepth(cur1.DeclaringType);
- int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType);
-
- if (hierarchyDepth1 == hierarchyDepth2) {
- return 0;
- }
- else if (hierarchyDepth1 < hierarchyDepth2)
- return 2;
- else
- return 1;
- }
-
- // The match is ambigous.
- return 0;
- }
-
- internal static bool CompareMethodSigAndName(MethodBase m1, MethodBase m2)
- {
- ParameterInfo[] params1 = m1.GetParametersNoCopy();
- ParameterInfo[] params2 = m2.GetParametersNoCopy();
-
- if (params1.Length != params2.Length)
- return false;
-
- int numParams = params1.Length;
- for (int i = 0; i < numParams; i++)
- {
- if (params1[i].ParameterType != params2[i].ParameterType)
- return false;
- }
-
- return true;
- }
-
- internal static int GetHierarchyDepth(Type t)
- {
- int depth = 0;
-
- Type currentType = t;
- do
- {
- depth++;
- currentType = currentType.BaseType;
- } while (currentType != null);
-
- return depth;
- }
-
- internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches)
- {
- int deepestHierarchy = 0;
- MethodBase methWithDeepestHierarchy = null;
-
- for (int i = 0; i < cMatches; i++)
- {
- // Calculate the depth of the hierarchy of the declaring type of the
- // current method.
- int currentHierarchyDepth = GetHierarchyDepth(match[i].DeclaringType);
-
- // The two methods have the same name, signature, and hierarchy depth.
- // This can only happen if at least one is vararg or generic.
- if (currentHierarchyDepth == deepestHierarchy)
- {
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
- }
-
- // Check to see if this method is on the most derived class.
- if (currentHierarchyDepth > deepestHierarchy)
- {
- deepestHierarchy = currentHierarchyDepth;
- methWithDeepestHierarchy = match[i];
- }
- }
-
- return methWithDeepestHierarchy;
- }
-
- // CanConvertPrimitive
- // This will determine if the source can be converted to the target type
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool CanConvertPrimitive(RuntimeType source,RuntimeType target);
-
- // CanConvertPrimitiveObjectToType
- // This method will determine if the primitive object can be converted
- // to a type.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern bool CanConvertPrimitiveObjectToType(Object source,RuntimeType type);
-
- // This method will sort the vars array into the mapping order stored
- // in the paramOrder array.
- private static void ReorderParams(int[] paramOrder,Object[] vars)
- {
- object[] varsCopy = new object[vars.Length];
- for (int i = 0; i < vars.Length; i ++)
- varsCopy[i] = vars[i];
-
- for (int i = 0; i < vars.Length; i ++)
- vars[i] = varsCopy[paramOrder[i]];
- }
-
- // This method will create the mapping between the Parameters and the underlying
- // data based upon the names array. The names array is stored in the same order
- // as the values and maps to the parameters of the method. We store the mapping
- // from the parameters to the names in the paramOrder array. All parameters that
- // don't have matching names are then stored in the array in order.
- private static bool CreateParamOrder(int[] paramOrder,ParameterInfo[] pars,String[] names)
- {
- bool[] used = new bool[pars.Length];
-
- // Mark which parameters have not been found in the names list
- for (int i=0;i<pars.Length;i++)
- paramOrder[i] = -1;
- // Find the parameters with names.
- for (int i=0;i<names.Length;i++) {
- int j;
- for (j=0;j<pars.Length;j++) {
- if (names[i].Equals(pars[j].Name)) {
- paramOrder[j] = i;
- used[i] = true;
- break;
- }
- }
- // This is an error condition. The name was not found. This
- // method must not match what we sent.
- if (j == pars.Length)
- return false;
- }
-
- // Now we fill in the holes with the parameters that are unused.
- int pos = 0;
- for (int i=0;i<pars.Length;i++) {
- if (paramOrder[i] == -1) {
- for (;pos<pars.Length;pos++) {
- if (!used[pos]) {
- paramOrder[i] = pos;
- pos++;
- break;
- }
- }
- }
- }
- return true;
- }
-
- internal class BinderState {
- internal int[] m_argsMap;
- internal int m_originalSize;
- internal bool m_isParamArray;
-
- internal BinderState(int[] argsMap, int originalSize, bool isParamArray) {
- m_argsMap = argsMap;
- m_originalSize = originalSize;
- m_isParamArray = isParamArray;
- }
-
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Delegate.cs b/src/mscorlib/src/System/Delegate.cs
index fb9dc4b110..de0ff6532c 100644
--- a/src/mscorlib/src/System/Delegate.cs
+++ b/src/mscorlib/src/System/Delegate.cs
@@ -2,8 +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.
-namespace System {
-
+namespace System
+{
using System;
using System.Reflection;
using System.Runtime;
@@ -18,7 +18,7 @@ namespace System {
[Serializable]
[ClassInterface(ClassInterfaceType.AutoDual)]
[System.Runtime.InteropServices.ComVisible(true)]
- public abstract class Delegate : ICloneable, ISerializable
+ public abstract class Delegate : ICloneable, ISerializable
{
// _target is the object we will invoke on
internal Object _target;
@@ -30,7 +30,7 @@ namespace System {
// _methodPtr is a pointer to the method we will invoke
// It could be a small thunk if this is a static or UM call
internal IntPtr _methodPtr;
-
+
// In the case of a static method passed to a delegate, this field stores
// whatever _methodPtr would have stored: and _methodPtr points to a
// small thunk which removes the "this" pointer before going on
@@ -39,15 +39,15 @@ namespace System {
// This constructor is called from the class generated by the
// compiler generated code
- protected Delegate(Object target,String method)
+ protected Delegate(Object target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
-
+
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
-
+
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodName to
// such and don't allow relaxed signature matching (which could make
@@ -57,19 +57,19 @@ namespace System {
if (!BindToMethodName(target, (RuntimeType)target.GetType(), method,
DelegateBindingFlags.InstanceMethodOnly |
DelegateBindingFlags.ClosedDelegateOnly))
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
-
+
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
- protected unsafe Delegate(Type target,String method)
+ protected unsafe Delegate(Type target, String method)
{
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
+ throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
@@ -77,7 +77,7 @@ namespace System {
RuntimeType rtTarget = target as RuntimeType;
if (rtTarget == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
// This API existed in v1/v1.1 and only expected to create open
// static delegates. Constrain the call to BindToMethodName to such
@@ -91,7 +91,7 @@ namespace System {
DelegateBindingFlags.OpenDelegateOnly |
DelegateBindingFlags.CaselessMatching);
}
-
+
// Protect the default constructor so you can't build a delegate
private Delegate()
{
@@ -108,7 +108,7 @@ namespace System {
return DynamicInvokeImpl(args);
}
- protected virtual object DynamicInvokeImpl(object[] args)
+ protected virtual object DynamicInvokeImpl(object[] args)
{
RuntimeMethodHandleInternal method = new RuntimeMethodHandleInternal(GetInvokeMethod());
RuntimeMethodInfo invoke = (RuntimeMethodInfo)RuntimeType.GetMethodBase((RuntimeType)this.GetType(), method);
@@ -116,16 +116,16 @@ namespace System {
return invoke.UnsafeInvoke(this, BindingFlags.Default, null, args, null);
}
-
+
public override bool Equals(Object obj)
- {
+ {
if (obj == null || !InternalEqualTypes(this, obj))
- return false;
+ return false;
- Delegate d = (Delegate) obj;
+ Delegate d = (Delegate)obj;
// do an optimistic check first. This is hopefully cheap enough to be worth
- if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
+ if (_target == d._target && _methodPtr == d._methodPtr && _methodPtrAux == d._methodPtrAux)
return true;
// even though the fields were not all equals the delegates may still match
@@ -154,7 +154,7 @@ namespace System {
return false;
*/
- if (_methodPtrAux == d._methodPtrAux)
+ if (_methodPtrAux == d._methodPtrAux)
return true;
// fall through method handle check
}
@@ -163,9 +163,8 @@ namespace System {
//
if (_methodBase == null || d._methodBase == null || !(_methodBase is MethodInfo) || !(d._methodBase is MethodInfo))
return Delegate.InternalEqualMethodHandles(this, d);
- else
+ else
return _methodBase.Equals(d._methodBase);
-
}
public override int GetHashCode()
@@ -188,37 +187,37 @@ namespace System {
if ((Object)a == null) // cast to object for a more efficient test
return b;
- return a.CombineImpl(b);
+ return a.CombineImpl(b);
}
-
+
public static Delegate Combine(params Delegate[] delegates)
{
if (delegates == null || delegates.Length == 0)
return null;
-
+
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
- d = Combine(d,delegates[i]);
-
+ d = Combine(d, delegates[i]);
+
return d;
}
-
+
public virtual Delegate[] GetInvocationList()
{
Delegate[] d = new Delegate[1];
d[0] = this;
return d;
}
-
+
// This routine will return the method
public MethodInfo Method
- {
- get
- {
+ {
+ get
+ {
return GetMethodImpl();
}
}
-
+
protected virtual MethodInfo GetMethodImpl()
{
if ((_methodBase == null) || !(_methodBase is MethodInfo))
@@ -226,12 +225,12 @@ namespace System {
IRuntimeMethodInfo method = FindMethodHandle();
RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(method);
// need a proper declaring type instance method on a generic type
- if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
+ if (RuntimeTypeHandle.IsGenericTypeDefinition(declaringType) || RuntimeTypeHandle.HasInstantiation(declaringType))
{
bool isStatic = (RuntimeMethodHandle.GetAttributes(method) & MethodAttributes.Static) != (MethodAttributes)0;
- if (!isStatic)
+ if (!isStatic)
{
- if (_methodPtrAux == (IntPtr)0)
+ if (_methodPtrAux == (IntPtr)0)
{
// The target may be of a derived type that doesn't have visibility onto the
// target method. We don't want to call RuntimeType.GetMethodBase below with that
@@ -271,9 +270,9 @@ namespace System {
}
_methodBase = (MethodInfo)RuntimeType.GetMethodBase(declaringType, method);
}
- return (MethodInfo)_methodBase;
+ return (MethodInfo)_methodBase;
}
-
+
public Object Target
{
get
@@ -281,19 +280,19 @@ namespace System {
return GetTarget();
}
}
-
-
+
+
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
-
+
if (value == null)
return source;
-
+
if (!InternalEqualTypes(source, value))
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis"));
-
+ throw new ArgumentException(SR.Arg_DlgtTypeMis);
+
return source.RemoveImpl(value);
}
@@ -302,7 +301,7 @@ namespace System {
Delegate newDelegate = null;
do
- {
+ {
newDelegate = source;
source = Remove(source, value);
}
@@ -310,29 +309,29 @@ namespace System {
return newDelegate;
}
-
- protected virtual Delegate CombineImpl(Delegate d)
+
+ protected virtual Delegate CombineImpl(Delegate d)
{
- throw new MulticastNotSupportedException(Environment.GetResourceString("Multicast_Combine"));
+ throw new MulticastNotSupportedException(SR.Multicast_Combine);
}
-
+
protected virtual Delegate RemoveImpl(Delegate d)
{
return (d.Equals(this)) ? null : this;
}
-
-
+
+
public virtual Object Clone()
{
return MemberwiseClone();
}
-
+
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
-
+
// V1 API.
public static Delegate CreateDelegate(Type type, Object target, String method, bool ignoreCase)
{
@@ -352,9 +351,9 @@ namespace System {
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create closed
@@ -371,19 +370,19 @@ namespace System {
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
-
+
return d;
}
-
+
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method)
{
return CreateDelegate(type, target, method, false, true);
}
-
+
// V1 API.
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase)
{
@@ -394,11 +393,11 @@ namespace System {
public static Delegate CreateDelegate(Type type, Type target, String method, bool ignoreCase, bool throwOnBindFailure)
{
if (type == null)
- throw new ArgumentNullException(nameof(type));
+ throw new ArgumentNullException(nameof(type));
if (target == null)
throw new ArgumentNullException(nameof(target));
if (target.IsGenericType && target.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), nameof(target));
+ throw new ArgumentException(SR.Arg_UnboundGenParam, nameof(target));
if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
@@ -406,11 +405,11 @@ namespace System {
RuntimeType rtType = type as RuntimeType;
RuntimeType rtTarget = target as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
if (rtTarget == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(target));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(target));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),nameof(type));
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
Delegate d = InternalAlloc(rtType);
// This API existed in v1/v1.1 and only expected to create open
@@ -423,15 +422,15 @@ namespace System {
(ignoreCase ? DelegateBindingFlags.CaselessMatching : 0)))
{
if (throwOnBindFailure)
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
d = null;
}
-
+
return d;
}
-
+
// V1 API.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
@@ -443,14 +442,14 @@ namespace System {
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
@@ -469,11 +468,11 @@ namespace System {
ref stackMark);
if (d == null && throwOnBindFailure)
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
-
+
// V2 API.
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method)
{
@@ -481,7 +480,7 @@ namespace System {
}
// V2 API.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)
{
// Validate the parameters.
@@ -493,14 +492,14 @@ namespace System {
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
RuntimeMethodInfo rmi = method as RuntimeMethodInfo;
if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
@@ -516,7 +515,7 @@ namespace System {
ref stackMark);
if (d == null && throwOnBindFailure)
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
@@ -525,18 +524,18 @@ namespace System {
{
if ((Object)d1 == null)
return (Object)d2 == null;
-
+
return d1.Equals(d2);
}
-
- public static bool operator != (Delegate d1, Delegate d2)
+
+ public static bool operator !=(Delegate d1, Delegate d2)
{
if ((Object)d1 == null)
return (Object)d2 != null;
-
+
return !d1.Equals(d2);
}
-
+
//
// Implementation of ISerializable
//
@@ -563,11 +562,11 @@ namespace System {
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(type));
-
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(type));
+
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
-
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
+
// Initialize the method...
Delegate d = InternalAlloc(rtType);
// This is a new internal API added in Whidbey. Currently it's only
@@ -579,7 +578,7 @@ namespace System {
method.GetMethodInfo(),
RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()),
DelegateBindingFlags.RelaxedSignature | DelegateBindingFlags.SkipSecurityChecks))
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
@@ -596,11 +595,11 @@ namespace System {
RuntimeMethodInfo rtMethod = method as RuntimeMethodInfo;
if (rtMethod == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(method));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(method));
if (!type.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(type));
-
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(type));
+
// This API is used by the formatters when deserializing a delegate.
// They pass us the specific target method (that was already the
// target in a valid delegate) so we should bind with the most
@@ -614,7 +613,7 @@ namespace System {
DelegateBindingFlags.RelaxedSignature);
if (d == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
return d;
}
@@ -629,19 +628,6 @@ namespace System {
{
Debug.Assert((flags & DelegateBindingFlags.SkipSecurityChecks) == 0);
-#if FEATURE_APPX
- bool nonW8PMethod = (rtMethod.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
- bool nonW8PType = (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0;
- if (nonW8PMethod || nonW8PType)
- {
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(
- Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext",
- nonW8PMethod ? rtMethod.FullName : rtType.FullName));
- }
-#endif
-
return UnsafeCreateDelegate(rtType, rtMethod, firstArgument, flags);
}
@@ -661,13 +647,13 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodName(Object target, RuntimeType methodType, String method, DelegateBindingFlags flags);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool BindToMethodInfo(Object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static MulticastDelegate InternalAlloc(RuntimeType type);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static MulticastDelegate InternalAllocLike(Delegate d);
@@ -703,20 +689,20 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static bool CompareUnmanagedFunctionPtrs (Delegate d1, Delegate d2);
+ internal extern static bool CompareUnmanagedFunctionPtrs(Delegate d1, Delegate d2);
}
// These flags effect the way BindToMethodInfo and BindToMethodName are allowed to bind a delegate to a target method. Their
// values must be kept in sync with the definition in vm\comdelegate.h.
internal enum DelegateBindingFlags
{
- StaticMethodOnly = 0x00000001, // Can only bind to static target methods
- InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
- OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
- ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
- NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
- CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
- SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
- RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
+ StaticMethodOnly = 0x00000001, // Can only bind to static target methods
+ InstanceMethodOnly = 0x00000002, // Can only bind to instance (including virtual) methods
+ OpenDelegateOnly = 0x00000004, // Only allow the creation of delegates open over the 1st argument
+ ClosedDelegateOnly = 0x00000008, // Only allow the creation of delegates closed over the 1st argument
+ NeverCloseOverNull = 0x00000010, // A null target will never been considered as a possible null 1st argument
+ CaselessMatching = 0x00000020, // Use case insensitive lookup for methods matched by name
+ SkipSecurityChecks = 0x00000040, // Skip security checks (visibility, link demand etc.)
+ RelaxedSignature = 0x00000080, // Allow relaxed signature matching (co/contra variance)
}
}
diff --git a/src/mscorlib/src/System/DelegateSerializationHolder.cs b/src/mscorlib/src/System/DelegateSerializationHolder.cs
index 061f92d42e..d7ad827673 100644
--- a/src/mscorlib/src/System/DelegateSerializationHolder.cs
+++ b/src/mscorlib/src/System/DelegateSerializationHolder.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.
-
+
using System;
using System.Reflection;
using System.Runtime.Remoting;
@@ -21,17 +21,17 @@ namespace System
{
// Used for MulticastDelegate
- if (method == null)
+ if (method == null)
throw new ArgumentNullException(nameof(method));
Contract.EndContractBlock();
-
+
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
+ throw new ArgumentException(SR.Arg_MustBeDelegate, "type");
if (method.DeclaringType == null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
+ throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization);
DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
@@ -39,7 +39,7 @@ namespace System
if (info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
- info.AddValue("Delegate",de,typeof(DelegateEntry));
+ info.AddValue("Delegate", de, typeof(DelegateEntry));
}
// target can be an object so it needs to be added to the info, or else a fixup is needed
@@ -108,15 +108,15 @@ namespace System
#region Private Data Members
private DelegateEntry m_delegateEntry;
private MethodInfo[] m_methods;
- #endregion
-
+ #endregion
+
#region Constructor
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
-
+
bool bNewWire = true;
try
@@ -170,7 +170,7 @@ namespace System
private void ThrowInsufficientState(string field)
{
throw new SerializationException(
- Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
+ SR.Format(SR.Serialization_InsufficientDeserializationState, field));
}
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
@@ -206,26 +206,34 @@ namespace System
// We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
- RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
+
+ // {de.targetTypeAssembly, de.targetTypeName} do not actually refer to the type of the target, but the reflected
+ // type of the method. Those types may be the same when the method is on the target's type or on a type in its
+ // inheritance chain, but those types may not be the same when the method is an extension method for the
+ // target's type or a type in its inheritance chain.
// If we received the new style delegate encoding we already have the target MethodInfo in hand.
if (m_methods != null)
{
- if(de.target != null && !targetType.IsInstanceOfType(de.target))
- throw new InvalidCastException();
- Object target=de.target;
- d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
+ // The method info is serialized, so the target type info is redundant. The desktop framework does no
+ // additional verification on the target type info.
+ d = Delegate.CreateDelegateNoSecurityCheck(type, de.target, m_methods[index]);
}
else
{
if (de.target != null)
{
- if(!targetType.IsInstanceOfType(de.target))
- throw new InvalidCastException();
- d = Delegate.CreateDelegate(type, de.target, de.methodName);
+ // For consistency with the desktop framework, when the method info is not serialized for a closed
+ // delegate, the method is assumed to be on the target's type or in its inheritance chain. An extension
+ // method would not work on this path for the above reason and also because the delegate binds to
+ // instance methods only. The desktop framework does no additional verification on the target type info.
+ d = Delegate.CreateDelegate(type, de.target, de.methodName);
}
else
+ {
+ RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
d = Delegate.CreateDelegate(type, targetType, de.methodName);
+ }
}
}
catch (Exception e)
@@ -256,7 +264,7 @@ namespace System
else
{
object[] invocationList = new object[count];
-
+
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
{
// Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
@@ -272,7 +280,7 @@ namespace System
#region ISerializable
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
+ throw new NotSupportedException(SR.NotSupported_DelegateSerHolderSerial);
}
#endregion
}
diff --git a/src/mscorlib/src/System/Diagnostics/Assert.cs b/src/mscorlib/src/System/Diagnostics/Assert.cs
index 9f4b86b7e4..67e6914aa4 100644
--- a/src/mscorlib/src/System/Diagnostics/Assert.cs
+++ b/src/mscorlib/src/System/Diagnostics/Assert.cs
@@ -2,36 +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.
-namespace System.Diagnostics {
- using System;
- using System.IO;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
- using System.Diagnostics.CodeAnalysis;
+using System;
+using System.IO;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+using System.Diagnostics.CodeAnalysis;
+namespace System.Diagnostics
+{
// Class which handles code asserts. Asserts are used to explicitly protect
// assumptions made in the code. In general if an assert fails, it indicates
// a program bug so is immediately called to the attention of the user.
// Only static data members, does not need to be marked with the serializable attribute
internal static class Assert
{
- internal const int COR_E_FAILFAST = unchecked((int) 0x80131623);
+ internal const int COR_E_FAILFAST = unchecked((int)0x80131623);
private static AssertFilter Filter;
static Assert()
{
Filter = new DefaultFilter();
}
-
+
// Called when an assertion is being made.
//
internal static void Check(bool condition, String conditionString, String message)
{
if (!condition)
{
- Fail (conditionString, message, null, COR_E_FAILFAST);
+ Fail(conditionString, message, null, COR_E_FAILFAST);
}
}
@@ -54,9 +55,9 @@ namespace System.Diagnostics {
{
// get the stacktrace
StackTrace st = new StackTrace(numStackFramesToSkip, true);
-
- AssertFilters iResult = Filter.AssertFailure (conditionString, message, st, stackTraceFormat, windowTitle);
-
+
+ AssertFilters iResult = Filter.AssertFailure(conditionString, message, st, stackTraceFormat, windowTitle);
+
if (iResult == AssertFilters.FailDebug)
{
if (Debugger.IsAttached == true)
@@ -66,9 +67,9 @@ namespace System.Diagnostics {
if (Debugger.Launch() == false)
{
throw new InvalidOperationException(
- Environment.GetResourceString("InvalidOperation_DebuggerLaunchFailed"));
- }
- }
+ SR.InvalidOperation_DebuggerLaunchFailed);
+ }
+ }
}
else if (iResult == AssertFilters.FailTerminate)
{
@@ -78,10 +79,10 @@ namespace System.Diagnostics {
Environment._Exit(exitCode);
}
}
-
- // Called when an assert happens.
- // windowTitle can be null.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static int ShowDefaultAssertDialog(String conditionString, String message, String stackTrace, String windowTitle);
+
+ // Called when an assert happens.
+ // windowTitle can be null.
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal extern static int ShowDefaultAssertDialog(String conditionString, String message, String stackTrace, String windowTitle);
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
index ab60ee4cff..7c861de58e 100644
--- a/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
+++ b/src/mscorlib/src/System/Diagnostics/AssertFilter.cs
@@ -2,29 +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.
-namespace System.Diagnostics {
-
-
- using System;
- using System.Runtime.Versioning;
- // A Filter is used to decide whether an assert failure
- // should terminate the program (or invoke the debugger).
- // Typically this is done by popping up a dialog & asking the user.
- //
- // The default filter brings up a simple Win32 dialog with 3 buttons.
-
+
+
+using System;
+using System.Runtime.Versioning;
+
+namespace System.Diagnostics
+{
+ // A Filter is used to decide whether an assert failure
+ // should terminate the program (or invoke the debugger).
+ // Typically this is done by popping up a dialog & asking the user.
+ //
+ // The default filter brings up a simple Win32 dialog with 3 buttons.
+
[Serializable]
abstract internal class AssertFilter
{
-
// Called when an assert fails. This should be overridden with logic which
// determines whether the program should terminate or not. Typically this
// is done by asking the user.
//
// The windowTitle can be null.
- abstract public AssertFilters AssertFailure(String condition, String message,
+ abstract public AssertFilters AssertFailure(String condition, String message,
StackTrace location, StackTrace.TraceFormat stackTraceFormat, String windowTitle);
-
}
// No data, does not need to be marked with the serializable attribute
internal class DefaultFilter : AssertFilter
@@ -32,14 +32,13 @@ namespace System.Diagnostics {
internal DefaultFilter()
{
}
-
- public override AssertFilters AssertFailure(String condition, String message,
+
+ public override AssertFilters AssertFailure(String condition, String message,
StackTrace location, StackTrace.TraceFormat stackTraceFormat,
String windowTitle)
-
+
{
- return (AssertFilters) Assert.ShowDefaultAssertDialog (condition, message, location.ToString(stackTraceFormat), windowTitle);
+ return (AssertFilters)Assert.ShowDefaultAssertDialog(condition, message, location.ToString(stackTraceFormat), windowTitle);
}
}
-
}
diff --git a/src/mscorlib/src/System/Diagnostics/AssertFilters.cs b/src/mscorlib/src/System/Diagnostics/AssertFilters.cs
index 13131d4819..0f34b41dba 100644
--- a/src/mscorlib/src/System/Diagnostics/AssertFilters.cs
+++ b/src/mscorlib/src/System/Diagnostics/AssertFilters.cs
@@ -2,23 +2,26 @@
// 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.Diagnostics {
-
- /*
- * FailDebug indicates the debugger should be invoked
- * FailIgnore indicates the failure should be ignored & the
- * program continued
- * FailTerminate indicates that the program should be terminated
- * FailContinue indicates that no decision is made -
- * the previous Filter should be invoked
- */
- using System;
+
+/*
+ * FailDebug indicates the debugger should be invoked
+ * FailIgnore indicates the failure should be ignored & the
+ * program continued
+ * FailTerminate indicates that the program should be terminated
+ * FailContinue indicates that no decision is made -
+ * the previous Filter should be invoked
+ */
+
+using System;
+
+namespace System.Diagnostics
+{
[Serializable]
internal enum AssertFilters
{
- FailDebug = 0,
- FailIgnore = 1,
- FailTerminate = 2,
- FailContinueFilter = 3,
+ FailDebug = 0,
+ FailIgnore = 1,
+ FailTerminate = 2,
+ FailContinueFilter = 3,
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs b/src/mscorlib/src/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs
deleted file mode 100644
index fb26fcc4ab..0000000000
--- a/src/mscorlib/src/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs
+++ /dev/null
@@ -1,76 +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.
-
-/*============================================================
-**
-**
-**
-** An attribute to suppress violation messages/warnings
-** by static code analysis tools.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.Diagnostics.CodeAnalysis
-{
-
- [AttributeUsage(
- AttributeTargets.All,
- Inherited = false,
- AllowMultiple = true
- )
- ]
- [Conditional("CODE_ANALYSIS")]
- public sealed class SuppressMessageAttribute : Attribute
- {
- private string category;
- private string justification;
- private string checkId;
- private string scope;
- private string target;
- private string messageId;
-
- public SuppressMessageAttribute(string category, string checkId)
- {
- this.category = category;
- this.checkId = checkId;
- }
-
- public string Category
- {
- get { return category; }
- }
-
- public string CheckId
- {
- get { return checkId; }
- }
-
- public string Scope
- {
- get { return scope; }
- set { scope = value; }
- }
-
- public string Target
- {
- get { return target; }
- set { target = value; }
- }
-
- public string MessageId
- {
- get { return messageId; }
- set { messageId = value; }
- }
-
- public string Justification
- {
- get { return justification; }
- set { justification = value; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs b/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
deleted file mode 100644
index c57fb59319..0000000000
--- a/src/mscorlib/src/System/Diagnostics/ConditionalAttribute.cs
+++ /dev/null
@@ -1,25 +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;
-
-namespace System.Diagnostics {
- [Serializable]
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple=true)]
- public sealed class ConditionalAttribute : Attribute
- {
- public ConditionalAttribute(String conditionString)
- {
- m_conditionString = conditionString;
- }
-
- public String ConditionString {
- get {
- return m_conditionString;
- }
- }
-
- private String m_conditionString;
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
index 93d6c48701..76b15197f2 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
@@ -27,7 +27,6 @@
#else // CLR
#define FEATURE_UNTRUSTED_CALLERS
#define FEATURE_RELIABILITY_CONTRACTS
-#define FEATURE_SERIALIZATION
#endif
using System;
@@ -43,8 +42,8 @@ using System.Runtime.ConstrainedExecution;
using System.Security;
#endif
-namespace System.Diagnostics.Contracts {
-
+namespace System.Diagnostics.Contracts
+{
#region Attributes
/// <summary>
@@ -71,7 +70,8 @@ namespace System.Diagnostics.Contracts {
_typeWithContracts = typeContainingContracts;
}
- public Type TypeContainingContracts {
+ public Type TypeContainingContracts
+ {
get { return _typeWithContracts; }
}
}
@@ -90,7 +90,8 @@ namespace System.Diagnostics.Contracts {
_typeIAmAContractFor = typeContractsAreFor;
}
- public Type TypeContractsAreFor {
+ public Type TypeContractsAreFor
+ {
get { return _typeIAmAContractFor; }
}
}
@@ -176,7 +177,8 @@ namespace System.Diagnostics.Contracts {
public ContractVerificationAttribute(bool value) { _value = value; }
- public bool Value {
+ public bool Value
+ {
get { return _value; }
}
}
@@ -197,7 +199,8 @@ namespace System.Diagnostics.Contracts {
_publicName = name;
}
- public String Name {
+ public String Name
+ {
get { return _publicName; }
}
}
@@ -247,19 +250,23 @@ namespace System.Diagnostics.Contracts {
_value = value;
}
- public String Category {
+ public String Category
+ {
get { return _category; }
}
- public String Setting {
+ public String Setting
+ {
get { return _setting; }
}
- public bool Enabled {
+ public bool Enabled
+ {
get { return _enabled; }
}
- public String Value {
+ public String Value
+ {
get { return _value; }
}
}
@@ -296,7 +303,8 @@ namespace System.Diagnostics.Contracts {
#endif
public static void Assume(bool condition)
{
- if (!condition) {
+ if (!condition)
+ {
ReportFailure(ContractFailureKind.Assume, null, null, null);
}
}
@@ -316,7 +324,8 @@ namespace System.Diagnostics.Contracts {
#endif
public static void Assume(bool condition, String userMessage)
{
- if (!condition) {
+ if (!condition)
+ {
ReportFailure(ContractFailureKind.Assume, userMessage, null, null);
}
}
@@ -630,8 +639,8 @@ namespace System.Diagnostics.Contracts {
public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
-#if INSIDE_CLR
- throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive"));
+#if CORECLR
+ throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive);
#else
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
@@ -690,8 +699,8 @@ namespace System.Diagnostics.Contracts {
public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate)
{
if (fromInclusive > toExclusive)
-#if INSIDE_CLR
- throw new ArgumentException(Environment.GetResourceString("Argument_ToExclusiveLessThanFromExclusive"));
+#if CORECLR
+ throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive);
#else
throw new ArgumentException("fromInclusive must be less than or equal to toExclusive.");
#endif
@@ -769,7 +778,8 @@ namespace System.Diagnostics.Contracts {
#endregion
}
- public enum ContractFailureKind {
+ public enum ContractFailureKind
+ {
Precondition,
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")]
Postcondition,
@@ -779,8 +789,6 @@ namespace System.Diagnostics.Contracts {
Assert,
Assume,
}
-
-
}
// Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
index 5f4de4f666..09d1e6baca 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
@@ -20,7 +20,6 @@
#else // CLR
#define FEATURE_UNTRUSTED_CALLERS
#define FEATURE_RELIABILITY_CONTRACTS
-#define FEATURE_SERIALIZATION
#endif
using System;
@@ -37,8 +36,8 @@ using System.Runtime.ConstrainedExecution;
using System.Security;
#endif
-namespace System.Diagnostics.Contracts {
-
+namespace System.Diagnostics.Contracts
+{
public static partial class Contract
{
#region Private Methods
@@ -74,7 +73,7 @@ namespace System.Diagnostics.Contracts {
if (probablyNotRewritten == null)
probablyNotRewritten = thisAssembly;
String simpleName = probablyNotRewritten.GetName().Name;
- System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, Environment.GetResourceString("MustUseCCRewrite", contractKind, simpleName), null, null, null);
+ System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null);
_assertingMustUseRewriter = false;
}
@@ -96,7 +95,7 @@ namespace System.Diagnostics.Contracts {
static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
Contract.EndContractBlock();
// displayMessage == null means: yes we handled it. Otherwise it is the localized failure message
@@ -116,15 +115,18 @@ namespace System.Diagnostics.Contracts {
/// full trust, because it will inform you of bugs in the appdomain and because the event handler
/// could allow you to continue execution.
/// </summary>
- public static event EventHandler<ContractFailedEventArgs> ContractFailed {
+ public static event EventHandler<ContractFailedEventArgs> ContractFailed
+ {
#if FEATURE_UNTRUSTED_CALLERS
#endif
- add {
+ add
+ {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value;
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
- remove {
+ remove
+ {
System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value;
}
}
@@ -159,7 +161,8 @@ namespace System.Diagnostics.Contracts {
public Exception OriginalException { get { return _originalException; } }
// Whether the event handler "handles" this contract failure, or to fail via escalation policy.
- public bool Handled {
+ public bool Handled
+ {
get { return _handled; }
}
@@ -170,7 +173,8 @@ namespace System.Diagnostics.Contracts {
_handled = true;
}
- public bool Unwind {
+ public bool Unwind
+ {
get { return _unwind; }
}
@@ -186,9 +190,9 @@ namespace System.Diagnostics.Contracts {
[SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")]
internal sealed class ContractException : Exception
{
- readonly ContractFailureKind _Kind;
- readonly string _UserMessage;
- readonly string _Condition;
+ private readonly ContractFailureKind _Kind;
+ private readonly string _UserMessage;
+ private readonly string _Condition;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public ContractFailureKind Kind { get { return _Kind; } }
@@ -209,9 +213,9 @@ namespace System.Diagnostics.Contracts {
: base(failure, innerException)
{
HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED;
- this._Kind = kind;
- this._UserMessage = userMessage;
- this._Condition = condition;
+ _Kind = kind;
+ _UserMessage = userMessage;
+ _Condition = condition;
}
private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
@@ -259,7 +263,8 @@ namespace System.Runtime.CompilerServices
{
#if FEATURE_UNTRUSTED_CALLERS
#endif
- add {
+ add
+ {
// Eagerly prepare each event handler _marked with a reliability contract_, to
// attempt to reduce out of memory exceptions while reporting contract violations.
// This only works if the new handler obeys the constraints placed on
@@ -275,7 +280,8 @@ namespace System.Runtime.CompilerServices
}
#if FEATURE_UNTRUSTED_CALLERS
#endif
- remove {
+ remove
+ {
lock (lockObject)
{
contractFailedEvent -= value;
@@ -302,7 +308,7 @@ namespace System.Runtime.CompilerServices
static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage)
{
if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", failureKind), nameof(failureKind));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), nameof(failureKind));
Contract.EndContractBlock();
string returnValue;
@@ -369,13 +375,14 @@ namespace System.Runtime.CompilerServices
// "Assert On Failure" but used in a process that can't pop up asserts, like an
// NT Service).
- if (!Environment.UserInteractive) {
+ if (!Environment.UserInteractive)
+ {
throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException);
}
// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info.
// Optional info like string for collapsed text vs. expanded text.
- String windowTitle = Environment.GetResourceString(GetResourceNameForFailure(kind));
+ String windowTitle = SR.GetResourceString(GetResourceNameForFailure(kind));
const int numStackFramesToSkip = 2; // To make stack traces easier to read
System.Diagnostics.Assert.Fail(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip);
// If we got here, the user selected Ignore. Continue.
@@ -430,12 +437,14 @@ namespace System.Runtime.CompilerServices
// on Silverlight we may not be able to look up a friendly string for the
// error message. Let's leverage Silverlight's default error message there.
String failureMessage;
- if (!String.IsNullOrEmpty(conditionText)) {
+ if (!String.IsNullOrEmpty(conditionText))
+ {
resourceName += "_Cnd";
- failureMessage = Environment.GetResourceString(resourceName, conditionText);
+ failureMessage = SR.Format(SR.GetResourceString(resourceName), conditionText);
}
- else {
- failureMessage = Environment.GetResourceString(resourceName);
+ else
+ {
+ failureMessage = SR.GetResourceString(resourceName);
}
// Now add in the user message, if present.
diff --git a/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs b/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs
new file mode 100644
index 0000000000..495f2f713c
--- /dev/null
+++ b/src/mscorlib/src/System/Diagnostics/Debug.Unix.cs
@@ -0,0 +1,95 @@
+// 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;
+
+namespace System.Diagnostics
+{
+ public static partial class Debug
+ {
+ private static readonly bool s_shouldWriteToStdErr = Environment.GetEnvironmentVariable("COMPlus_DebugWriteToStdErr") == "1";
+
+ private static void ShowAssertDialog(string stackTrace, string message, string detailMessage)
+ {
+ if (Debugger.IsAttached)
+ {
+ Debugger.Break();
+ }
+ else
+ {
+ // In Core, we do not show a dialog.
+ // Fail in order to avoid anyone catching an exception and masking
+ // an assert failure.
+ var ex = new DebugAssertException(message, detailMessage, stackTrace);
+ Environment.FailFast(ex.Message, ex);
+ }
+ }
+
+ private static void WriteCore(string message)
+ {
+ WriteToDebugger(message);
+
+ if (s_shouldWriteToStdErr)
+ {
+ WriteToStderr(message);
+ }
+ }
+
+ private static void WriteToDebugger(string message)
+ {
+ if (Debugger.IsLogging())
+ {
+ Debugger.Log(0, null, message);
+ }
+ else
+ {
+ Interop.Sys.SysLog(Interop.Sys.SysLogPriority.LOG_USER | Interop.Sys.SysLogPriority.LOG_DEBUG, "%s", message);
+ }
+ }
+
+ private static void WriteToStderr(string message)
+ {
+ // We don't want to write UTF-16 to a file like standard error. Ideally we would transcode this
+ // to UTF8, but the downside of that is it pulls in a bunch of stuff into what is ideally
+ // a path with minimal dependencies (as to prevent re-entrency), so we'll take the strategy
+ // of just throwing away any non ASCII characters from the message and writing the rest
+
+ const int BufferLength = 256;
+
+ unsafe
+ {
+ byte* buf = stackalloc byte[BufferLength];
+ int bufCount;
+ int i = 0;
+
+ while (i < message.Length)
+ {
+ for (bufCount = 0; bufCount < BufferLength && i < message.Length; i++)
+ {
+ if (message[i] <= 0x7F)
+ {
+ buf[bufCount] = (byte)message[i];
+ bufCount++;
+ }
+ }
+
+ int totalBytesWritten = 0;
+ while (bufCount > 0)
+ {
+ int bytesWritten = Interop.Sys.Write(2 /* stderr */, buf + totalBytesWritten, bufCount);
+ if (bytesWritten < 0)
+ {
+ // On error, simply stop writing the debug output. This could commonly happen if stderr
+ // was piped to a program that ended before this program did, resulting in EPIPE errors.
+ return;
+ }
+
+ bufCount -= bytesWritten;
+ totalBytesWritten += bytesWritten;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Diagnostics/Debug.Windows.cs b/src/mscorlib/src/System/Diagnostics/Debug.Windows.cs
new file mode 100644
index 0000000000..095e9b6985
--- /dev/null
+++ b/src/mscorlib/src/System/Diagnostics/Debug.Windows.cs
@@ -0,0 +1,63 @@
+// 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.Diagnostics
+{
+ public static partial class Debug
+ {
+ private static void ShowAssertDialog(string stackTrace, string message, string detailMessage)
+ {
+ if (Debugger.IsAttached)
+ {
+ Debugger.Break();
+ }
+ else
+ {
+ // In Core, we do not show a dialog.
+ // Fail in order to avoid anyone catching an exception and masking
+ // an assert failure.
+ var ex = new DebugAssertException(message, detailMessage, stackTrace);
+ Environment.FailFast(ex.Message, ex);
+ }
+ }
+
+ private static void WriteCore(string message)
+ {
+ // really huge messages mess up both VS and dbmon, so we chop it up into
+ // reasonable chunks if it's too big. This is the number of characters
+ // that OutputDebugstring chunks at.
+ const int WriteChunkLength = 4091;
+
+ // We don't want output from multiple threads to be interleaved.
+ lock (s_ForLock)
+ {
+ if (message == null || message.Length <= WriteChunkLength)
+ {
+ WriteToDebugger(message);
+ }
+ else
+ {
+ int offset;
+ for (offset = 0; offset < message.Length - WriteChunkLength; offset += WriteChunkLength)
+ {
+ WriteToDebugger(message.Substring(offset, WriteChunkLength));
+ }
+ WriteToDebugger(message.Substring(offset));
+ }
+ }
+ }
+
+ private static void WriteToDebugger(string message)
+ {
+ if (Debugger.IsLogging())
+ {
+ Debugger.Log(0, null, message);
+ }
+ else
+ {
+ Interop.Kernel32.OutputDebugString(message ?? string.Empty);
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Diagnostics/Debugger.cs b/src/mscorlib/src/System/Diagnostics/Debugger.cs
index 21c57dbfaf..92df7e7f5f 100644
--- a/src/mscorlib/src/System/Diagnostics/Debugger.cs
+++ b/src/mscorlib/src/System/Diagnostics/Debugger.cs
@@ -5,16 +5,16 @@
// The Debugger class is a part of the System.Diagnostics package
// and is used for communicating with a debugger.
+using System;
+using System.IO;
+using System.Collections;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Security;
+using System.Runtime.Versioning;
+
namespace System.Diagnostics
{
- using System;
- using System.IO;
- using System.Collections;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Security;
- using System.Runtime.Versioning;
-
// No data, does not need to be marked with the serializable attribute
public sealed class Debugger
{
@@ -30,13 +30,14 @@ namespace System.Diagnostics
// Break causes a breakpoint to be signalled to an attached debugger. If no debugger
// is attached, the user is asked if he wants to attach a debugger. If yes, then the
// debugger is launched.
+ [MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Break()
{
// Causing a break is now allowed.
BreakInternal();
}
- static void BreakCanThrow()
+ private static void BreakCanThrow()
{
BreakInternal();
}
@@ -128,7 +129,5 @@ namespace System.Diagnostics
// report the notification depending on its settings.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void CustomNotification(ICustomDebuggerNotification data);
-
}
-
}
diff --git a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
index ce9987b9e2..5e1dfd82a5 100644
--- a/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
+++ b/src/mscorlib/src/System/Diagnostics/DebuggerAttributes.cs
@@ -10,32 +10,33 @@
**
**
===========================================================*/
-
-
-namespace System.Diagnostics {
- using System;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
+
+
+using System;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Diagnostics
+{
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerStepThroughAttribute : Attribute
{
- public DebuggerStepThroughAttribute () {}
- }
+ public DebuggerStepThroughAttribute() { }
+ }
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)]
public sealed class DebuggerHiddenAttribute : Attribute
{
- public DebuggerHiddenAttribute () {}
+ public DebuggerHiddenAttribute() { }
}
-[Serializable]
-[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor |AttributeTargets.Struct, Inherited = false)]
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor | AttributeTargets.Struct, Inherited = false)]
public sealed class DebuggerNonUserCodeAttribute : Attribute
{
- public DebuggerNonUserCodeAttribute () {}
+ public DebuggerNonUserCodeAttribute() { }
}
// Attribute class used by the compiler to mark modules.
@@ -46,11 +47,11 @@ namespace System.Diagnostics {
// or may not have included debugging information, and the Runtime
// won't preserve the debugging info, which will make debugging after
// a JIT attach difficult.
- [AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Module, AllowMultiple = false)]
+ [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module, AllowMultiple = false)]
public sealed class DebuggableAttribute : Attribute
{
[Flags]
- public enum DebuggingModes
+ public enum DebuggingModes
{
None = 0x0,
Default = 0x1,
@@ -58,7 +59,7 @@ namespace System.Diagnostics {
IgnoreSymbolStoreSequencePoints = 0x2,
EnableEditAndContinue = 0x4
}
-
+
private DebuggingModes m_debuggingModes;
public DebuggableAttribute(bool isJITTrackingEnabled,
@@ -66,12 +67,12 @@ namespace System.Diagnostics {
{
m_debuggingModes = 0;
- if (isJITTrackingEnabled)
+ if (isJITTrackingEnabled)
{
m_debuggingModes |= DebuggingModes.Default;
}
- if (isJITOptimizerDisabled)
+ if (isJITOptimizerDisabled)
{
m_debuggingModes |= DebuggingModes.DisableOptimizations;
}
@@ -91,7 +92,7 @@ namespace System.Diagnostics {
{
get { return ((m_debuggingModes & DebuggingModes.DisableOptimizations) != 0); }
}
-
+
public DebuggingModes DebuggingFlags
{
get { return m_debuggingModes; }
@@ -108,25 +109,25 @@ namespace System.Diagnostics {
// Please also change the code which validates DebuggerBrowsableState variable (in this file)
// if you change this enum.
- public enum DebuggerBrowsableState
- {
- Never = 0,
+ public enum DebuggerBrowsableState
+ {
+ Never = 0,
//Expanded is not supported in this release
//Expanded = 1,
- Collapsed = 2,
+ Collapsed = 2,
RootHidden = 3
}
-
-
+
+
// the one currently supported with the csee.dat
// (mcee.dat, autoexp.dat) file.
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
- public sealed class DebuggerBrowsableAttribute: Attribute
+ public sealed class DebuggerBrowsableAttribute : Attribute
{
private DebuggerBrowsableState state;
public DebuggerBrowsableAttribute(DebuggerBrowsableState state)
{
- if( state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
+ if (state < DebuggerBrowsableState.Never || state > DebuggerBrowsableState.RootHidden)
throw new ArgumentOutOfRangeException(nameof(state));
Contract.EndContractBlock();
@@ -141,7 +142,7 @@ namespace System.Diagnostics {
// DebuggerTypeProxyAttribute
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true)]
- public sealed class DebuggerTypeProxyAttribute: Attribute
+ public sealed class DebuggerTypeProxyAttribute : Attribute
{
private string typeName;
private string targetName;
@@ -149,14 +150,15 @@ namespace System.Diagnostics {
public DebuggerTypeProxyAttribute(Type type)
{
- if (type == null) {
+ if (type == null)
+ {
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
- this.typeName = type.AssemblyQualifiedName;
+ typeName = type.AssemblyQualifiedName;
}
-
+
public DebuggerTypeProxyAttribute(string typeName)
{
this.typeName = typeName;
@@ -168,16 +170,18 @@ namespace System.Diagnostics {
public Type Target
{
- set {
- if( value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
-
- targetName = value.AssemblyQualifiedName;
- target = value;
+
+ targetName = value.AssemblyQualifiedName;
+ target = value;
}
-
+
get { return target; }
}
@@ -185,10 +189,9 @@ namespace System.Diagnostics {
{
get { return targetName; }
set { targetName = value; }
-
}
}
-
+
// This attribute is used to control what is displayed for the given class or field
// in the data windows in the debugger. The single argument to this attribute is
// the string that will be displayed in the value column for instances of the type.
@@ -209,19 +212,21 @@ namespace System.Diagnostics {
public DebuggerDisplayAttribute(string value)
{
- if( value == null ) {
+ if (value == null)
+ {
this.value = "";
}
- else {
+ else
+ {
this.value = value;
}
name = "";
type = "";
- }
+ }
public string Value
{
- get { return this.value; }
+ get { return value; }
}
public string Name
@@ -238,13 +243,15 @@ namespace System.Diagnostics {
public Type Target
{
- set {
- if( value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
-
- targetName = value.AssemblyQualifiedName;
+
+ targetName = value.AssemblyQualifiedName;
target = value;
}
get { return target; }
@@ -254,7 +261,6 @@ namespace System.Diagnostics {
{
get { return targetName; }
set { targetName = value; }
-
}
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs b/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs
index 32d7a98a50..8ad4fec082 100644
--- a/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs
+++ b/src/mscorlib/src/System/Diagnostics/EditAndContinueHelper.cs
@@ -11,12 +11,13 @@
**
=============================================================================*/
-namespace System.Diagnostics {
-
- using System;
-
+
+using System;
+
+namespace System.Diagnostics
+{
[Serializable]
- internal sealed class EditAndContinueHelper
+ internal sealed class EditAndContinueHelper
{
#pragma warning disable 169
#pragma warning disable 414 // Field is not used from managed.
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs b/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
deleted file mode 100644
index 1a1f5fa2c0..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/ActivityTracker.cs
+++ /dev/null
@@ -1,665 +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.Diagnostics;
-using System.Threading;
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-using System.Threading.Tasks;
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Tracks activities. This is meant to be a singleton (accessed by the ActivityTracer.Instance static property)
- ///
- /// Logically this is simply holds the m_current variable that holds the async local that holds the current ActivityInfo
- /// An ActivityInfo is represents a activity (which knows its creator and thus knows its path).
- ///
- /// Most of the magic is in the async local (it gets copied to new tasks)
- ///
- /// On every start event call OnStart
- ///
- /// Guid activityID;
- /// Guid relatedActivityID;
- /// if (OnStart(activityName, out activityID, out relatedActivityID, ForceStop, options))
- /// // Log Start event with activityID and relatedActivityID
- ///
- /// On every stop event call OnStop
- ///
- /// Guid activityID;
- /// if (OnStop(activityName, ref activityID ForceStop))
- /// // Stop event with activityID
- ///
- /// On any normal event log the event with activityTracker.CurrentActivityId
- /// </summary>
- internal class ActivityTracker
- {
-
- /// <summary>
- /// Called on work item begins. The activity name = providerName + activityName without 'Start' suffix.
- /// It updates CurrentActivityId to track.
- ///
- /// It returns true if the Start should be logged, otherwise (if it is illegal recursion) it return false.
- ///
- /// The start event should use as its activity ID the CurrentActivityId AFTER calling this routine and its
- /// RelatedActivityID the CurrentActivityId BEFORE calling this routine (the creator).
- ///
- /// If activity tracing is not on, then activityId and relatedActivityId are not set
- /// </summary>
- public void OnStart(string providerName, string activityName, int task, ref Guid activityId, ref Guid relatedActivityId, EventActivityOptions options)
- {
- if (m_current == null) // We are not enabled
- {
- // We used to rely on the TPL provider turning us on, but that has the disadvantage that you don't get Start-Stop tracking
- // until you use Tasks for the first time (which you may never do). Thus we change it to pull rather tan push for whether
- // we are enabled.
- if (m_checkedForEnable)
- return;
- m_checkedForEnable = true;
- if (TplEtwProvider.Log.IsEnabled(EventLevel.Informational, TplEtwProvider.Keywords.TasksFlowActivityIds))
- Enable();
- if (m_current == null)
- return;
- }
-
-
- Debug.Assert((options & EventActivityOptions.Disable) == 0);
-
- var currentActivity = m_current.Value;
- var fullActivityName = NormalizeActivityName(providerName, activityName, task);
-
- var etwLog = TplEtwProvider.Log;
- if (etwLog.Debug)
- {
- etwLog.DebugFacilityMessage("OnStartEnter", fullActivityName);
- etwLog.DebugFacilityMessage("OnStartEnterActivityState", ActivityInfo.LiveActivities(currentActivity));
- }
-
- if (currentActivity != null)
- {
- // Stop activity tracking if we reached the maximum allowed depth
- if (currentActivity.m_level >= MAX_ACTIVITY_DEPTH)
- {
- activityId = Guid.Empty;
- relatedActivityId = Guid.Empty;
- if (etwLog.Debug)
- etwLog.DebugFacilityMessage("OnStartRET", "Fail");
- return;
- }
- // Check for recursion, and force-stop any activities if the activity already started.
- if ((options & EventActivityOptions.Recursive) == 0)
- {
- ActivityInfo existingActivity = FindActiveActivity(fullActivityName, currentActivity);
- if (existingActivity != null)
- {
- OnStop(providerName, activityName, task, ref activityId);
- currentActivity = m_current.Value;
- }
- }
- }
-
- // Get a unique ID for this activity.
- long id;
- if (currentActivity == null)
- id = Interlocked.Increment(ref m_nextId);
- else
- id = Interlocked.Increment(ref currentActivity.m_lastChildID);
-
- // The previous ID is my 'causer' and becomes my related activity ID
- relatedActivityId = EventSource.CurrentThreadActivityId;
-
- // Add to the list of started but not stopped activities.
- ActivityInfo newActivity = new ActivityInfo(fullActivityName, id, currentActivity, relatedActivityId, options);
- m_current.Value = newActivity;
-
- // Remember the current ID so we can log it
- activityId = newActivity.ActivityId;
-
- if (etwLog.Debug)
- {
- etwLog.DebugFacilityMessage("OnStartRetActivityState", ActivityInfo.LiveActivities(newActivity));
- etwLog.DebugFacilityMessage1("OnStartRet", activityId.ToString(), relatedActivityId.ToString());
- }
- }
-
- /// <summary>
- /// Called when a work item stops. The activity name = providerName + activityName without 'Stop' suffix.
- /// It updates m_current variable to track this fact. The Stop event associated with stop should log the ActivityID associated with the event.
- ///
- /// If activity tracing is not on, then activityId and relatedActivityId are not set
- /// </summary>
- public void OnStop(string providerName, string activityName, int task, ref Guid activityId)
- {
- if (m_current == null) // We are not enabled
- return;
-
- var fullActivityName = NormalizeActivityName(providerName, activityName, task);
-
- var etwLog = TplEtwProvider.Log;
- if (etwLog.Debug)
- {
- etwLog.DebugFacilityMessage("OnStopEnter", fullActivityName);
- etwLog.DebugFacilityMessage("OnStopEnterActivityState", ActivityInfo.LiveActivities(m_current.Value));
- }
-
- for (; ; ) // This is a retry loop.
- {
- ActivityInfo currentActivity = m_current.Value;
- ActivityInfo newCurrentActivity = null; // if we have seen any live activities (orphans), at he first one we have seen.
-
- // Search to find the activity to stop in one pass. This insures that we don't let one mistake
- // (stopping something that was not started) cause all active starts to be stopped
- // By first finding the target start to stop we are more robust.
- ActivityInfo activityToStop = FindActiveActivity(fullActivityName, currentActivity);
-
- // ignore stops where we can't find a start because we may have popped them previously.
- if (activityToStop == null)
- {
- activityId = Guid.Empty;
- // TODO add some logging about this. Basically could not find matching start.
- if (etwLog.Debug)
- etwLog.DebugFacilityMessage("OnStopRET", "Fail");
- return;
- }
-
- activityId = activityToStop.ActivityId;
-
- // See if there are any orphans that need to be stopped.
- ActivityInfo orphan = currentActivity;
- while (orphan != activityToStop && orphan != null)
- {
- if (orphan.m_stopped != 0) // Skip dead activities.
- {
- orphan = orphan.m_creator;
- continue;
- }
- if (orphan.CanBeOrphan())
- {
- // We can't pop anything after we see a valid orphan, remember this for later when we update m_current.
- if (newCurrentActivity == null)
- newCurrentActivity = orphan;
- }
- else
- {
- orphan.m_stopped = 1;
- Debug.Assert(orphan.m_stopped != 0);
- }
- orphan = orphan.m_creator;
- }
-
- // try to Stop the activity atomically. Other threads may be trying to do this as well.
- if (Interlocked.CompareExchange(ref activityToStop.m_stopped, 1, 0) == 0)
- {
- // I succeeded stopping this activity. Now we update our m_current pointer
-
- // If I haven't yet determined the new current activity, it is my creator.
- if (newCurrentActivity == null)
- newCurrentActivity = activityToStop.m_creator;
-
- m_current.Value = newCurrentActivity;
-
- if (etwLog.Debug)
- {
- etwLog.DebugFacilityMessage("OnStopRetActivityState", ActivityInfo.LiveActivities(newCurrentActivity));
- etwLog.DebugFacilityMessage("OnStopRet", activityId.ToString());
- }
- return;
- }
- // We failed to stop it. We must have hit a race to stop it. Just start over and try again.
- }
- }
-
- /// <summary>
- /// Turns on activity tracking. It is sticky, once on it stays on (race issues otherwise)
- /// </summary>
- public void Enable()
- {
- if (m_current == null)
- {
- // Catch the not Implemented
- try
- {
- m_current = new AsyncLocal<ActivityInfo>(ActivityChanging);
- }
- catch (NotImplementedException) {
-#if (!ES_BUILD_PCL && ! PROJECTN)
- // send message to debugger without delay
- System.Diagnostics.Debugger.Log(0, null, "Activity Enabled() called but AsyncLocals Not Supported (pre V4.6). Ignoring Enable");
-#endif
- }
- }
- }
-
- /// <summary>
- /// An activity tracker is a singleton, this is how you get the one and only instance.
- /// </summary>
- public static ActivityTracker Instance { get { return s_activityTrackerInstance; } }
-
-
- #region private
-
- /// <summary>
- /// The current activity ID. Use this to log normal events.
- /// </summary>
- private Guid CurrentActivityId { get { return m_current.Value.ActivityId; } }
-
- /// <summary>
- /// Searched for a active (nonstopped) activity with the given name. Returns null if not found.
- /// </summary>
- private ActivityInfo FindActiveActivity(string name, ActivityInfo startLocation)
- {
- var activity = startLocation;
- while (activity != null)
- {
- if (name == activity.m_name && activity.m_stopped == 0)
- return activity;
- activity = activity.m_creator;
- }
- return null;
- }
-
- /// <summary>
- /// Strip out "Start" or "End" suffix from activity name and add providerName prefix.
- /// If 'task' it does not end in Start or Stop and Task is non-zero use that as the name of the activity
- /// </summary>
- private string NormalizeActivityName(string providerName, string activityName, int task)
- {
- if (activityName.EndsWith(EventSource.s_ActivityStartSuffix, StringComparison.Ordinal))
- activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStartSuffix.Length);
- else if (activityName.EndsWith(EventSource.s_ActivityStopSuffix, StringComparison.Ordinal))
- activityName = activityName.Substring(0, activityName.Length - EventSource.s_ActivityStopSuffix.Length);
- else if (task != 0)
- activityName = "task" + task.ToString();
-
- // We use provider name to distinguish between activities from different providers.
- return providerName + activityName;
- }
-
- // *******************************************************************************
- /// <summary>
- /// An ActivityInfo represents a particular activity. It is almost read-only. The only
- /// fields that change after creation are
- /// m_lastChildID - used to generate unique IDs for the children activities and for the most part can be ignored.
- /// m_stopped - indicates that this activity is dead
- /// This read-only-ness is important because an activity's m_creator chain forms the
- /// 'Path of creation' for the activity (which is also its unique ID) but is also used as
- /// the 'list of live parents' which indicate of those ancestors, which are alive (if they
- /// are not marked dead they are alive).
- /// </summary>
- private class ActivityInfo
- {
- public ActivityInfo(string name, long uniqueId, ActivityInfo creator, Guid activityIDToRestore, EventActivityOptions options)
- {
- m_name = name;
- m_eventOptions = options;
- m_creator = creator;
- m_uniqueId = uniqueId;
- m_level = creator != null ? creator.m_level + 1 : 0;
- m_activityIdToRestore = activityIDToRestore;
-
- // Create a nice GUID that encodes the chain of activities that started this one.
- CreateActivityPathGuid(out m_guid, out m_activityPathGuidOffset);
- }
-
- public Guid ActivityId
- {
- get
- {
- return m_guid;
- }
- }
-
- public static string Path(ActivityInfo activityInfo)
- {
- if (activityInfo == null)
- return ("");
- return Path(activityInfo.m_creator) + "/" + activityInfo.m_uniqueId.ToString();
- }
-
- public override string ToString()
- {
- return m_name + "(" + Path(this) + (m_stopped != 0 ? ",DEAD)" : ")");
- }
-
- public static string LiveActivities(ActivityInfo list)
- {
- if (list == null)
- return "";
- return list.ToString() + ";" + LiveActivities(list.m_creator);
- }
-
- public bool CanBeOrphan()
- {
- if ((m_eventOptions & EventActivityOptions.Detachable) != 0)
- return true;
- return false;
- }
-
- #region private
-
- #region CreateActivityPathGuid
- /// <summary>
- /// Logically every activity Path (see Path()) that describes the activities that caused this
- /// (rooted in an activity that predates activity tracking.
- ///
- /// We wish to encode this path in the Guid to the extent that we can. Many of the paths have
- /// many small numbers in them and we take advantage of this in the encoding to output as long
- /// a path in the GUID as possible.
- ///
- /// Because of the possibility of GUID collision, we only use 96 of the 128 bits of the GUID
- /// for encoding the path. The last 32 bits are a simple checksum (and random number) that
- /// identifies this as using the convention defined here.
- ///
- /// It returns both the GUID which has the path as well as the offset that points just beyond
- /// the end of the activity (so it can be appended to). Note that if the end is in a nibble
- /// (it uses nibbles instead of bytes as the unit of encoding, then it will point at the unfinished
- /// byte (since the top nibble can't be zero you can determine if this is true by seeing if
- /// this byte is nonZero. This offset is needed to efficiently create the ID for child activities.
- /// </summary>
- private unsafe void CreateActivityPathGuid(out Guid idRet, out int activityPathGuidOffset)
- {
- fixed (Guid* outPtr = &idRet)
- {
- int activityPathGuidOffsetStart = 0;
- if (m_creator != null)
- {
- activityPathGuidOffsetStart = m_creator.m_activityPathGuidOffset;
- idRet = m_creator.m_guid;
- }
- else
- {
- // TODO FIXME - differentiate between AD inside PCL
- int appDomainID = 0;
-#if (!ES_BUILD_STANDALONE && !PROJECTN)
- appDomainID = System.Threading.Thread.GetDomainID();
-#endif
- // We start with the appdomain number to make this unique among appdomains.
- activityPathGuidOffsetStart = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint)appDomainID);
- }
-
- activityPathGuidOffset = AddIdToGuid(outPtr, activityPathGuidOffsetStart, (uint)m_uniqueId);
-
-
- // If the path does not fit, Make a GUID by incrementing rather than as a path, keeping as much of the path as possible
- if (12 < activityPathGuidOffset)
- CreateOverflowGuid(outPtr);
- }
- }
-
- /// <summary>
- /// If we can't fit the activity Path into the GUID we come here. What we do is simply
- /// generate a 4 byte number (s_nextOverflowId). Then look for an ancestor that has
- /// sufficient space for this ID. By doing this, we preserve the fact that this activity
- /// is a child (of unknown depth) from that ancestor.
- /// </summary>
- private unsafe void CreateOverflowGuid(Guid* outPtr)
- {
- // Search backwards for an ancestor that has sufficient space to put the ID.
- for (ActivityInfo ancestor = m_creator; ancestor != null; ancestor = ancestor.m_creator)
- {
- if (ancestor.m_activityPathGuidOffset <= 10) // we need at least 2 bytes.
- {
- uint id = unchecked((uint)Interlocked.Increment(ref ancestor.m_lastChildID)); // Get a unique ID
- // Try to put the ID into the GUID
- *outPtr = ancestor.m_guid;
- int endId = AddIdToGuid(outPtr, ancestor.m_activityPathGuidOffset, id, true);
-
- // Does it fit?
- if (endId <= 12)
- break;
- }
- }
- }
-
- /// <summary>
- /// The encoding for a list of numbers used to make Activity GUIDs. Basically
- /// we operate on nibbles (which are nice because they show up as hex digits). The
- /// list is ended with a end nibble (0) and depending on the nibble value (Below)
- /// the value is either encoded into nibble itself or it can spill over into the
- /// bytes that follow.
- /// </summary>
- enum NumberListCodes : byte
- {
- End = 0x0, // ends the list. No valid value has this prefix.
- LastImmediateValue = 0xA,
-
- PrefixCode = 0xB, // all the 'long' encodings go here. If the next nibble is MultiByte1-4
- // than this is a 'overflow' id. Unlike the hierarchical IDs these are
- // allocated densely but don't tell you anything about nesting. we use
- // these when we run out of space in the GUID to store the path.
-
- MultiByte1 = 0xC, // 1 byte follows. If this Nibble is in the high bits, it the high bits of the number are stored in the low nibble.
- // commented out because the code does not explicitly reference the names (but they are logically defined).
- // MultiByte2 = 0xD, // 2 bytes follow (we don't bother with the nibble optimization)
- // MultiByte3 = 0xE, // 3 bytes follow (we don't bother with the nibble optimization)
- // MultiByte4 = 0xF, // 4 bytes follow (we don't bother with the nibble optimization)
- }
-
- /// Add the activity id 'id' to the output Guid 'outPtr' starting at the offset 'whereToAddId'
- /// Thus if this number is 6 that is where 'id' will be added. This will return 13 (12
- /// is the maximum number of bytes that fit in a GUID) if the path did not fit.
- /// If 'overflow' is true, then the number is encoded as an 'overflow number (which has a
- /// special (longer prefix) that indicates that this ID is allocated differently
- private static unsafe int AddIdToGuid(Guid* outPtr, int whereToAddId, uint id, bool overflow = false)
- {
- byte* ptr = (byte*)outPtr;
- byte* endPtr = ptr + 12;
- ptr += whereToAddId;
- if (endPtr <= ptr)
- return 13; // 12 means we might exactly fit, 13 means we definately did not fit
-
- if (0 < id && id <= (uint)NumberListCodes.LastImmediateValue && !overflow)
- WriteNibble(ref ptr, endPtr, id);
- else
- {
- uint len = 4;
- if (id <= 0xFF)
- len = 1;
- else if (id <= 0xFFFF)
- len = 2;
- else if (id <= 0xFFFFFF)
- len = 3;
-
- if (overflow)
- {
- if (endPtr <= ptr + 2) // I need at least 2 bytes
- return 13;
-
- // Write out the prefix code nibble and the length nibble
- WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.PrefixCode);
- }
- // The rest is the same for overflow and non-overflow case
- WriteNibble(ref ptr, endPtr, (uint)NumberListCodes.MultiByte1 + (len - 1));
-
- // Do we have an odd nibble? If so flush it or use it for the 12 byte case.
- if (ptr < endPtr && *ptr != 0)
- {
- // If the value < 4096 we can use the nibble we are otherwise just outputting as padding.
- if (id < 4096)
- {
- // Indicate this is a 1 byte multicode with 4 high order bits in the lower nibble.
- *ptr = (byte)(((uint)NumberListCodes.MultiByte1 << 4) + (id >> 8));
- id &= 0xFF; // Now we only want the low order bits.
- }
- ptr++;
- }
-
- // Write out the bytes.
- while (0 < len)
- {
- if (endPtr <= ptr)
- {
- ptr++; // Indicate that we have overflowed
- break;
- }
- *ptr++ = (byte)id;
- id = (id >> 8);
- --len;
- }
- }
-
- // Compute the checksum
- uint* sumPtr = (uint*)outPtr;
- // We set the last DWORD the sum of the first 3 DWORDS in the GUID. This
- sumPtr[3] = sumPtr[0] + sumPtr[1] + sumPtr[2] + 0x599D99AD; // This last number is a random number (it identifies us as us)
-
- return (int)(ptr - ((byte*)outPtr));
- }
-
- /// <summary>
- /// Write a single Nible 'value' (must be 0-15) to the byte buffer represented by *ptr.
- /// Will not go past 'endPtr'. Also it assumes that we never write 0 so we can detect
- /// whether a nibble has already been written to ptr because it will be nonzero.
- /// Thus if it is non-zero it adds to the current byte, otherwise it advances and writes
- /// the new byte (in the high bits) of the next byte.
- /// </summary>
- private static unsafe void WriteNibble(ref byte* ptr, byte* endPtr, uint value)
- {
- Debug.Assert(0 <= value && value < 16);
- Debug.Assert(ptr < endPtr);
-
- if (*ptr != 0)
- *ptr++ |= (byte)value;
- else
- *ptr = (byte)(value << 4);
- }
-
- #endregion // CreateGuidForActivityPath
-
- readonly internal string m_name; // The name used in the 'start' and 'stop' APIs to help match up
- readonly long m_uniqueId; // a small number that makes this activity unique among its siblings
- internal readonly Guid m_guid; // Activity Guid, it is basically an encoding of the Path() (see CreateActivityPathGuid)
- internal readonly int m_activityPathGuidOffset; // Keeps track of where in m_guid the causality path stops (used to generated child GUIDs)
- internal readonly int m_level; // current depth of the Path() of the activity (used to keep recursion under control)
- readonly internal EventActivityOptions m_eventOptions; // Options passed to start.
- internal long m_lastChildID; // used to create a unique ID for my children activities
- internal int m_stopped; // This work item has stopped
- readonly internal ActivityInfo m_creator; // My parent (creator). Forms the Path() for the activity.
- readonly internal Guid m_activityIdToRestore; // The Guid to restore after a stop.
- #endregion
- }
-
- // This callback is used to initialize the m_current AsyncLocal Variable.
- // Its job is to keep the ETW Activity ID (part of thread local storage) in sync
- // with m_current.ActivityID
- void ActivityChanging(AsyncLocalValueChangedArgs<ActivityInfo> args)
- {
- ActivityInfo cur = args.CurrentValue;
- ActivityInfo prev = args.PreviousValue;
-
- // Are we popping off a value? (we have a prev, and it creator is cur)
- // Then check if we should use the GUID at the time of the start event
- if (prev != null && prev.m_creator == cur)
- {
- // If the saved activity ID is not the same as the creator activity
- // that takes precedence (it means someone explicitly did a SetActivityID)
- // Set it to that and get out
- if (cur == null || prev.m_activityIdToRestore != cur.ActivityId)
- {
- EventSource.SetCurrentThreadActivityId(prev.m_activityIdToRestore);
- return;
- }
- }
-
- // OK we did not have an explicit SetActivityID set. Then we should be
- // setting the activity to current ActivityInfo. However that activity
- // might be dead, in which case we should skip it, so we never set
- // the ID to dead things.
- while (cur != null)
- {
- // We found a live activity (typically the first time), set it to that.
- if (cur.m_stopped == 0)
- {
- EventSource.SetCurrentThreadActivityId(cur.ActivityId);
- return;
- }
- cur = cur.m_creator;
- }
- // we can get here if there is no information on our activity stack (everything is dead)
- // currently we do nothing, as that seems better than setting to Guid.Emtpy.
- }
-
- /// <summary>
- /// Async local variables have the property that the are automatically copied whenever a task is created and used
- /// while that task is running. Thus m_current 'flows' to any task that is caused by the current thread that
- /// last set it.
- ///
- /// This variable points a a linked list that represents all Activities that have started but have not stopped.
- /// </summary>
- AsyncLocal<ActivityInfo> m_current;
- bool m_checkedForEnable;
-
- // Singleton
- private static ActivityTracker s_activityTrackerInstance = new ActivityTracker();
-
- // Used to create unique IDs at the top level. Not used for nested Ids (each activity has its own id generator)
- static long m_nextId = 0;
- private const ushort MAX_ACTIVITY_DEPTH = 100; // Limit maximum depth of activities to be tracked at 100.
- // This will avoid leaking memory in case of activities that are never stopped.
-
- #endregion
- }
-
-#if ES_BUILD_STANDALONE || PROJECTN
- /******************************** SUPPORT *****************************/
- /// <summary>
- /// This is supplied by the framework. It is has the semantics that the value is copied to any new Tasks that is created
- /// by the current task. Thus all causally related code gets this value. Note that reads and writes to this VARIABLE
- /// (not what it points it) to this does not need to be protected by locks because it is inherently thread local (you always
- /// only get your thread local copy which means that you never have races.
- /// </summary>
- ///
-#if ES_BUILD_STANDALONE
- [EventSource(Name = "Microsoft.Tasks.Nuget")]
-#else
- [EventSource(Name = "System.Diagnostics.Tracing.TplEtwProvider")]
-#endif
- internal class TplEtwProvider : EventSource
- {
- public class Keywords
- {
- public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80;
- public const EventKeywords Debug = (EventKeywords)0x20000;
- }
-
- public static TplEtwProvider Log = new TplEtwProvider();
- public bool Debug { get { return IsEnabled(EventLevel.Verbose, Keywords.Debug); } }
-
- public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(1, Facility, Message); }
- public void DebugFacilityMessage1(string Facility, string Message, string Arg) { WriteEvent(2, Facility, Message, Arg); }
- public void SetActivityId(Guid Id) { WriteEvent(3, Id); }
- }
-#endif
-
-#if ES_BUILD_AGAINST_DOTNET_V35 || ES_BUILD_PCL || NO_ASYNC_LOCAL
- // In these cases we don't have any Async local support. Do nothing.
- internal sealed class AsyncLocalValueChangedArgs<T>
- {
- public T PreviousValue { get { return default(T); } }
- public T CurrentValue { get { return default(T); } }
-
- }
-
- internal sealed class AsyncLocal<T>
- {
- public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler) {
- throw new NotImplementedException("AsyncLocal only available on V4.6 and above");
- }
- public T Value
- {
- get { return default(T); }
- set { }
- }
- }
-#endif
-
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventActivityOptions.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventActivityOptions.cs
deleted file mode 100644
index 782afbf869..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventActivityOptions.cs
+++ /dev/null
@@ -1,39 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// EventActivityOptions flags allow to specify different activity related characteristics.
- /// </summary>
- [Flags]
- public enum EventActivityOptions
- {
- /// <summary>
- /// No special options are added to the event.
- /// </summary>
- None = 0,
-
- /// <summary>
- /// Disable Implicit Activity Tracking
- /// </summary>
- Disable = 0x2,
-
- /// <summary>
- /// Allow activity event to call itself (directly or indirectly)
- /// </summary>
- Recursive = 0x4,
-
- /// <summary>
- /// Allows event activity to live beyond its parent.
- /// </summary>
- Detachable = 0x8
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventCounter.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventCounter.cs
deleted file mode 100644
index b1f946464e..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventCounter.cs
+++ /dev/null
@@ -1,436 +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.Collections;
-using System.Collections.Generic;
-using System.Threading;
-#if ES_BUILD_PCL
- using System.Threading.Tasks;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Provides the ability to collect statistics through EventSource
- /// </summary>
- public class EventCounter
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="EventCounter"/> class.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <param name="eventSource">The event source.</param>
- public EventCounter(string name, EventSource eventSource)
- {
- if (name == null)
- {
- throw new ArgumentNullException(nameof(name));
- }
-
- if (eventSource == null)
- {
- throw new ArgumentNullException(nameof(eventSource));
- }
-
- InitializeBuffer();
- _name = name;
- EventCounterGroup.AddEventCounter(eventSource, this);
- }
-
- /// <summary>
- /// Writes the metric.
- /// </summary>
- /// <param name="value">The value.</param>
- public void WriteMetric(float value)
- {
- Enqueue(value);
- }
-
- #region private implementation
-
- private readonly string _name;
-
- #region Buffer Management
-
- // Values buffering
- private const int BufferedSize = 10;
- private const float UnusedBufferSlotValue = float.NegativeInfinity;
- private const int UnsetIndex = -1;
- private volatile float[] _bufferedValues;
- private volatile int _bufferedValuesIndex;
-
- private void InitializeBuffer()
- {
- _bufferedValues = new float[BufferedSize];
- for (int i = 0; i < _bufferedValues.Length; i++)
- {
- _bufferedValues[i] = UnusedBufferSlotValue;
- }
- }
-
- private void Enqueue(float value)
- {
- // It is possible that two threads read the same bufferedValuesIndex, but only one will be able to write the slot, so that is okay.
- int i = _bufferedValuesIndex;
- while (true)
- {
- float result = Interlocked.CompareExchange(ref _bufferedValues[i], value, UnusedBufferSlotValue);
- i++;
- if (_bufferedValues.Length <= i)
- {
- // It is possible that two threads both think the buffer is full, but only one get to actually flush it, the other
- // will eventually enter this code path and potentially calling Flushing on a buffer that is not full, and that's okay too.
- lock (_bufferedValues)
- {
- Flush();
- }
- i = 0;
- }
-
- if (result == UnusedBufferSlotValue)
- {
- // CompareExchange succeeded
- _bufferedValuesIndex = i;
- return;
- }
- }
- }
-
- private void Flush()
- {
- for (int i = 0; i < _bufferedValues.Length; i++)
- {
- var value = Interlocked.Exchange(ref _bufferedValues[i], UnusedBufferSlotValue);
- if (value != UnusedBufferSlotValue)
- {
- OnMetricWritten(value);
- }
- }
-
- _bufferedValuesIndex = 0;
- }
-
- #endregion // Buffer Management
-
- #region Statistics Calculation
-
- // Statistics
- private int _count;
- private float _sum;
- private float _sumSquared;
- private float _min;
- private float _max;
-
- private void OnMetricWritten(float value)
- {
- _sum += value;
- _sumSquared += value * value;
- if (_count == 0 || value > _max)
- {
- _max = value;
- }
-
- if (_count == 0 || value < _min)
- {
- _min = value;
- }
-
- _count++;
- }
-
- internal EventCounterPayload GetEventCounterPayload()
- {
- lock (_bufferedValues)
- {
- Flush();
- EventCounterPayload result = new EventCounterPayload();
- result.Name = _name;
- result.Count = _count;
- result.Mean = _sum / _count;
- result.StandardDerivation = (float)Math.Sqrt(_sumSquared / _count - _sum * _sum / _count / _count);
- result.Min = _min;
- result.Max = _max;
- ResetStatistics();
- return result;
- }
- }
-
- private void ResetStatistics()
- {
- _count = 0;
- _sum = 0;
- _sumSquared = 0;
- _min = 0;
- _max = 0;
- }
-
- #endregion // Statistics Calculation
-
- #endregion // private implementation
- }
-
- #region internal supporting classes
-
- [EventData]
- internal class EventCounterPayload : IEnumerable<KeyValuePair<string, object>>
- {
- public string Name { get; set; }
-
- public float Mean { get; set; }
-
- public float StandardDerivation { get; set; }
-
- public int Count { get; set; }
-
- public float Min { get; set; }
-
- public float Max { get; set; }
-
- public float IntervalSec { get; internal set; }
-
- #region Implementation of the IEnumerable interface
-
- public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
- {
- return ForEnumeration.GetEnumerator();
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- return ForEnumeration.GetEnumerator();
- }
-
- private IEnumerable<KeyValuePair<string, object>> ForEnumeration
- {
- get
- {
- yield return new KeyValuePair<string, object>("Name", Name);
- yield return new KeyValuePair<string, object>("Mean", Mean);
- yield return new KeyValuePair<string, object>("StandardDerivation", StandardDerivation);
- yield return new KeyValuePair<string, object>("Count", Count);
- yield return new KeyValuePair<string, object>("Min", Min);
- yield return new KeyValuePair<string, object>("Max", Max);
- }
- }
-
- #endregion // Implementation of the IEnumerable interface
- }
-
- internal class EventCounterGroup : IDisposable
- {
- private readonly EventSource _eventSource;
- private readonly int _eventSourceIndex;
- private readonly List<EventCounter> _eventCounters;
-
- internal EventCounterGroup(EventSource eventSource, int eventSourceIndex)
- {
- _eventSource = eventSource;
- _eventSourceIndex = eventSourceIndex;
- _eventCounters = new List<EventCounter>();
- RegisterCommandCallback();
- }
-
- private void Add(EventCounter eventCounter)
- {
- _eventCounters.Add(eventCounter);
- }
-
- #region EventSource Command Processing
-
- private void RegisterCommandCallback()
- {
- _eventSource.EventCommandExecuted += OnEventSourceCommand;
- }
-
- private void OnEventSourceCommand(object sender, EventCommandEventArgs e)
- {
- if (e.Command == EventCommand.Enable || e.Command == EventCommand.Update)
- {
- string valueStr;
- float value;
- if (e.Arguments.TryGetValue("EventCounterIntervalSec", out valueStr) && float.TryParse(valueStr, out value))
- {
- EnableTimer(value);
- }
- }
- }
-
- #endregion // EventSource Command Processing
-
- #region Global EventCounterGroup Array management
-
- private static EventCounterGroup[] s_eventCounterGroups;
-
- internal static void AddEventCounter(EventSource eventSource, EventCounter eventCounter)
- {
- int eventSourceIndex = EventListener.EventSourceIndex(eventSource);
-
- EventCounterGroup.EnsureEventSourceIndexAvailable(eventSourceIndex);
- EventCounterGroup eventCounterGroup = GetEventCounterGroup(eventSource);
- eventCounterGroup.Add(eventCounter);
- }
-
- private static void EnsureEventSourceIndexAvailable(int eventSourceIndex)
- {
- if (EventCounterGroup.s_eventCounterGroups == null)
- {
- EventCounterGroup.s_eventCounterGroups = new EventCounterGroup[eventSourceIndex + 1];
- }
- else if (eventSourceIndex >= EventCounterGroup.s_eventCounterGroups.Length)
- {
- EventCounterGroup[] newEventCounterGroups = new EventCounterGroup[eventSourceIndex + 1];
- Array.Copy(EventCounterGroup.s_eventCounterGroups, 0, newEventCounterGroups, 0, EventCounterGroup.s_eventCounterGroups.Length);
- EventCounterGroup.s_eventCounterGroups = newEventCounterGroups;
- }
- }
-
- private static EventCounterGroup GetEventCounterGroup(EventSource eventSource)
- {
- int eventSourceIndex = EventListener.EventSourceIndex(eventSource);
- EventCounterGroup result = EventCounterGroup.s_eventCounterGroups[eventSourceIndex];
- if (result == null)
- {
- result = new EventCounterGroup(eventSource, eventSourceIndex);
- EventCounterGroup.s_eventCounterGroups[eventSourceIndex] = result;
- }
-
- return result;
- }
-
- #endregion // Global EventCounterGroup Array management
-
- #region Timer Processing
-
- private DateTime _timeStampSinceCollectionStarted;
- private int _pollingIntervalInMilliseconds;
- private Timer _pollingTimer;
-
- private void EnableTimer(float pollingIntervalInSeconds)
- {
- if (pollingIntervalInSeconds == 0)
- {
- if (_pollingTimer != null)
- {
- _pollingTimer.Dispose();
- _pollingTimer = null;
- }
-
- _pollingIntervalInMilliseconds = 0;
- }
- else if (_pollingIntervalInMilliseconds == 0 || pollingIntervalInSeconds < _pollingIntervalInMilliseconds)
- {
- _pollingIntervalInMilliseconds = (int)(pollingIntervalInSeconds * 1000);
- if (_pollingTimer != null)
- {
- _pollingTimer.Dispose();
- _pollingTimer = null;
- }
-
- _timeStampSinceCollectionStarted = DateTime.Now;
- _pollingTimer = new Timer(OnTimer, null, _pollingIntervalInMilliseconds, _pollingIntervalInMilliseconds);
- }
- }
-
- private void OnTimer(object state)
- {
- if (_eventSource.IsEnabled())
- {
- DateTime now = DateTime.Now;
- TimeSpan elapsed = now - _timeStampSinceCollectionStarted;
- lock (_pollingTimer)
- {
- foreach (var eventCounter in _eventCounters)
- {
- EventCounterPayload payload = eventCounter.GetEventCounterPayload();
- payload.IntervalSec = (float)elapsed.TotalSeconds;
- _eventSource.Write("EventCounters", new EventSourceOptions() { Level = EventLevel.LogAlways }, new { Payload = payload });
- }
-
-
- _timeStampSinceCollectionStarted = now;
- }
- }
- else
- {
- _pollingTimer.Dispose();
- _pollingTimer = null;
- EventCounterGroup.s_eventCounterGroups[_eventSourceIndex] = null;
- }
- }
-
- #region PCL timer hack
-
-#if ES_BUILD_PCL
- internal delegate void TimerCallback(object state);
-
- internal sealed class Timer : CancellationTokenSource, IDisposable
- {
- private int _period;
- private TimerCallback _callback;
- private object _state;
-
- internal Timer(TimerCallback callback, object state, int dueTime, int period)
- {
- _callback = callback;
- _state = state;
- _period = period;
- Schedule(dueTime);
- }
-
- private void Schedule(int dueTime)
- {
- Task.Delay(dueTime, Token).ContinueWith(OnTimer, null, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default);
- }
-
- private void OnTimer(Task t, object s)
- {
- Schedule(_period);
- _callback(_state);
- }
-
- public new void Dispose() { base.Cancel(); }
- }
-#endif
- #endregion // PCL timer hack
-
- #endregion // Timer Processing
-
- #region Implementation of the IDisposable interface
-
- private bool _disposed = false;
-
- public void Dispose()
- {
- Dispose(true);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- if (_disposed)
- {
- return;
- }
-
- if (disposing)
- {
- if (_pollingTimer != null)
- {
- _pollingTimer.Dispose();
- _pollingTimer = null;
- }
- }
-
- _disposed = true;
- }
-
- #endregion // Implementation of the IDisposable interface
- }
-
- #endregion // internal supporting classes
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
deleted file mode 100644
index 116b50f86c..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventDescriptor.cs
+++ /dev/null
@@ -1,195 +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.Runtime.InteropServices;
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-#endif
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- [StructLayout(LayoutKind.Explicit, Size = 16)]
-#if !CORECLR
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#endif // CORECLR
- internal struct EventDescriptor
- {
- # region private
- [FieldOffset(0)]
- private int m_traceloggingId;
- [FieldOffset(0)]
- private ushort m_id;
- [FieldOffset(2)]
- private byte m_version;
- [FieldOffset(3)]
- private byte m_channel;
- [FieldOffset(4)]
- private byte m_level;
- [FieldOffset(5)]
- private byte m_opcode;
- [FieldOffset(6)]
- private ushort m_task;
- [FieldOffset(8)]
- private long m_keywords;
- #endregion
-
- public EventDescriptor(
- int traceloggingId,
- byte level,
- byte opcode,
- long keywords
- )
- {
- this.m_id = 0;
- this.m_version = 0;
- this.m_channel = 0;
- this.m_traceloggingId = traceloggingId;
- this.m_level = level;
- this.m_opcode = opcode;
- this.m_task = 0;
- this.m_keywords = keywords;
- }
-
- public EventDescriptor(
- int id,
- byte version,
- byte channel,
- byte level,
- byte opcode,
- int task,
- long keywords
- )
- {
- if (id < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(id), Resources.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if (id > ushort.MaxValue)
- {
- throw new ArgumentOutOfRangeException(nameof(id), Resources.GetResourceString("ArgumentOutOfRange_NeedValidId", 1, ushort.MaxValue));
- }
-
- m_traceloggingId = 0;
- m_id = (ushort)id;
- m_version = version;
- m_channel = channel;
- m_level = level;
- m_opcode = opcode;
- m_keywords = keywords;
-
- if (task < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(task), Resources.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
-
- if (task > ushort.MaxValue)
- {
- throw new ArgumentOutOfRangeException(nameof(task), Resources.GetResourceString("ArgumentOutOfRange_NeedValidId", 1, ushort.MaxValue));
- }
-
- m_task = (ushort)task;
- }
-
- public int EventId
- {
- get
- {
- return m_id;
- }
- }
- public byte Version
- {
- get
- {
- return m_version;
- }
- }
- public byte Channel
- {
- get
- {
- return m_channel;
- }
- }
- public byte Level
- {
- get
- {
- return m_level;
- }
- }
- public byte Opcode
- {
- get
- {
- return m_opcode;
- }
- }
- public int Task
- {
- get
- {
- return m_task;
- }
- }
- public long Keywords
- {
- get
- {
- return m_keywords;
- }
- }
-
- public override bool Equals(object obj)
- {
- if (!(obj is EventDescriptor))
- return false;
-
- return Equals((EventDescriptor) obj);
- }
-
- public override int GetHashCode()
- {
- return m_id ^ m_version ^ m_channel ^ m_level ^ m_opcode ^ m_task ^ (int)m_keywords;
- }
-
- public bool Equals(EventDescriptor other)
- {
- if ((m_id != other.m_id) ||
- (m_version != other.m_version) ||
- (m_channel != other.m_channel) ||
- (m_level != other.m_level) ||
- (m_opcode != other.m_opcode) ||
- (m_task != other.m_task) ||
- (m_keywords != other.m_keywords))
- {
- return false;
- }
- return true;
- }
-
- public static bool operator ==(EventDescriptor event1, EventDescriptor event2)
- {
- return event1.Equals(event2);
- }
-
- public static bool operator !=(EventDescriptor event1, EventDescriptor event2)
- {
- return !event1.Equals(event2);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
deleted file mode 100644
index 1da6a46707..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventProvider.cs
+++ /dev/null
@@ -1,1207 +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 Microsoft.Win32;
-using System.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Runtime.InteropServices;
-using System.Security;
-#if !CORECLR
-using System.Security.Permissions;
-#endif // !CORECLR
-using System.Threading;
-using System;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_AGAINST_DOTNET_V35
-using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace)
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- // New in CLR4.0
- internal enum ControllerCommand
- {
- // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256
- // The first 256 negative numbers are reserved for the framework.
- Update = 0, // Not used by EventPrividerBase.
- SendManifest = -1,
- Enable = -2,
- Disable = -3,
- };
-
- /// <summary>
- /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
- /// controller callback)
- /// </summary>
-#if !CORECLR
- [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
-#endif // CORECLR
- internal partial class EventProvider : IDisposable
- {
- // This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what
- // subclasses of EventProvider use when creating efficient (but unsafe) version of
- // EventWrite. We do make it a nested type because we really don't expect anyone to use
- // it except subclasses (and then only rarely).
- public struct EventData
- {
- internal unsafe ulong Ptr;
- internal uint Size;
- internal uint Reserved;
- }
-
- /// <summary>
- /// A struct characterizing ETW sessions (identified by the etwSessionId) as
- /// activity-tracing-aware or legacy. A session that's activity-tracing-aware
- /// has specified one non-zero bit in the reserved range 44-47 in the
- /// 'allKeywords' value it passed in for a specific EventProvider.
- /// </summary>
- public struct SessionInfo
- {
- internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords
- internal int etwSessionId; // the machine-wide ETW session ID
-
- internal SessionInfo(int sessionIdBit_, int etwSessionId_)
- { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; }
- }
-
- private static bool m_setInformationMissing;
-
- UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
- private long m_regHandle; // Trace Registration Handle
- private byte m_level; // Tracing Level
- private long m_anyKeywordMask; // Trace Enable Flags
- 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
- internal bool m_disposed; // when true provider has unregistered
-
- [ThreadStatic]
- private static WriteEventErrorCode s_returnCode; // The last return code
-
- private const int s_basicTypeAllocationBufferSize = 16;
- private const int s_etwMaxNumberArguments = 128;
- private const int s_etwAPIMaxRefObjCount = 8;
- private const int s_maxEventDataDescriptors = 128;
- private const int s_traceEventMaximumSize = 65482;
- private const int s_traceEventMaximumStringSize = 32724;
-
- [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
- public enum WriteEventErrorCode : int
- {
- //check mapping to runtime codes
- NoError = 0,
- NoFreeBuffers = 1,
- EventTooBig = 2,
- NullInput = 3,
- TooManyArgs = 4,
- Other = 5,
- };
-
- // Because callbacks happen on registration, and we need the callbacks for those setup
- // we can't call Register in the constructor.
- //
- // Note that EventProvider should ONLY be used by EventSource. In particular because
- // it registers a callback from native code you MUST dispose it BEFORE shutdown, otherwise
- // you may get native callbacks during shutdown when we have destroyed the delegate.
- // EventSource has special logic to do this, no one else should be calling EventProvider.
- internal EventProvider()
- {
- }
-
- /// <summary>
- /// This method registers the controlGuid of this class with ETW. We need to be running on
- /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some
- /// reason the ETW Register call failed a NotSupported exception will be thrown.
- /// </summary>
- // <SecurityKernel Critical="True" Ring="0">
- // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" />
- // <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)
- {
- m_providerId = providerGuid;
- uint status;
- m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack);
-
- status = EventRegister(ref m_providerId, m_etwCallback);
- if (status != 0)
- {
- throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status)));
- }
- }
-
- //
- // implement Dispose Pattern to early deregister from ETW insted of waiting for
- // the finalizer to call deregistration.
- // Once the user is done with the provider it needs to call Close() or Dispose()
- // If neither are called the finalizer will unregister the provider anyway
- //
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
- // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
- // </SecurityKernel>
- protected virtual void Dispose(bool disposing)
- {
- //
- // explicit cleanup is done by calling Dispose with true from
- // Dispose() or Close(). The disposing arguement is ignored because there
- // are no unmanaged resources.
- // The finalizer calls Dispose with false.
- //
-
- //
- // check if the object has been allready disposed
- //
- if (m_disposed) return;
-
- // Disable the provider.
- m_enabled = false;
-
- // Do most of the work under a lock to avoid shutdown race.
-
- long registrationHandle = 0;
- lock (EventListener.EventListenersLock)
- {
- // Double check
- if (m_disposed)
- return;
-
- registrationHandle = m_regHandle;
- m_regHandle = 0;
- m_disposed = true;
- }
-
- // We do the Unregistration outside the EventListenerLock because there is a lock
- // inside the ETW routines. This lock is taken before ETW issues commands
- // Thus the ETW lock gets taken first and then our EventListenersLock gets taken
- // in SendCommand(), and also here. If we called EventUnregister after taking
- // the EventListenersLock then the take-lock order is reversed and we can have
- // deadlocks in race conditions (dispose racing with an ETW command).
- //
- // We solve by Unregistering after releasing the EventListenerLock.
- if (registrationHandle != 0)
- EventUnregister(registrationHandle);
-
- }
-
- /// <summary>
- /// This method deregisters the controlGuid of this class with ETW.
- ///
- /// </summary>
- public virtual void Close()
- {
- Dispose();
- }
-
- ~EventProvider()
- {
- Dispose(false);
- }
-
- // <SecurityKernel Critical="True" Ring="0">
- // <UsesUnsafeCode Name="Parameter filterData of type: Void*" />
- // <UsesUnsafeCode Name="Parameter callbackContext of type: Void*" />
- // </SecurityKernel>
- unsafe void EtwEnableCallBack(
- [In] ref System.Guid sourceId,
- [In] int controlCode,
- [In] byte setLevel,
- [In] long anyKeyword,
- [In] long allKeyword,
- [In] UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
- [In] void* callbackContext
- )
- {
- // This is an optional callback API. We will therefore ignore any failures that happen as a
- // result of turning on this provider as to not crash the app.
- // EventSource has code to validate whether initialization it expected to occur actually occurred
- try
- {
- ControllerCommand command = ControllerCommand.Update;
- IDictionary<string, string> args = null;
- bool skipFinalOnControllerCommand = false;
- if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER)
- {
- m_enabled = true;
- m_level = setLevel;
- m_anyKeywordMask = anyKeyword;
- m_allKeywordMask = allKeyword;
-
- // ES_SESSION_INFO is a marker for additional places we #ifdeffed out to remove
- // references to EnumerateTraceGuidsEx. This symbol is actually not used because
- // today we use FEATURE_ACTIVITYSAMPLING to determine if this code is there or not.
- // However we put it in the #if so that we don't lose the fact that this feature
- // switch is at least partially independent of FEATURE_ACTIVITYSAMPLING
-
- List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions();
- foreach (var session in sessionsChanged)
- {
- int sessionChanged = session.Item1.sessionIdBit;
- int etwSessionId = session.Item1.etwSessionId;
- bool bEnabling = session.Item2;
-
- skipFinalOnControllerCommand = true;
- args = null; // reinitialize args for every session...
-
- // if we get more than one session changed we have no way
- // of knowing which one "filterData" belongs to
- if (sessionsChanged.Count > 1)
- filterData = null;
-
- // read filter data only when a session is being *added*
- byte[] data;
- int keyIndex;
- if (bEnabling &&
- GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex))
- {
- args = new Dictionary<string, string>(4);
- while (keyIndex < data.Length)
- {
- int keyEnd = FindNull(data, keyIndex);
- int valueIdx = keyEnd + 1;
- int valueEnd = FindNull(data, valueIdx);
- if (valueEnd < data.Length)
- {
- string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex);
- string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx);
- args[key] = value;
- }
- keyIndex = valueEnd + 1;
- }
- }
-
- // execute OnControllerCommand once for every session that has changed.
- OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId);
- }
- }
- else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER)
- {
- m_enabled = false;
- m_level = 0;
- m_anyKeywordMask = 0;
- m_allKeywordMask = 0;
- m_liveSessions = null;
- }
- else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE)
- {
- command = ControllerCommand.SendManifest;
- }
- else
- return; // per spec you ignore commands you don't recognize.
-
- if (!skipFinalOnControllerCommand)
- OnControllerCommand(command, args, 0, 0);
- }
- catch (Exception)
- {
- // We want to ignore any failures that happen as a result of turning on this provider as to
- // not crash the app.
- }
- }
-
- // New in CLR4.0
- protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { }
- protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } }
- protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } }
- protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } }
-
- static private int FindNull(byte[] buffer, int idx)
- {
- while (idx < buffer.Length && buffer[idx] != 0)
- idx++;
- return idx;
- }
-
- /// <summary>
- /// Determines the ETW sessions that have been added and/or removed to the set of
- /// sessions interested in the current provider. It does so by (1) enumerating over all
- /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2)
- /// comparing the current list with a list it cached on the previous invocation.
- ///
- /// The return value is a list of tuples, where the SessionInfo specifies the
- /// ETW session that was added or remove, and the bool specifies whether the
- /// session was added or whether it was removed from the set.
- /// </summary>
- private List<Tuple<SessionInfo, bool>> GetSessions()
- {
- List<SessionInfo> liveSessionList = null;
-
- GetSessionInfo(
- (int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) =>
- GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref sessionList),
- ref liveSessionList);
-
- List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>();
-
- // first look for sessions that have gone away (or have changed)
- // (present in the m_liveSessions but not in the new liveSessionList)
- if (m_liveSessions != null)
- {
- foreach (SessionInfo s in m_liveSessions)
- {
- int idx;
- if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 ||
- (liveSessionList[idx].sessionIdBit != s.sessionIdBit))
- changedSessionList.Add(Tuple.Create(s, false));
-
- }
- }
- // next look for sessions that were created since the last callback (or have changed)
- // (present in the new liveSessionList but not in m_liveSessions)
- if (liveSessionList != null)
- {
- foreach (SessionInfo s in liveSessionList)
- {
- int idx;
- if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 ||
- (m_liveSessions[idx].sessionIdBit != s.sessionIdBit))
- changedSessionList.Add(Tuple.Create(s, true));
- }
- }
-
- m_liveSessions = liveSessionList;
- return changedSessionList;
- }
-
-
- /// <summary>
- /// This method is the callback used by GetSessions() when it calls into GetSessionInfo().
- /// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that
- /// GetSessionInfo() passes in.
- /// </summary>
- private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords,
- ref List<SessionInfo> sessionList)
- {
- uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords));
- // an ETW controller that specifies more than the mandated bit for our EventSource
- // will be ignored...
- if (bitcount(sessionIdBitMask) > 1)
- return;
-
- if (sessionList == null)
- sessionList = new List<SessionInfo>(8);
-
- if (bitcount(sessionIdBitMask) == 1)
- {
- // activity-tracing-aware etw session
- sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask) + 1, etwSessionId));
- }
- else
- {
- // legacy etw session
- sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All) + 1, etwSessionId));
- }
- }
-
- private delegate void SessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList);
-
- /// <summary>
- /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid'
- /// for the current process ID, calling 'action' for each session, and passing it the
- /// ETW session and the 'AllKeywords' the session enabled for the current provider.
- /// </summary>
- private unsafe void GetSessionInfo(SessionInfoCallback action, ref List<SessionInfo> sessionList)
- {
- // We wish the EventSource package to be legal for Windows Store applications.
- // Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here
- // and use the information in the registry instead. This means that ETW controllers
- // that do not publish their intent to the registry (basically all controllers EXCEPT
- // TraceEventSesion) will not work properly
-
- // However the framework version of EventSource DOES have ES_SESSION_INFO defined and thus
- // does not have this issue.
-#if ES_SESSION_INFO || !ES_BUILD_STANDALONE
- int buffSize = 256; // An initial guess that probably works most of the time.
- byte* buffer;
- for (; ; )
- {
- var space = stackalloc byte[buffSize];
- buffer = space;
- var hr = 0;
-
- fixed (Guid* provider = &m_providerId)
- {
- hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo,
- provider, sizeof(Guid), buffer, buffSize, ref buffSize);
- }
- if (hr == 0)
- break;
- if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */)
- return;
- }
-
- var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer;
- var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1];
- int processId = unchecked((int)Win32Native.GetCurrentProcessId());
- // iterate over the instances of the EventProvider in all processes
- for (int i = 0; i < providerInfos->InstanceCount; i++)
- {
- if (providerInstance->Pid == processId)
- {
- var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1];
- // iterate over the list of active ETW sessions "listening" to the current provider
- for (int j = 0; j < providerInstance->EnableCount; j++)
- action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword, ref sessionList);
- }
- if (providerInstance->NextOffset == 0)
- break;
- Debug.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
- var structBase = (byte*)providerInstance;
- providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
- }
-#else
-#if !ES_BUILD_PCL && !FEATURE_PAL // TODO command arguments don't work on PCL builds...
- // This code is only used in the Nuget Package Version of EventSource. because
- // the code above is using APIs baned from UWP apps.
- //
- // TODO: In addition to only working when TraceEventSession enables the provider, this code
- // also has a problem because TraceEvent does not clean up if the registry is stale
- // It is unclear if it is worth keeping, but for now we leave it as it does work
- // at least some of the time.
-
- // Determine our session from what is in the registry.
- string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
- if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
- regKey = @"Software" + @"\Wow6432Node" + regKey;
- else
- regKey = @"Software" + regKey;
-
- var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey);
- if (key != null)
- {
- foreach (string valueName in key.GetValueNames())
- {
- if (valueName.StartsWith("ControllerData_Session_", StringComparison.Ordinal))
- {
- string strId = valueName.Substring(23); // strip of the ControllerData_Session_
- int etwSessionId;
- if (int.TryParse(strId, out etwSessionId))
- {
- // we need to assert this permission for partial trust scenarios
- (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
- var data = key.GetValue(valueName) as byte[];
- if (data != null)
- {
- var dataAsString = System.Text.Encoding.UTF8.GetString(data);
- int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword", StringComparison.Ordinal);
- if (0 <= keywordIdx)
- {
- int startIdx = keywordIdx + 18;
- int endIdx = dataAsString.IndexOf('\0', startIdx);
- string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx);
- int keywordBit;
- if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit))
- action(etwSessionId, 1L << keywordBit, ref sessionList);
- }
- }
- }
- }
- }
- }
-#endif
-#endif
- }
-
- /// <summary>
- /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId'
- /// or -1 if the value is not present.
- /// </summary>
- private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId)
- {
- if (sessions == null)
- return -1;
- // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile
- // on coreclr as well
- for (int i = 0; i < sessions.Count; ++i)
- if (sessions[i].etwSessionId == etwSessionId)
- return i;
-
- return -1;
- }
-
- /// <summary>
- /// Gets any data to be passed from the controller to the provider. It starts with what is passed
- /// into the callback, but unfortunately this data is only present for when the provider is active
- /// at the time the controller issues the command. To allow for providers to activate after the
- /// controller issued a command, we also check the registry and use that to get the data. The function
- /// returns an array of bytes representing the data, the index into that byte array where the data
- /// starts, and the command being issued associated with that data.
- /// </summary>
- private unsafe bool GetDataFromController(int etwSessionId,
- UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart)
- {
- data = null;
- dataStart = 0;
- if (filterData == null)
- {
-#if (!ES_BUILD_PCL && !PROJECTN && !FEATURE_PAL)
- string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
- if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
- regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
- else
- regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;
-
- string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);
-
- // we need to assert this permission for partial trust scenarios
-#if !CORECLR
- (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
-#endif
- data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
- if (data != null)
- {
- // We only used the persisted data from the registry for updates.
- command = ControllerCommand.Update;
- return true;
- }
-#endif
- }
- else
- {
- if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024)
- {
- data = new byte[filterData->Size];
- Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length);
- }
- command = (ControllerCommand)filterData->Type;
- return true;
- }
-
- command = ControllerCommand.Update;
- return false;
- }
-
- /// <summary>
- /// IsEnabled, method used to test if provider is enabled
- /// </summary>
- public bool IsEnabled()
- {
- return m_enabled;
- }
-
- /// <summary>
- /// IsEnabled, method used to test if event is enabled
- /// </summary>
- /// <param name="level">
- /// Level to test
- /// </param>
- /// <param name="keywords">
- /// Keyword to test
- /// </param>
- public bool IsEnabled(byte level, long keywords)
- {
- //
- // If not enabled at all, return false.
- //
- if (!m_enabled)
- {
- return false;
- }
-
- // This also covers the case of Level == 0.
- if ((level <= m_level) ||
- (m_level == 0))
- {
-
- //
- // Check if Keyword is enabled
- //
-
- if ((keywords == 0) ||
- (((keywords & m_anyKeywordMask) != 0) &&
- ((keywords & m_allKeywordMask) == m_allKeywordMask)))
- {
- return true;
- }
- }
-
- return false;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
- public static WriteEventErrorCode GetLastWriteEventError()
- {
- return s_returnCode;
- }
-
- //
- // Helper function to set the last error on the thread
- //
- private static void SetLastError(int error)
- {
- switch (error)
- {
- case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW:
- case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA:
- s_returnCode = WriteEventErrorCode.EventTooBig;
- break;
- case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY:
- s_returnCode = WriteEventErrorCode.NoFreeBuffers;
- break;
- }
- }
-
- // <SecurityKernel Critical="True" Ring="0">
- // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" />
- // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" />
- // <UsesUnsafeCode Name="Local longptr of type: Int64*" />
- // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" />
- // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" />
- // <UsesUnsafeCode Name="Local charptr of type: Char*" />
- // <UsesUnsafeCode Name="Local byteptr of type: Byte*" />
- // <UsesUnsafeCode Name="Local shortptr of type: Int16*" />
- // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" />
- // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" />
- // <UsesUnsafeCode Name="Local floatptr of type: Single*" />
- // <UsesUnsafeCode Name="Local doubleptr of type: Double*" />
- // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" />
- // <UsesUnsafeCode Name="Local guidptr of type: Guid*" />
- // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" />
- // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" />
- // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
- // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
- // </SecurityKernel>
- private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize)
- /*++
-
- Routine Description:
-
- This routine is used by WriteEvent to unbox the object type and
- to fill the passed in ETW data descriptor.
-
- Arguments:
-
- data - argument to be decoded
-
- dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry)
-
- dataBuffer - storage buffer for storing user data, needed because cant get the address of the object
- (updated to point to the next empty entry)
-
- Return Value:
-
- null if the object is a basic type other than string or byte[]. String otherwise
-
- --*/
- {
- Again:
- dataDescriptor->Reserved = 0;
-
- string sRet = data as string;
- byte[] blobRet = null;
-
- if (sRet != null)
- {
- dataDescriptor->Size = ((uint)sRet.Length + 1) * 2;
- }
- else if ((blobRet = data as byte[]) != null)
- {
- // first store array length
- *(int*)dataBuffer = blobRet.Length;
- dataDescriptor->Ptr = (ulong)dataBuffer;
- dataDescriptor->Size = 4;
- totalEventSize += dataDescriptor->Size;
-
- // then the array parameters
- dataDescriptor++;
- dataBuffer += s_basicTypeAllocationBufferSize;
- dataDescriptor->Size = (uint)blobRet.Length;
- }
- else if (data is IntPtr)
- {
- dataDescriptor->Size = (uint)sizeof(IntPtr);
- IntPtr* intptrPtr = (IntPtr*)dataBuffer;
- *intptrPtr = (IntPtr)data;
- dataDescriptor->Ptr = (ulong)intptrPtr;
- }
- else if (data is int)
- {
- dataDescriptor->Size = (uint)sizeof(int);
- int* intptr = (int*)dataBuffer;
- *intptr = (int)data;
- dataDescriptor->Ptr = (ulong)intptr;
- }
- else if (data is long)
- {
- dataDescriptor->Size = (uint)sizeof(long);
- long* longptr = (long*)dataBuffer;
- *longptr = (long)data;
- dataDescriptor->Ptr = (ulong)longptr;
- }
- else if (data is uint)
- {
- dataDescriptor->Size = (uint)sizeof(uint);
- uint* uintptr = (uint*)dataBuffer;
- *uintptr = (uint)data;
- dataDescriptor->Ptr = (ulong)uintptr;
- }
- else if (data is UInt64)
- {
- dataDescriptor->Size = (uint)sizeof(ulong);
- UInt64* ulongptr = (ulong*)dataBuffer;
- *ulongptr = (ulong)data;
- dataDescriptor->Ptr = (ulong)ulongptr;
- }
- else if (data is char)
- {
- dataDescriptor->Size = (uint)sizeof(char);
- char* charptr = (char*)dataBuffer;
- *charptr = (char)data;
- dataDescriptor->Ptr = (ulong)charptr;
- }
- else if (data is byte)
- {
- dataDescriptor->Size = (uint)sizeof(byte);
- byte* byteptr = (byte*)dataBuffer;
- *byteptr = (byte)data;
- dataDescriptor->Ptr = (ulong)byteptr;
- }
- else if (data is short)
- {
- dataDescriptor->Size = (uint)sizeof(short);
- short* shortptr = (short*)dataBuffer;
- *shortptr = (short)data;
- dataDescriptor->Ptr = (ulong)shortptr;
- }
- else if (data is sbyte)
- {
- dataDescriptor->Size = (uint)sizeof(sbyte);
- sbyte* sbyteptr = (sbyte*)dataBuffer;
- *sbyteptr = (sbyte)data;
- dataDescriptor->Ptr = (ulong)sbyteptr;
- }
- else if (data is ushort)
- {
- dataDescriptor->Size = (uint)sizeof(ushort);
- ushort* ushortptr = (ushort*)dataBuffer;
- *ushortptr = (ushort)data;
- dataDescriptor->Ptr = (ulong)ushortptr;
- }
- else if (data is float)
- {
- dataDescriptor->Size = (uint)sizeof(float);
- float* floatptr = (float*)dataBuffer;
- *floatptr = (float)data;
- dataDescriptor->Ptr = (ulong)floatptr;
- }
- else if (data is double)
- {
- dataDescriptor->Size = (uint)sizeof(double);
- double* doubleptr = (double*)dataBuffer;
- *doubleptr = (double)data;
- dataDescriptor->Ptr = (ulong)doubleptr;
- }
- else if (data is bool)
- {
- // WIN32 Bool is 4 bytes
- dataDescriptor->Size = 4;
- int* intptr = (int*)dataBuffer;
- if (((bool)data))
- {
- *intptr = 1;
- }
- else
- {
- *intptr = 0;
- }
- dataDescriptor->Ptr = (ulong)intptr;
- }
- else if (data is Guid)
- {
- dataDescriptor->Size = (uint)sizeof(Guid);
- Guid* guidptr = (Guid*)dataBuffer;
- *guidptr = (Guid)data;
- dataDescriptor->Ptr = (ulong)guidptr;
- }
- else if (data is decimal)
- {
- dataDescriptor->Size = (uint)sizeof(decimal);
- decimal* decimalptr = (decimal*)dataBuffer;
- *decimalptr = (decimal)data;
- dataDescriptor->Ptr = (ulong)decimalptr;
- }
- else if (data is DateTime)
- {
- const long UTCMinTicks = 504911232000000000;
- long dateTimeTicks = 0;
- // We cannot translate dates sooner than 1/1/1601 in UTC.
- // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks
- if (((DateTime)data).Ticks > UTCMinTicks)
- dateTimeTicks = ((DateTime)data).ToFileTimeUtc();
- dataDescriptor->Size = (uint)sizeof(long);
- long* longptr = (long*)dataBuffer;
- *longptr = dateTimeTicks;
- dataDescriptor->Ptr = (ulong)longptr;
- }
- else
- {
- if (data is System.Enum)
- {
- Type underlyingType = Enum.GetUnderlyingType(data.GetType());
- if (underlyingType == typeof(int))
- {
-#if !ES_BUILD_PCL
- data = ((IConvertible)data).ToInt32(null);
-#else
- data = (int)data;
-#endif
- goto Again;
- }
- else if (underlyingType == typeof(long))
- {
-#if !ES_BUILD_PCL
- data = ((IConvertible)data).ToInt64(null);
-#else
- data = (long)data;
-#endif
- goto Again;
- }
- }
-
- // To our eyes, everything else is a just a string
- if (data == null)
- sRet = "";
- else
- sRet = data.ToString();
- dataDescriptor->Size = ((uint)sRet.Length + 1) * 2;
- }
-
- totalEventSize += dataDescriptor->Size;
-
- // advance buffers
- dataDescriptor++;
- dataBuffer += s_basicTypeAllocationBufferSize;
-
- return (object)sRet ?? (object)blobRet;
- }
-
- /// <summary>
- /// WriteEvent, method to write a parameters with event schema properties
- /// </summary>
- /// <param name="eventDescriptor">
- /// Event Descriptor for this event.
- /// </param>
- /// <param name="activityID">
- /// A pointer to the activity ID GUID to log
- /// </param>
- /// <param name="childActivityID">
- /// childActivityID is marked as 'related' to the current activity ID.
- /// </param>
- /// <param name="eventPayload">
- /// Payload for the ETW event.
- /// </param>
- // <SecurityKernel Critical="True" Ring="0">
- // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
- // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" />
- // <UsesUnsafeCode Name="Local pdata of type: Char*" />
- // <UsesUnsafeCode Name="Local userData of type: EventData*" />
- // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" />
- // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" />
- // <UsesUnsafeCode Name="Local v0 of type: Char*" />
- // <UsesUnsafeCode Name="Local v1 of type: Char*" />
- // <UsesUnsafeCode Name="Local v2 of type: Char*" />
- // <UsesUnsafeCode Name="Local v3 of type: Char*" />
- // <UsesUnsafeCode Name="Local v4 of type: Char*" />
- // <UsesUnsafeCode Name="Local v5 of type: Char*" />
- // <UsesUnsafeCode Name="Local v6 of type: Char*" />
- // <UsesUnsafeCode Name="Local v7 of type: Char*" />
- // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" />
- // </SecurityKernel>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
- {
- int status = 0;
-
- if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
- {
- int argCount = 0;
- unsafe
- {
- argCount = eventPayload.Length;
-
- if (argCount > s_etwMaxNumberArguments)
- {
- s_returnCode = WriteEventErrorCode.TooManyArgs;
- return false;
- }
-
- uint totalEventSize = 0;
- int index;
- int refObjIndex = 0;
- List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount);
- List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount);
- EventData* userData = stackalloc EventData[2 * argCount];
- EventData* userDataPtr = (EventData*)userData;
- byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument
- byte* currentBuffer = dataBuffer;
-
- //
- // The loop below goes through all the arguments and fills in the data
- // descriptors. For strings save the location in the dataString array.
- // Calculates the total size of the event by adding the data descriptor
- // size value set in EncodeObject method.
- //
- bool hasNonStringRefArgs = false;
- for (index = 0; index < eventPayload.Length; index++)
- {
- if (eventPayload[index] != null)
- {
- object supportedRefObj;
- supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize);
-
- if (supportedRefObj != null)
- {
- // EncodeObject advanced userDataPtr to the next empty slot
- int idx = (int)(userDataPtr - userData - 1);
- if (!(supportedRefObj is string))
- {
- if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments)
- {
- s_returnCode = WriteEventErrorCode.TooManyArgs;
- return false;
- }
- hasNonStringRefArgs = true;
- }
- dataRefObj.Add(supportedRefObj);
- refObjPosition.Add(idx);
- refObjIndex++;
- }
- }
- else
- {
- s_returnCode = WriteEventErrorCode.NullInput;
- return false;
- }
- }
-
- // update argCount based on actual number of arguments written to 'userData'
- argCount = (int)(userDataPtr - userData);
-
- if (totalEventSize > s_traceEventMaximumSize)
- {
- s_returnCode = WriteEventErrorCode.EventTooBig;
- return false;
- }
-
- // the optimized path (using "fixed" instead of allocating pinned GCHandles
- if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount))
- {
- // Fast path: at most 8 string arguments
-
- // ensure we have at least s_etwAPIMaxStringCount in dataString, so that
- // the "fixed" statement below works
- while (refObjIndex < s_etwAPIMaxRefObjCount)
- {
- dataRefObj.Add(null);
- ++refObjIndex;
- }
-
- //
- // now fix any string arguments and set the pointer on the data descriptor
- //
- fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3],
- v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7])
- {
- userDataPtr = (EventData*)userData;
- if (dataRefObj[0] != null)
- {
- userDataPtr[refObjPosition[0]].Ptr = (ulong)v0;
- }
- if (dataRefObj[1] != null)
- {
- userDataPtr[refObjPosition[1]].Ptr = (ulong)v1;
- }
- if (dataRefObj[2] != null)
- {
- userDataPtr[refObjPosition[2]].Ptr = (ulong)v2;
- }
- if (dataRefObj[3] != null)
- {
- userDataPtr[refObjPosition[3]].Ptr = (ulong)v3;
- }
- if (dataRefObj[4] != null)
- {
- userDataPtr[refObjPosition[4]].Ptr = (ulong)v4;
- }
- if (dataRefObj[5] != null)
- {
- userDataPtr[refObjPosition[5]].Ptr = (ulong)v5;
- }
- if (dataRefObj[6] != null)
- {
- userDataPtr[refObjPosition[6]].Ptr = (ulong)v6;
- }
- if (dataRefObj[7] != null)
- {
- userDataPtr[refObjPosition[7]].Ptr = (ulong)v7;
- }
-
- status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
- }
- }
- else
- {
- // Slow path: use pinned handles
- userDataPtr = (EventData*)userData;
-
- GCHandle[] rgGCHandle = new GCHandle[refObjIndex];
- for (int i = 0; i < refObjIndex; ++i)
- {
- // below we still use "fixed" to avoid taking dependency on the offset of the first field
- // in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject)
- rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned);
- if (dataRefObj[i] is string)
- {
- fixed (char* p = (string)dataRefObj[i])
- userDataPtr[refObjPosition[i]].Ptr = (ulong)p;
- }
- else
- {
- fixed (byte* p = (byte[])dataRefObj[i])
- userDataPtr[refObjPosition[i]].Ptr = (ulong)p;
- }
- }
-
- status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
-
- for (int i = 0; i < refObjIndex; ++i)
- {
- rgGCHandle[i].Free();
- }
- }
- }
- }
-
- if (status != 0)
- {
- SetLastError((int)status);
- return false;
- }
-
- return true;
- }
-
- /// <summary>
- /// WriteEvent, method to be used by generated code on a derived class
- /// </summary>
- /// <param name="eventDescriptor">
- /// Event Descriptor for this event.
- /// </param>
- /// <param name="activityID">
- /// A pointer to the activity ID to log
- /// </param>
- /// <param name="childActivityID">
- /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity
- /// This can be null for events that do not generate a child activity.
- /// </param>
- /// <param name="dataCount">
- /// number of event descriptors
- /// </param>
- /// <param name="data">
- /// pointer do the event data
- /// </param>
- // <SecurityKernel Critical="True" Ring="0">
- // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
- // </SecurityKernel>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
- {
- if (childActivityID != null)
- {
- // activity transfers are supported only for events that specify the Send or Receive opcode
- Debug.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
- (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive ||
- (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start ||
- (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
- }
-
- int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data);
-
- if (status != 0)
- {
- SetLastError(status);
- return false;
- }
- return true;
- }
-
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
- internal unsafe bool WriteEventRaw(
- ref EventDescriptor eventDescriptor,
- Guid* activityID,
- Guid* relatedActivityID,
- int dataCount,
- IntPtr data)
- {
- int status;
-
- status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(
- m_regHandle,
- ref eventDescriptor,
- activityID,
- relatedActivityID,
- dataCount,
- (EventData*)data);
-
- if (status != 0)
- {
- SetLastError(status);
- return false;
- }
- return true;
- }
-
-
- // 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)
- {
- m_providerId = providerId;
- m_etwCallback = enableCallback;
- return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
- }
-
- private uint EventUnregister(long registrationHandle)
- {
- return UnsafeNativeMethods.ManifestEtw.EventUnregister(registrationHandle);
- }
-
- static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
- private static int bitcount(uint n)
- {
- int count = 0;
- for (; n != 0; n = n >> 4)
- count += nibblebits[n & 0x0f];
- return count;
- }
- private static int bitindex(uint n)
- {
- Debug.Assert(bitcount(n) == 1);
- int idx = 0;
- while ((n & (1 << idx)) == 0)
- idx++;
- return idx;
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
deleted file mode 100644
index a558a1647e..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource.cs
+++ /dev/null
@@ -1,6912 +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.
-
-// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
-// It is available from http://www.codeplex.com/hyperAddin
-#if !PLATFORM_UNIX
-
-#define FEATURE_MANAGED_ETW
-
-#if !ES_BUILD_STANDALONE && !CORECLR && !PROJECTN
-#define FEATURE_ACTIVITYSAMPLING
-#endif // !ES_BUILD_STANDALONE
-
-#endif // !PLATFORM_UNIX
-
-#if ES_BUILD_STANDALONE
-#define FEATURE_MANAGED_ETW_CHANNELS
-// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
-#endif
-
-/* DESIGN NOTES DESIGN NOTES DESIGN NOTES DESIGN NOTES */
-// DESIGN NOTES
-// Over the years EventSource has become more complex and so it is important to understand
-// the basic structure of the code to insure that it does not grow more complex.
-//
-// Basic Model
-//
-// PRINCIPLE: EventSource - ETW decoupling
-//
-// Conceptually and EventSouce is something takes event logging data from the source methods
-// To the EventListener that can subscribe them. Note that CONCEPTUALLY EVENTSOURCES DON'T
-// KNOW ABOUT ETW!. The MODEL of the system is that there is a special EventListern Which
-// we will call the EtwEventListener, that forwards commands from ETW to EventSources and
-// listeners to the EventSources and forwards on those events to ETW. THus the model should
-// be that you DON'T NEED ETW.
-//
-// Now in actual practice, EventSouce have rather intimate knowledge of ETW and send events
-// to it directly, but this can be VIEWED AS AN OPTIMIATION.
-//
-// Basic Event Data Flow:
-//
-// There are two ways for event Data to enter the system
-// 1) WriteEvent* and friends. This is called the 'contract' based approach because
-// you write a method per event which forms a contract that is know at compile time.
-// In this scheme each event is given an EVENTID (small integer). which is its identity
-// 2) Write<T> methods. This is called the 'dynamic' approach because new events
-// can be created on the fly. Event identity is determined by the event NAME, and these
-// are not quite as efficient at runtime since you have at least a hash table lookup
-// on every event write.
-//
-// EventSource-EventListener transfer fully support both ways of writing events (either contract
-// based (WriteEvent*) or dynamic (Write<T>). Both way fully support the same set of data
-// types. It is suggested, however, that you use the contract based approach when the event scheme
-// is known at compile time (that is whenever possible). It is more efficient, but more importantly
-// it makes the contract very explicit, and centralizes all policy about logging. These are good
-// things. The Write<T> API is really meant for more ad-hoc
-//
-// Allowed Data.
-//
-// Note that EventSource-EventListeners have a conceptual serialization-deserialization that happens
-// during the transfer. In particular object identity is not preserved, some objects are morphed,
-// and not all data types are supported. In particular you can pass
-//
-// A Valid type to log to an EventSource include
-// * Primitive data types
-// * IEnumerable<T> of valid types T (this include arrays) (* New for V4.6)
-// * Explicitly Opted in class or struct with public property Getters over Valid types. (* New for V4.6)
-//
-// This set of types is roughly a generalization of JSON support (Basically primitives, bags, and arrays).
-//
-// Explicitly allowed structs include (* New for V4.6)
-// * Marked with the EventData attribute
-// * implicitly defined (e.g the C# new {x = 3, y = 5} syntax)
-// * KeyValuePair<K,V> (thus dictionaries can be passed since they are an IEnumerable of KeyValuePair)
-//
-// When classes are returned in an EventListener, what is returned is something that implements
-// IDictionary<string, T>. Thus when objects are passed to an EventSource they are transformed
-// into a key-value bag (the IDictionary<string, T>) for consumption in the listener. These
-// are obvious NOT the original objects.
-//
-// ETWserialization formats:
-//
-// As mentioned conceptually EventSource's send data to EventListeners and there is a conceptual
-// copy/morph of that data as described above. In addition the .NET framework supports a conceptual
-// ETWListener that will send the data to then ETW stream. If you use this feature, the data needs
-// to be serialized in a way that ETW supports. ETW supports the following serialization formats
-//
-// 1) Manifest Based serialization.
-// 2) SelfDescribing serialization (TraceLogging style in the TraceLogging directory)
-//
-// A key factor is that the Write<T> method, which support on the fly definition of events, can't
-// support the manifest based serialization because the manifest needs the schema of all events
-// to be known before any events are emitted. This implies the following
-//
-// If you use Write<T> and the output goes to ETW it will use the SelfDescribing format.
-// If you use the EventSource(string) constructor for an eventSource (in which you don't
-// create a subclass), the default is also to use Self-Describing serialization. In addition
-// you can use the EventSoruce(EventSourceSettings) constructor to also explicitly specify
-// Self-Describing serialization format. These effect the WriteEvent* APIs going to ETW.
-//
-// Note that none of this ETW serialization logic affects EventListeners. Only the ETW listener.
-//
-// *************************************************************************************
-// *** INTERNALS: Event Propagation
-//
-// Data enters the system either though
-//
-// 1) A user defined method in the user defined subclass of EventSource which calls
-// A) A typesafe type specific overload of WriteEvent(ID, ...) e.g. WriteEvent(ID, string, string)
-// * which calls into the unsafe WriteEventCore(ID COUNT EventData*) WriteEventWithRelatedActivityIdCore()
-// B) The typesafe overload WriteEvent(ID, object[]) which calls the private helper WriteEventVarargs(ID, Guid* object[])
-// C) Directly into the unsafe WriteEventCore(ID, COUNT EventData*) or WriteEventWithRelatedActivityIdCore()
-//
-// All event data eventually flows to one of
-// * WriteEventWithRelatedActivityIdCore(ID, Guid*, COUNT, EventData*)
-// * WriteEventVarargs(ID, Guid*, object[])
-//
-// 2) A call to one of the overloads of Write<T>. All these overloads end up in
-// * WriteImpl<T>(EventName, Options, Data, Guid*, Guid*)
-//
-// On output there are the following routines
-// Writing to all listeners that are NOT ETW, we have the following routines
-// * WriteToAllListeners(ID, Guid*, COUNT, EventData*)
-// * WriteToAllListeners(ID, Guid*, object[])
-// * WriteToAllListeners(NAME, Guid*, EventPayload)
-//
-// EventPayload is the internal type that implements the IDictionary<string, object> interface
-// The EventListeners will pass back for serialized classes for nested object, but
-// WriteToAllListeners(NAME, Guid*, EventPayload) unpacks this uses the fields as if they
-// were parameters to a method.
-//
-// The first two are used for the WriteEvent* case, and the later is used for the Write<T> case.
-//
-// Writing to ETW, Manifest Based
-// EventProvider.WriteEvent(EventDescriptor, Guid*, COUNT, EventData*)
-// EventProvider.WriteEvent(EventDescriptor, Guid*, object[])
-// Writing to ETW, Self-Describing format
-// WriteMultiMerge(NAME, Options, Types, EventData*)
-// WriteMultiMerge(NAME, Options, Types, object[])
-// WriteImpl<T> has logic that knows how to serialize (like WriteMultiMerge) but also knows
-// will write it to
-//
-// All ETW writes eventually call
-// EventWriteTransfer (native PINVOKE wrapper)
-// EventWriteTransferWrapper (fixes compat problem if you pass null as the related activityID)
-// EventProvider.WriteEventRaw - sets last error
-// EventSource.WriteEventRaw - Does EventSource exception handling logic
-// WriteMultiMerge
-// WriteImpl<T>
-// EventProvider.WriteEvent(EventDescriptor, Guid*, COUNT, EventData*)
-// EventProvider.WriteEvent(EventDescriptor, Guid*, object[])
-//
-// Serialization: We have a bit of a hodge-podge of serializers right now. Only the one for ETW knows
-// how to deal with nested classes or arrays. I will call this serializer the 'TypeInfo' serializer
-// since it is the TraceLoggingTypeInfo structure that knows how to do this. Effectively for a type you
-// can call one of these
-// WriteMetadata - transforms the type T into serialization meta data blob for that type
-// WriteObjectData - transforms an object of T into serialization meta data blob for that type
-// GetData - transforms an object of T into its deserialized form suitable for passing to EventListener.
-// The first two are used to serialize something for ETW. The second one is used to transform the object
-// for use by the EventListener. We also have a 'DecodeObject' method that will take a EventData* and
-// deserialize to pass to an EventListener, but it only works on primitive types (types supported in version V4.5).
-//
-// It is an important observation that while EventSource does support users directly calling with EventData*
-// blobs, we ONLY support that for the primitive types (V4.5 level support). Thus while there is a EventData*
-// path through the system it is only for some types. The object[] path is the more general (but less efficient) path.
-//
-// TODO There is cleanup needed There should be no divergence until WriteEventRaw.
-//
-// TODO: We should have a single choke point (right now we always have this parallel EventData* and object[] path. This
-// was historical (at one point we tried to pass object directly from EventSoruce to EventListener. That was always
-// fragile and a compatibility headache, but we have finally been forced into the idea that there is always a transformation.
-// This allows us to use the EventData* form to be the canonical data format in the low level APIs. This also gives us the
-// opportunity to expose this format to EventListeners in the future.
-//
-using System;
-using System.Runtime.CompilerServices;
-#if FEATURE_ACTIVITYSAMPLING
-using System.Collections.Concurrent;
-#endif
-using System.Collections.Generic;
-using System.Collections.ObjectModel;
-using System.Diagnostics;
-using System.Diagnostics.CodeAnalysis;
-using System.Globalization;
-using System.Reflection;
-using System.Resources;
-using System.Security;
-#if !CORECLR
-using System.Security.Permissions;
-#endif // !CORECLR
-
-using System.Text;
-using System.Threading;
-using Microsoft.Win32;
-
-#if ES_BUILD_STANDALONE
-using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
-#else
-using System.Threading.Tasks;
-#endif
-
-using Microsoft.Reflection;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// This class is meant to be inherited by a user-defined event source in order to define a managed
- /// ETW provider. Please See DESIGN NOTES above for the internal architecture.
- /// The minimal definition of an EventSource simply specifies a number of ETW event methods that
- /// call one of the EventSource.WriteEvent overloads, <see cref="EventSource.WriteEventCore"/>,
- /// or <see cref="EventSource.WriteEventWithRelatedActivityIdCore"/> to log them. This functionality
- /// is sufficient for many users.
- /// <para>
- /// To achieve more control over the ETW provider manifest exposed by the event source type, the
- /// [<see cref="EventAttribute"/>] attributes can be specified for the ETW event methods.
- /// </para><para>
- /// For very advanced EventSources, it is possible to intercept the commands being given to the
- /// eventSource and change what filtering is done (see EventListener.EnableEvents and
- /// <see cref="EventListener.DisableEvents"/>) or cause actions to be performed by the eventSource,
- /// e.g. dumping a data structure (see EventSource.SendCommand and
- /// <see cref="EventSource.OnEventCommand"/>).
- /// </para><para>
- /// The eventSources can be turned on with Windows ETW controllers (e.g. logman), immediately.
- /// It is also possible to control and intercept the data dispatcher programmatically. See
- /// <see cref="EventListener"/> for more.
- /// </para>
- /// </summary>
- /// <remarks>
- /// This is a minimal definition for a custom event source:
- /// <code>
- /// [EventSource(Name="Samples-Demos-Minimal")]
- /// sealed class MinimalEventSource : EventSource
- /// {
- /// public static MinimalEventSource Log = new MinimalEventSource();
- /// public void Load(long ImageBase, string Name) { WriteEvent(1, ImageBase, Name); }
- /// public void Unload(long ImageBase) { WriteEvent(2, ImageBase); }
- /// private MinimalEventSource() {}
- /// }
- /// </code>
- /// </remarks>
- public partial class EventSource : IDisposable
- {
-
-#if FEATURE_EVENTSOURCE_XPLAT
- private static readonly EventListener persistent_Xplat_Listener = XplatEventLogger.InitializePersistentListener();
-#endif //FEATURE_EVENTSOURCE_XPLAT
-
- /// <summary>
- /// The human-friendly name of the eventSource. It defaults to the simple name of the class
- /// </summary>
- public string Name { get { return m_name; } }
- /// <summary>
- /// Every eventSource is assigned a GUID to uniquely identify it to the system.
- /// </summary>
- public Guid Guid { get { return m_guid; } }
-
- /// <summary>
- /// Returns true if the eventSource has been enabled at all. This is the prefered 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")]
- public bool IsEnabled()
- {
- return m_eventSourceEnabled;
- }
-
- /// <summary>
- /// Returns true if events with greater than or equal 'level' and have one of 'keywords' set are enabled.
- ///
- /// Note that the result of this function is only an approximation on whether a particular
- /// event is active or not. It is only meant to be used as way of avoiding expensive
- /// computation for logging when logging is not on, therefore it sometimes returns false
- /// positives (but is always accurate when returning false). EventSources are free to
- /// have additional filtering.
- /// </summary>
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- public bool IsEnabled(EventLevel level, EventKeywords keywords)
- {
- return IsEnabled(level, keywords, EventChannel.None);
- }
-
- /// <summary>
- /// Returns true if events with greater than or equal 'level' and have one of 'keywords' set are enabled, or
- /// if 'keywords' specifies a channel bit for a channel that is enabled.
- ///
- /// Note that the result of this function only an approximation on whether a particular
- /// event is active or not. It is only meant to be used as way of avoiding expensive
- /// computation for logging when logging is not on, therefore it sometimes returns false
- /// positives (but is always accurate when returning false). EventSources are free to
- /// have additional filtering.
- /// </summary>
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- public bool IsEnabled(EventLevel level, EventKeywords keywords, EventChannel channel)
- {
- if (!m_eventSourceEnabled)
- return false;
-
- if (!IsEnabledCommon(m_eventSourceEnabled, m_level, m_matchAnyKeyword, level, keywords, channel))
- return false;
-
-#if !FEATURE_ACTIVITYSAMPLING
-
- return true;
-
-#else // FEATURE_ACTIVITYSAMPLING
-
- return true;
-
-#if OPTIMIZE_IS_ENABLED
- //================================================================================
- // 2013/03/06 - The code below is a possible optimization for IsEnabled(level, kwd)
- // in case activity tracing/sampling is enabled. The added complexity of this
- // code however weighs against having it "on" until we know it's really needed.
- // For now we'll have this #ifdef-ed out in case we see evidence this is needed.
- //================================================================================
-
- // At this point we believe the event is enabled, however we now need to check
- // if we filter because of activity
-
- // Optimization, all activity filters also register a delegate here, so if there
- // is no delegate, we know there are no activity filters, which means that there
- // is no additional filtering, which means that we can return true immediately.
- if (s_activityDying == null)
- return true;
-
- // if there's at least one legacy ETW listener we can't filter this
- if (m_legacySessions != null && m_legacySessions.Count > 0)
- return true;
-
- // if any event ID that triggers a new activity, or "transfers" activities
- // is covered by 'keywords' we can't filter this
- if (unchecked(((long)keywords & m_keywordTriggers)) != 0)
- return true;
-
- // See if all listeners have activity filters that would block the event.
- for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId)
- {
- EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId];
- if (etwSession == null)
- continue;
-
- ActivityFilter activityFilter = etwSession.m_activityFilter;
- if (activityFilter == null ||
- ActivityFilter.GetFilter(activityFilter, this) == null)
- {
- // No activity filter for ETW, if event is active for ETW, we can't filter.
- for (int i = 0; i < m_eventData.Length; i++)
- if (m_eventData[i].EnabledForETW)
- return true;
- }
- else if (ActivityFilter.IsCurrentActivityActive(activityFilter))
- return true;
- }
-
- // for regular event listeners
- var curDispatcher = m_Dispatchers;
- while (curDispatcher != null)
- {
- ActivityFilter activityFilter = curDispatcher.m_Listener.m_activityFilter;
- if (activityFilter == null)
- {
- // See if any event is enabled.
- for (int i = 0; i < curDispatcher.m_EventEnabled.Length; i++)
- if (curDispatcher.m_EventEnabled[i])
- return true;
- }
- else if (ActivityFilter.IsCurrentActivityActive(activityFilter))
- return true;
- curDispatcher = curDispatcher.m_Next;
- }
-
- // Every listener has an activity filter that is blocking writing the event,
- // thus the event is not enabled.
- return false;
-#endif // OPTIMIZE_IS_ENABLED
-
-#endif // FEATURE_ACTIVITYSAMPLING
- }
-
- /// <summary>
- /// Returns the settings for the event source instance
- /// </summary>
- public EventSourceSettings Settings
- {
- get { return m_config; }
- }
-
- // Manifest support
- /// <summary>
- /// Returns the GUID that uniquely identifies the eventSource defined by 'eventSourceType'.
- /// This API allows you to compute this without actually creating an instance of the EventSource.
- /// It only needs to reflect over the type.
- /// </summary>
- public static Guid GetGuid(Type eventSourceType)
- {
- if (eventSourceType == null)
- throw new ArgumentNullException(nameof(eventSourceType));
- Contract.EndContractBlock();
-
- EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute));
- string name = eventSourceType.Name;
- if (attrib != null)
- {
- if (attrib.Guid != null)
- {
- Guid g = Guid.Empty;
-#if !ES_BUILD_AGAINST_DOTNET_V35
- if (Guid.TryParse(attrib.Guid, out g))
- return g;
-#else
- try { return new Guid(attrib.Guid); }
- catch (Exception) { }
-#endif
- }
-
- if (attrib.Name != null)
- name = attrib.Name;
- }
-
- if (name == null)
- {
- throw new ArgumentException(Resources.GetResourceString("Argument_InvalidTypeName"), nameof(eventSourceType));
- }
- return GenerateGuidFromName(name.ToUpperInvariant()); // Make it case insensitive.
- }
- /// <summary>
- /// Returns the official ETW Provider name for the eventSource defined by 'eventSourceType'.
- /// This API allows you to compute this without actually creating an instance of the EventSource.
- /// It only needs to reflect over the type.
- /// </summary>
- public static string GetName(Type eventSourceType)
- {
- return GetName(eventSourceType, EventManifestOptions.None);
- }
-
- /// <summary>
- /// Returns a string of the XML manifest associated with the eventSourceType. The scheme for this XML is
- /// documented at in EventManifest Schema http://msdn.microsoft.com/en-us/library/aa384043(VS.85).aspx.
- /// This is the preferred way of generating a manifest to be embedded in the ETW stream as it is fast and
- /// the fact that it only includes localized entries for the current UI culture is an acceptable tradeoff.
- /// </summary>
- /// <param name="eventSourceType">The type of the event source class for which the manifest is generated</param>
- /// <param name="assemblyPathToIncludeInManifest">The manifest XML fragment contains the string name of the DLL name in
- /// which it is embedded. This parameter specifies what name will be used</param>
- /// <returns>The XML data string</returns>
- public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest)
- {
- return GenerateManifest(eventSourceType, assemblyPathToIncludeInManifest, EventManifestOptions.None);
- }
- /// <summary>
- /// Returns a string of the XML manifest associated with the eventSourceType. The scheme for this XML is
- /// documented at in EventManifest Schema http://msdn.microsoft.com/en-us/library/aa384043(VS.85).aspx.
- /// Pass EventManifestOptions.AllCultures when generating a manifest to be registered on the machine. This
- /// ensures that the entries in the event log will be "optimally" localized.
- /// </summary>
- /// <param name="eventSourceType">The type of the event source class for which the manifest is generated</param>
- /// <param name="assemblyPathToIncludeInManifest">The manifest XML fragment contains the string name of the DLL name in
- /// which it is embedded. This parameter specifies what name will be used</param>
- /// <param name="flags">The flags to customize manifest generation. If flags has bit OnlyIfNeededForRegistration specified
- /// this returns null when the eventSourceType does not require explicit registration</param>
- /// <returns>The XML data string or null</returns>
- public static string GenerateManifest(Type eventSourceType, string assemblyPathToIncludeInManifest, EventManifestOptions flags)
- {
- if (eventSourceType == null)
- throw new ArgumentNullException(nameof(eventSourceType));
- Contract.EndContractBlock();
-
- byte[] manifestBytes = EventSource.CreateManifestAndDescriptors(eventSourceType, assemblyPathToIncludeInManifest, null, flags);
- return (manifestBytes == null) ? null : Encoding.UTF8.GetString(manifestBytes, 0, manifestBytes.Length);
- }
-
- // EventListener support
- /// <summary>
- /// returns a list (IEnumerable) of all sources in the appdomain). EventListeners typically need this.
- /// </summary>
- /// <returns></returns>
- public static IEnumerable<EventSource> GetSources()
- {
- var ret = new List<EventSource>();
- lock (EventListener.EventListenersLock)
- {
- foreach (WeakReference eventSourceRef in EventListener.s_EventSources)
- {
- EventSource eventSource = eventSourceRef.Target as EventSource;
- if (eventSource != null && !eventSource.IsDisposed)
- ret.Add(eventSource);
- }
- }
- return ret;
- }
-
- /// <summary>
- /// Send a command to a particular EventSource identified by 'eventSource'.
- /// Calling this routine simply forwards the command to the EventSource.OnEventCommand
- /// callback. What the EventSource does with the command and its arguments are from
- /// that point EventSource-specific.
- /// </summary>
- /// <param name="eventSource">The instance of EventSource to send the command to</param>
- /// <param name="command">A positive user-defined EventCommand, or EventCommand.SendManifest</param>
- /// <param name="commandArguments">A set of (name-argument, value-argument) pairs associated with the command</param>
- public static void SendCommand(EventSource eventSource, EventCommand command, IDictionary<string, string> commandArguments)
- {
- if (eventSource == null)
- throw new ArgumentNullException(nameof(eventSource));
-
- // User-defined EventCommands should not conflict with the reserved commands.
- if ((int)command <= (int)EventCommand.Update && (int)command != (int)EventCommand.SendManifest)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_InvalidCommand"), nameof(command));
- }
-
- eventSource.SendCommand(null, 0, 0, command, true, EventLevel.LogAlways, EventKeywords.None, commandArguments);
- }
-
-#if !ES_BUILD_STANDALONE
- /// <summary>
- /// This property allows EventSource code to appropriately handle as "different"
- /// activities started on different threads that have not had an activity created on them.
- /// </summary>
- internal static Guid InternalCurrentThreadActivityId
- {
- get
- {
- Guid retval = CurrentThreadActivityId;
- if (retval == Guid.Empty)
- {
- retval = FallbackActivityId;
- }
- return retval;
- }
- }
-
- internal static Guid FallbackActivityId
- {
- get
- {
-#pragma warning disable 612, 618
- int threadID = AppDomain.GetCurrentThreadId();
-
- // Managed thread IDs are more aggressively re-used than native thread IDs,
- // so we'll use the latter...
- return new Guid(unchecked((uint)threadID),
- unchecked((ushort)s_currentPid), unchecked((ushort)(s_currentPid >> 16)),
- 0x94, 0x1b, 0x87, 0xd5, 0xa6, 0x5c, 0x36, 0x64);
-#pragma warning restore 612, 618
- }
- }
-#endif // !ES_BUILD_STANDALONE
-
- // Error APIs. (We don't throw by default, but you can probe for status)
- /// <summary>
- /// Because
- ///
- /// 1) Logging is often optional and thus should not generate fatal errors (exceptions)
- /// 2) EventSources are often initialized in class constructors (which propagate exceptions poorly)
- ///
- /// The event source constructor does not throw exceptions. Instead we remember any exception that
- /// was generated (it is also logged to Trace.WriteLine).
- /// </summary>
- public Exception ConstructionException { get { return m_constructionException; } }
-
- /// <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
- /// 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>
- public string GetTrait(string key)
- {
- if (m_traits != null)
- {
- for (int i = 0; i < m_traits.Length - 1; i += 2)
- {
- if (m_traits[i] == key)
- return m_traits[i + 1];
- }
- }
- return null;
- }
-
- /// <summary>
- /// Displays the name and GUID for the eventSource for debugging purposes.
- /// </summary>
- public override string ToString()
- {
- return Resources.GetResourceString("EventSource_ToString", Name, Guid);
- }
-
- /// <summary>
- /// Fires when a Command (e.g. Enable) comes from a an EventListener.
- /// </summary>
- public event EventHandler<EventCommandEventArgs> EventCommandExecuted
- {
- add
- {
- m_eventCommandExecuted += value;
-
- // If we have an EventHandler<EventCommandEventArgs> attached to the EventSource before the first command arrives
- // It should get a chance to handle the deferred commands.
- EventCommandEventArgs deferredCommands = m_deferredCommands;
- while (deferredCommands != null)
- {
- value(this, deferredCommands);
- deferredCommands = deferredCommands.nextCommand;
- }
- }
- remove
- {
- m_eventCommandExecuted -= value;
- }
- }
-
- #region protected
- /// <summary>
- /// This is the constructor that most users will use to create their eventSource. It takes
- /// no parameters. The ETW provider name and GUID of the EventSource are determined by the EventSource
- /// custom attribute (so you can determine these things declaratively). If the GUID for the eventSource
- /// is not specified in the EventSourceAttribute (recommended), it is Generated by hashing the name.
- /// If the ETW provider name of the EventSource is not given, the name of the EventSource class is used as
- /// the ETW provider name.
- /// </summary>
- protected EventSource()
- : this(EventSourceSettings.EtwManifestEventFormat)
- {
- }
-
- /// <summary>
- /// By default calling the 'WriteEvent' methods do NOT throw on errors (they silently discard the event).
- /// This is because in most cases users assume logging is not 'precious' and do NOT wish to have logging failures
- /// crash the program. However for those applications where logging is 'precious' and if it fails the caller
- /// wishes to react, setting 'throwOnEventWriteErrors' will cause an exception to be thrown if WriteEvent
- /// fails. Note the fact that EventWrite succeeds does not necessarily mean that the event reached its destination
- /// only that operation of writing it did not fail. These EventSources will not generate self-describing ETW events.
- ///
- /// For compatibility only use the EventSourceSettings.ThrowOnEventWriteErrors flag instead.
- /// </summary>
- // [Obsolete("Use the EventSource(EventSourceSettings) overload")]
- protected EventSource(bool throwOnEventWriteErrors)
- : this(EventSourceSettings.EtwManifestEventFormat | (throwOnEventWriteErrors ? EventSourceSettings.ThrowOnEventWriteErrors : 0))
- { }
-
- /// <summary>
- /// Construct an EventSource with additional non-default settings (see EventSourceSettings for more)
- /// </summary>
- protected EventSource(EventSourceSettings settings) : this(settings, null) { }
-
- /// <summary>
- /// Construct an EventSource with additional non-default settings.
- ///
- /// 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).
- /// </summary>
- /// <param name="settings">See EventSourceSettings for more.</param>
- /// <param name="traits">A collection of key-value strings (must be an even number).</param>
- protected EventSource(EventSourceSettings settings, params string[] traits)
- {
- m_config = ValidateSettings(settings);
-
- Guid eventSourceGuid;
- string eventSourceName;
-
- EventMetadata[] eventDescriptors;
- byte[] manifest;
- GetMetadata(out eventSourceGuid, out eventSourceName, out eventDescriptors, out manifest);
-
- if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null)
- {
- var myType = this.GetType();
- eventSourceGuid = GetGuid(myType);
- eventSourceName = GetName(myType);
- }
-
- Initialize(eventSourceGuid, eventSourceName, traits);
- }
-
- internal virtual void GetMetadata(out Guid eventSourceGuid, out string eventSourceName, out EventMetadata[] eventData, out byte[] manifestBytes)
- {
- //
- // In ProjectN subclasses need to override this method, and return the data from their EventSourceAttribute and EventAttribute annotations.
- // On other architectures it is a no-op.
- //
- // eventDescriptors needs to contain one EventDescriptor for each event; the event's ID should be the same as its index in this array.
- // manifestBytes is a UTF-8 encoding of the ETW manifest for the type.
- //
- // This will be implemented by an IL rewriter, so we can't make this method abstract or the initial build of the subclass would fail.
- //
- eventSourceGuid = Guid.Empty;
- eventSourceName = null;
- eventData = null;
- manifestBytes = null;
-
- return;
- }
-
- /// <summary>
- /// This method is called when the eventSource is updated by the controller.
- /// </summary>
- protected virtual void OnEventCommand(EventCommandEventArgs command) { }
-
-#pragma warning disable 1591
- // optimized for common signatures (no args)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId)
- {
- WriteEventCore(eventId, 0, null);
- }
-
- // optimized for common signatures (ints)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, int arg1)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[1];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 4;
- WriteEventCore(eventId, 1, descrs);
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, int arg1, int arg2)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 4;
- WriteEventCore(eventId, 2, descrs);
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, int arg1, int arg2, int arg3)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 4;
- descrs[2].DataPointer = (IntPtr)(&arg3);
- descrs[2].Size = 4;
- WriteEventCore(eventId, 3, descrs);
- }
- }
-
- // optimized for common signatures (longs)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, long arg1)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[1];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 8;
- WriteEventCore(eventId, 1, descrs);
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, long arg1, long arg2)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 8;
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 8;
- WriteEventCore(eventId, 2, descrs);
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, long arg1, long arg2, long arg3)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 8;
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 8;
- descrs[2].DataPointer = (IntPtr)(&arg3);
- descrs[2].Size = 8;
- WriteEventCore(eventId, 3, descrs);
- }
- }
-
- // optimized for common signatures (strings)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, string arg1)
- {
- if (m_eventSourceEnabled)
- {
- if (arg1 == null) arg1 = "";
- fixed (char* string1Bytes = arg1)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[1];
- descrs[0].DataPointer = (IntPtr)string1Bytes;
- descrs[0].Size = ((arg1.Length + 1) * 2);
- WriteEventCore(eventId, 1, descrs);
- }
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, string arg1, string arg2)
- {
- if (m_eventSourceEnabled)
- {
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- fixed (char* string1Bytes = arg1)
- fixed (char* string2Bytes = arg2)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)string1Bytes;
- descrs[0].Size = ((arg1.Length + 1) * 2);
- descrs[1].DataPointer = (IntPtr)string2Bytes;
- descrs[1].Size = ((arg2.Length + 1) * 2);
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, string arg1, string arg2, string arg3)
- {
- if (m_eventSourceEnabled)
- {
- if (arg1 == null) arg1 = "";
- if (arg2 == null) arg2 = "";
- if (arg3 == null) arg3 = "";
- fixed (char* string1Bytes = arg1)
- fixed (char* string2Bytes = arg2)
- fixed (char* string3Bytes = arg3)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
- descrs[0].DataPointer = (IntPtr)string1Bytes;
- descrs[0].Size = ((arg1.Length + 1) * 2);
- descrs[1].DataPointer = (IntPtr)string2Bytes;
- descrs[1].Size = ((arg2.Length + 1) * 2);
- descrs[2].DataPointer = (IntPtr)string3Bytes;
- descrs[2].Size = ((arg3.Length + 1) * 2);
- WriteEventCore(eventId, 3, descrs);
- }
- }
- }
-
- // optimized for common signatures (string and ints)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, string arg1, int arg2)
- {
- if (m_eventSourceEnabled)
- {
- if (arg1 == null) arg1 = "";
- fixed (char* string1Bytes = arg1)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)string1Bytes;
- descrs[0].Size = ((arg1.Length + 1) * 2);
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 4;
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, string arg1, int arg2, int arg3)
- {
- if (m_eventSourceEnabled)
- {
- if (arg1 == null) arg1 = "";
- fixed (char* string1Bytes = arg1)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
- descrs[0].DataPointer = (IntPtr)string1Bytes;
- descrs[0].Size = ((arg1.Length + 1) * 2);
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 4;
- descrs[2].DataPointer = (IntPtr)(&arg3);
- descrs[2].Size = 4;
- WriteEventCore(eventId, 3, descrs);
- }
- }
- }
-
- // optimized for common signatures (string and longs)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, string arg1, long arg2)
- {
- if (m_eventSourceEnabled)
- {
- if (arg1 == null) arg1 = "";
- fixed (char* string1Bytes = arg1)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)string1Bytes;
- descrs[0].Size = ((arg1.Length + 1) * 2);
- descrs[1].DataPointer = (IntPtr)(&arg2);
- descrs[1].Size = 8;
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
-
- // optimized for common signatures (long and string)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, long arg1, string arg2)
- {
- if (m_eventSourceEnabled)
- {
- if (arg2 == null) arg2 = "";
- fixed (char* string2Bytes = arg2)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 8;
- descrs[1].DataPointer = (IntPtr)string2Bytes;
- descrs[1].Size = ((arg2.Length + 1) * 2);
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
-
- // optimized for common signatures (int and string)
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, int arg1, string arg2)
- {
- if (m_eventSourceEnabled)
- {
- if (arg2 == null) arg2 = "";
- fixed (char* string2Bytes = arg2)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)string2Bytes;
- descrs[1].Size = ((arg2.Length + 1) * 2);
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, byte[] arg1)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- if (arg1 == null || arg1.Length == 0)
- {
- int blobSize = 0;
- descrs[0].DataPointer = (IntPtr)(&blobSize);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty content
- descrs[1].Size = 0;
- WriteEventCore(eventId, 2, descrs);
- }
- else
- {
- int blobSize = arg1.Length;
- fixed (byte* blob = &arg1[0])
- {
- descrs[0].DataPointer = (IntPtr)(&blobSize);
- descrs[0].Size = 4;
- descrs[1].DataPointer = (IntPtr)blob;
- descrs[1].Size = blobSize;
- WriteEventCore(eventId, 2, descrs);
- }
- }
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, long arg1, byte[] arg2)
- {
- if (m_eventSourceEnabled)
- {
- EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
- descrs[0].DataPointer = (IntPtr)(&arg1);
- descrs[0].Size = 8;
- if (arg2 == null || arg2.Length == 0)
- {
- int blobSize = 0;
- descrs[1].DataPointer = (IntPtr)(&blobSize);
- descrs[1].Size = 4;
- descrs[2].DataPointer = (IntPtr)(&blobSize); // valid address instead of empty contents
- descrs[2].Size = 0;
- WriteEventCore(eventId, 3, descrs);
- }
- else
- {
- int blobSize = arg2.Length;
- fixed (byte* blob = &arg2[0])
- {
- descrs[1].DataPointer = (IntPtr)(&blobSize);
- descrs[1].Size = 4;
- descrs[2].DataPointer = (IntPtr)blob;
- descrs[2].Size = blobSize;
- WriteEventCore(eventId, 3, descrs);
- }
- }
- }
- }
-
-#pragma warning restore 1591
-
- /// <summary>
- /// Used to construct the data structure to be passed to the native ETW APIs - EventWrite and EventWriteTransfer.
- /// </summary>
- protected internal struct EventData
- {
- /// <summary>
- /// Address where the one argument lives (if this points to managed memory you must ensure the
- /// managed object is pinned.
- /// </summary>
- public IntPtr DataPointer { get { return (IntPtr)m_Ptr; } set { m_Ptr = unchecked((long)value); } }
- /// <summary>
- /// Size of the argument referenced by DataPointer
- /// </summary>
- public int Size { get { return m_Size; } set { m_Size = value; } }
-
- #region private
- /// <summary>
- /// Initializes the members of this EventData object to point at a previously-pinned
- /// tracelogging-compatible metadata blob.
- /// </summary>
- /// <param name="pointer">Pinned tracelogging-compatible metadata blob.</param>
- /// <param name="size">The size of the metadata blob.</param>
- /// <param name="reserved">Value for reserved: 2 for per-provider metadata, 1 for per-event metadata</param>
- internal unsafe void SetMetadata(byte* pointer, int size, int reserved)
- {
- this.m_Ptr = (long)(ulong)(UIntPtr)pointer;
- this.m_Size = size;
- this.m_Reserved = reserved; // Mark this descriptor as containing tracelogging-compatible metadata.
- }
-
- //Important, we pass this structure directly to the Win32 EventWrite API, so this structure must be layed out exactly
- // the way EventWrite wants it.
- internal long m_Ptr;
- internal int m_Size;
-#pragma warning disable 0649
- internal int m_Reserved; // Used to pad the size to match the Win32 API
-#pragma warning restore 0649
- #endregion
- }
-
- /// <summary>
- /// This routine allows you to create efficient WriteEvent helpers, however the code that you use to
- /// do this, while straightforward, is unsafe.
- /// </summary>
- /// <remarks>
- /// <code>
- /// protected unsafe void WriteEvent(int eventId, string arg1, long arg2)
- /// {
- /// if (IsEnabled())
- /// {
- /// if (arg2 == null) arg2 = "";
- /// fixed (char* string2Bytes = arg2)
- /// {
- /// EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- /// descrs[0].DataPointer = (IntPtr)(&amp;arg1);
- /// descrs[0].Size = 8;
- /// descrs[1].DataPointer = (IntPtr)string2Bytes;
- /// descrs[1].Size = ((arg2.Length + 1) * 2);
- /// WriteEventCore(eventId, 2, descrs);
- /// }
- /// }
- /// }
- /// </code>
- /// </remarks>
- [CLSCompliant(false)]
- protected unsafe void WriteEventCore(int eventId, int eventDataCount, EventSource.EventData* data)
- {
- WriteEventWithRelatedActivityIdCore(eventId, null, eventDataCount, data);
- }
-
- /// <summary>
- /// This routine allows you to create efficient WriteEventWithRelatedActivityId helpers, however the code
- /// that you use to do this, while straightforward, is unsafe. The only difference from
- /// <see cref="WriteEventCore"/> is that you pass the relatedActivityId from caller through to this API
- /// </summary>
- /// <remarks>
- /// <code>
- /// protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, string arg1, long arg2)
- /// {
- /// if (IsEnabled())
- /// {
- /// if (arg2 == null) arg2 = "";
- /// fixed (char* string2Bytes = arg2)
- /// {
- /// EventSource.EventData* descrs = stackalloc EventSource.EventData[2];
- /// descrs[0].DataPointer = (IntPtr)(&amp;arg1);
- /// descrs[0].Size = 8;
- /// descrs[1].DataPointer = (IntPtr)string2Bytes;
- /// descrs[1].Size = ((arg2.Length + 1) * 2);
- /// WriteEventWithRelatedActivityIdCore(eventId, relatedActivityId, 2, descrs);
- /// }
- /// }
- /// }
- /// </code>
- /// </remarks>
- [CLSCompliant(false)]
- protected unsafe void WriteEventWithRelatedActivityIdCore(int eventId, Guid* relatedActivityId, int eventDataCount, EventSource.EventData* data)
- {
- if (m_eventSourceEnabled)
- {
- try
- {
- Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
- if (relatedActivityId != null)
- ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
-
- EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
- EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
- Guid* pActivityId = null;
- Guid activityId = Guid.Empty;
- Guid relActivityId = Guid.Empty;
-
- if (opcode != EventOpcode.Info && relatedActivityId == null &&
- ((activityOptions & EventActivityOptions.Disable) == 0))
- {
- if (opcode == EventOpcode.Start)
- {
- m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relActivityId, m_eventData[eventId].ActivityOptions);
- }
- else if (opcode == EventOpcode.Stop)
- {
- m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
- }
-
- if (activityId != Guid.Empty)
- pActivityId = &activityId;
- if (relActivityId != Guid.Empty)
- relatedActivityId = &relActivityId;
- }
-
-#if FEATURE_MANAGED_ETW
- if (m_eventData[eventId].EnabledForETW)
- {
-
-#if FEATURE_ACTIVITYSAMPLING
- // this code should be kept in sync with WriteEventVarargs().
- SessionMask etwSessions = SessionMask.All;
- // only compute etwSessions if there are *any* ETW filters enabled...
- if ((ulong)m_curLiveSessions != 0)
- etwSessions = GetEtwSessionMask(eventId, relatedActivityId);
- // OutputDebugString(string.Format("{0}.WriteEvent(id {1}) -> to sessions {2:x}",
- // m_name, m_eventData[eventId].Name, (ulong) etwSessions));
-
- if ((ulong)etwSessions != 0 || m_legacySessions != null && m_legacySessions.Count > 0)
- {
- if (!SelfDescribingEvents)
- {
- if (etwSessions.IsEqualOrSupersetOf(m_curLiveSessions))
- {
- // OutputDebugString(string.Format(" (1) id {0}, kwd {1:x}",
- // m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Keywords));
- // by default the Descriptor.Keyword will have the perEventSourceSessionId bit
- // mask set to 0x0f so, when all ETW sessions want the event we don't need to
- // synthesize a new one
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
- ThrowEventSourceException(m_eventData[eventId].Name);
- }
- else
- {
- long origKwd = unchecked((long)((ulong)m_eventData[eventId].Descriptor.Keywords & ~(SessionMask.All.ToEventKeywords())));
- // OutputDebugString(string.Format(" (2) id {0}, kwd {1:x}",
- // m_eventData[eventId].Name, etwSessions.ToEventKeywords() | (ulong) origKwd));
- // only some of the ETW sessions will receive this event. Synthesize a new
- // Descriptor whose Keywords field will have the appropriate bits set.
- // etwSessions might be 0, if there are legacy ETW listeners that want this event
- var desc = new EventDescriptor(
- m_eventData[eventId].Descriptor.EventId,
- m_eventData[eventId].Descriptor.Version,
- m_eventData[eventId].Descriptor.Channel,
- m_eventData[eventId].Descriptor.Level,
- m_eventData[eventId].Descriptor.Opcode,
- m_eventData[eventId].Descriptor.Task,
- unchecked((long)etwSessions.ToEventKeywords() | origKwd));
-
- if (!m_provider.WriteEvent(ref desc, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
- ThrowEventSourceException(m_eventData[eventId].Name);
- }
- }
- else
- {
- TraceLoggingEventTypes tlet = m_eventData[eventId].TraceLoggingEventTypes;
- if (tlet == null)
- {
- tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name,
- EventTags.None,
- m_eventData[eventId].Parameters);
- Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, tlet, null);
-
- }
- long origKwd = unchecked((long)((ulong)m_eventData[eventId].Descriptor.Keywords & ~(SessionMask.All.ToEventKeywords())));
- // TODO: activity ID support
- EventSourceOptions opt = new EventSourceOptions
- {
- Keywords = (EventKeywords)unchecked((long)etwSessions.ToEventKeywords() | origKwd),
- Level = (EventLevel)m_eventData[eventId].Descriptor.Level,
- Opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode
- };
-
- WriteMultiMerge(m_eventData[eventId].Name, ref opt, tlet, pActivityId, relatedActivityId, data);
- }
- }
-#else
- if (!SelfDescribingEvents)
- {
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, relatedActivityId, eventDataCount, (IntPtr)data))
- ThrowEventSourceException(m_eventData[eventId].Name);
- }
- else
- {
- TraceLoggingEventTypes tlet = m_eventData[eventId].TraceLoggingEventTypes;
- if (tlet == null)
- {
- tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name,
- m_eventData[eventId].Tags,
- m_eventData[eventId].Parameters);
- Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, tlet, null);
-
- }
- EventSourceOptions opt = new EventSourceOptions
- {
- Keywords = (EventKeywords)m_eventData[eventId].Descriptor.Keywords,
- Level = (EventLevel)m_eventData[eventId].Descriptor.Level,
- Opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode
- };
-
- WriteMultiMerge(m_eventData[eventId].Name, ref opt, tlet, pActivityId, relatedActivityId, data);
- }
-#endif // FEATURE_ACTIVITYSAMPLING
- }
-#endif // FEATURE_MANAGED_ETW
-
- if (m_Dispatchers != null && m_eventData[eventId].EnabledForAnyListener)
- WriteToAllListeners(eventId, relatedActivityId, eventDataCount, data);
- }
- catch (Exception ex)
- {
- if (ex is EventSourceException)
- throw;
- else
- ThrowEventSourceException(m_eventData[eventId].Name, ex);
- }
- }
- }
-
- // fallback varags helpers.
- /// <summary>
- /// This is the varargs helper for writing an event. It does create an array and box all the arguments so it is
- /// relatively inefficient and should only be used for relatively rare events (e.g. less than 100 / sec). If your
- /// rates are faster than that you should use <see cref="WriteEventCore"/> to create fast helpers for your particular
- /// method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/>
- /// check so that the varargs call is not made when the EventSource is not active.
- /// </summary>
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- protected unsafe void WriteEvent(int eventId, params object[] args)
- {
- WriteEventVarargs(eventId, null, args);
- }
-
- /// <summary>
- /// This is the varargs helper for writing an event which also specifies a related activity. It is completely analogous
- /// to corresponding WriteEvent (they share implementation). It does create an array and box all the arguments so it is
- /// relatively inefficient and should only be used for relatively rare events (e.g. less than 100 / sec). If your
- /// rates are faster than that you should use <see cref="WriteEventWithRelatedActivityIdCore"/> to create fast helpers for your
- /// particular method signature. Even if you use this for rare events, this call should be guarded by an <see cref="IsEnabled()"/>
- /// check so that the varargs call is not made when the EventSource is not active.
- /// </summary>
- protected unsafe void WriteEventWithRelatedActivityId(int eventId, Guid relatedActivityId, params object[] args)
- {
- WriteEventVarargs(eventId, &relatedActivityId, args);
- }
-
- #endregion
-
- #region IDisposable Members
- /// <summary>
- /// Disposes of an EventSource.
- /// </summary>
- public void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize(this);
- }
- /// <summary>
- /// Disposes of an EventSource.
- /// </summary>
- /// <remarks>
- /// Called from Dispose() with disposing=true, and from the finalizer (~EventSource) with disposing=false.
- /// Guidelines:
- /// 1. We may be called more than once: do nothing after the first call.
- /// 2. Avoid throwing exceptions if disposing is false, i.e. if we're being finalized.
- /// </remarks>
- /// <param name="disposing">True if called from Dispose(), false if called from the finalizer.</param>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
-#if FEATURE_MANAGED_ETW
- // Send the manifest one more time to ensure circular buffers have a chance to get to this information
- // even in scenarios with a high volume of ETW events.
- if (m_eventSourceEnabled)
- {
- try
- {
- SendManifest(m_rawManifest);
- }
- catch (Exception)
- { } // If it fails, simply give up.
- m_eventSourceEnabled = false;
- }
- if (m_provider != null)
- {
- m_provider.Dispose();
- m_provider = null;
- }
-#endif
- }
- m_eventSourceEnabled = false;
- m_eventSourceDisposed = true;
- }
- /// <summary>
- /// Finalizer for EventSource
- /// </summary>
- ~EventSource()
- {
- this.Dispose(false);
- }
- #endregion
-
- #region private
-#if FEATURE_ACTIVITYSAMPLING
- internal void WriteStringToListener(EventListener listener, string msg, SessionMask m)
- {
- Debug.Assert(listener == null || (uint)m == (uint)SessionMask.FromId(0));
-
- if (m_eventSourceEnabled)
- {
- if (listener == null)
- {
- WriteEventString(0, unchecked((long)m.ToEventKeywords()), msg);
- }
- else
- {
- EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
- eventCallbackArgs.EventId = 0;
- eventCallbackArgs.Message = msg;
- eventCallbackArgs.Payload = new ReadOnlyCollection<object>(new List<object>() { msg });
- eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>(new List<string> { "message" });
- eventCallbackArgs.EventName = "EventSourceMessage";
- listener.OnEventWritten(eventCallbackArgs);
- }
- }
- }
-#endif
-
- private unsafe void WriteEventRaw(
- string eventName,
- ref EventDescriptor eventDescriptor,
- Guid* activityID,
- Guid* relatedActivityID,
- int dataCount,
- IntPtr data)
- {
-#if FEATURE_MANAGED_ETW
- if (m_provider == null)
- {
- ThrowEventSourceException(eventName);
- }
- else
- {
- if (!m_provider.WriteEventRaw(ref eventDescriptor, activityID, relatedActivityID, dataCount, data))
- ThrowEventSourceException(eventName);
- }
-#endif // FEATURE_MANAGED_ETW
- }
-
- // FrameworkEventSource is on the startup path for the framework, so we have this internal overload that it can use
- // to prevent the working set hit from looking at the custom attributes on the type to get the Guid.
- internal EventSource(Guid eventSourceGuid, string eventSourceName)
- : this(eventSourceGuid, eventSourceName, EventSourceSettings.EtwManifestEventFormat)
- { }
-
- // Used by the internal FrameworkEventSource constructor and the TraceLogging-style event source constructor
- internal EventSource(Guid eventSourceGuid, string eventSourceName, EventSourceSettings settings, string[] traits = null)
- {
- m_config = ValidateSettings(settings);
- Initialize(eventSourceGuid, eventSourceName, traits);
- }
-
- /// <summary>
- /// This method is responsible for the common initialization path from our constructors. It must
- /// not leak any exceptions (otherwise, since most EventSource classes define a static member,
- /// "Log", such an exception would become a cached exception for the initialization of the static
- /// member, and any future access to the "Log" would throw the cached exception).
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")]
- private unsafe void Initialize(Guid eventSourceGuid, string eventSourceName, string[] traits)
- {
- try
- {
- m_traits = traits;
- if (m_traits != null && m_traits.Length % 2 != 0)
- {
- throw new ArgumentException(Resources.GetResourceString("TraitEven"), nameof(traits));
- }
-
- if (eventSourceGuid == Guid.Empty)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_NeedGuid"));
- }
-
- if (eventSourceName == null)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_NeedName"));
- }
-
- m_name = eventSourceName;
- m_guid = eventSourceGuid;
-#if FEATURE_ACTIVITYSAMPLING
- m_curLiveSessions = new SessionMask(0);
- m_etwSessionIdMap = new EtwSession[SessionMask.MAX];
-#endif // FEATURE_ACTIVITYSAMPLING
-
- //Enable Implicit Activity tracker
- m_activityTracker = ActivityTracker.Instance;
-
-#if FEATURE_MANAGED_ETW
- // Create and register our provider traits. We do this early because it is needed to log errors
- // In the self-describing event case.
- this.InitializeProviderMetadata();
-
- // Register the provider with ETW
- var provider = new OverideEventProvider(this);
- provider.Register(eventSourceGuid);
-#endif
- // Add the eventSource to the global (weak) list.
- // This also sets m_id, which is the index in the list.
- EventListener.AddEventSource(this);
-
-#if FEATURE_MANAGED_ETW
- // OK if we get this far without an exception, then we can at least write out error messages.
- // Set m_provider, which allows this.
- m_provider = provider;
-
-#if (!ES_BUILD_STANDALONE && !PROJECTN)
- // API available on OS >= Win 8 and patched Win 7.
- // Disable only for FrameworkEventSource to avoid recursion inside exception handling.
- var osVer = Environment.OSVersion.Version.Major * 10 + Environment.OSVersion.Version.Minor;
- if (this.Name != "System.Diagnostics.Eventing.FrameworkEventSource" || osVer >= 62)
-#endif
- {
- int setInformationResult;
- System.Runtime.InteropServices.GCHandle metadataHandle =
- System.Runtime.InteropServices.GCHandle.Alloc(this.providerMetadata, System.Runtime.InteropServices.GCHandleType.Pinned);
- IntPtr providerMetadata = metadataHandle.AddrOfPinnedObject();
-
- setInformationResult = m_provider.SetInformation(
- UnsafeNativeMethods.ManifestEtw.EVENT_INFO_CLASS.SetTraits,
- providerMetadata,
- (uint)this.providerMetadata.Length);
-
- metadataHandle.Free();
- }
-#endif // FEATURE_MANAGED_ETW
-
- Debug.Assert(!m_eventSourceEnabled); // We can't be enabled until we are completely initted.
- // We are logically completely initialized at this point.
- m_completelyInited = true;
- }
- catch (Exception e)
- {
- if (m_constructionException == null)
- m_constructionException = e;
- ReportOutOfBandMessage("ERROR: Exception during construction of EventSource " + Name + ": " + e.Message, true);
- }
-
- // Once m_completelyInited is set, you can have concurrency, so all work is under the lock.
- lock (EventListener.EventListenersLock)
- {
- // If there are any deferred commands, we can do them now.
- // This is the most likely place for exceptions to happen.
- // Note that we are NOT resetting m_deferredCommands to NULL here,
- // We are giving for EventHandler<EventCommandEventArgs> that will be attached later
- EventCommandEventArgs deferredCommands = m_deferredCommands;
- while (deferredCommands != null)
- {
- DoCommand(deferredCommands); // This can never throw, it catches them and reports the errors.
- deferredCommands = deferredCommands.nextCommand;
- }
- }
- }
-
- private static string GetName(Type eventSourceType, EventManifestOptions flags)
- {
- if (eventSourceType == null)
- throw new ArgumentNullException(nameof(eventSourceType));
- Contract.EndContractBlock();
-
- EventSourceAttribute attrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags);
- if (attrib != null && attrib.Name != null)
- return attrib.Name;
-
- return eventSourceType.Name;
- }
-
- /// <summary>
- /// Implements the SHA1 hashing algorithm. Note that this
- /// implementation is for hashing public information. Do not
- /// use this code to hash private data, as this implementation does
- /// not take any steps to avoid information disclosure.
- /// </summary>
- private struct Sha1ForNonSecretPurposes
- {
- private long length; // Total message length in bits
- private uint[] w; // Workspace
- private int pos; // Length of current chunk in bytes
-
- /// <summary>
- /// Call Start() to initialize the hash object.
- /// </summary>
- public void Start()
- {
- if (this.w == null)
- {
- this.w = new uint[85];
- }
-
- this.length = 0;
- this.pos = 0;
- this.w[80] = 0x67452301;
- this.w[81] = 0xEFCDAB89;
- this.w[82] = 0x98BADCFE;
- this.w[83] = 0x10325476;
- this.w[84] = 0xC3D2E1F0;
- }
-
- /// <summary>
- /// Adds an input byte to the hash.
- /// </summary>
- /// <param name="input">Data to include in the hash.</param>
- public void Append(byte input)
- {
- this.w[this.pos / 4] = (this.w[this.pos / 4] << 8) | input;
- if (64 == ++this.pos)
- {
- this.Drain();
- }
- }
-
- /// <summary>
- /// Adds input bytes to the hash.
- /// </summary>
- /// <param name="input">
- /// Data to include in the hash. Must not be null.
- /// </param>
- public void Append(byte[] input)
- {
- foreach (var b in input)
- {
- this.Append(b);
- }
- }
-
- /// <summary>
- /// Retrieves the hash value.
- /// Note that after calling this function, the hash object should
- /// be considered uninitialized. Subsequent calls to Append or
- /// Finish will produce useless results. Call Start() to
- /// reinitialize.
- /// </summary>
- /// <param name="output">
- /// Buffer to receive the hash value. Must not be null.
- /// Up to 20 bytes of hash will be written to the output buffer.
- /// If the buffer is smaller than 20 bytes, the remaining hash
- /// bytes will be lost. If the buffer is larger than 20 bytes, the
- /// rest of the buffer is left unmodified.
- /// </param>
- public void Finish(byte[] output)
- {
- long l = this.length + 8 * this.pos;
- this.Append(0x80);
- while (this.pos != 56)
- {
- this.Append(0x00);
- }
-
- unchecked
- {
- this.Append((byte)(l >> 56));
- this.Append((byte)(l >> 48));
- this.Append((byte)(l >> 40));
- this.Append((byte)(l >> 32));
- this.Append((byte)(l >> 24));
- this.Append((byte)(l >> 16));
- this.Append((byte)(l >> 8));
- this.Append((byte)l);
-
- int end = output.Length < 20 ? output.Length : 20;
- for (int i = 0; i != end; i++)
- {
- uint temp = this.w[80 + i / 4];
- output[i] = (byte)(temp >> 24);
- this.w[80 + i / 4] = temp << 8;
- }
- }
- }
-
- /// <summary>
- /// Called when this.pos reaches 64.
- /// </summary>
- private void Drain()
- {
- for (int i = 16; i != 80; i++)
- {
- this.w[i] = Rol1((this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16]));
- }
-
- unchecked
- {
- uint a = this.w[80];
- uint b = this.w[81];
- uint c = this.w[82];
- uint d = this.w[83];
- uint e = this.w[84];
-
- for (int i = 0; i != 20; i++)
- {
- const uint k = 0x5A827999;
- uint f = (b & c) | ((~b) & d);
- uint temp = Rol5(a) + f + e + k + this.w[i]; e = d; d = c; c = Rol30(b); b = a; a = temp;
- }
-
- for (int i = 20; i != 40; i++)
- {
- uint f = b ^ c ^ d;
- const uint k = 0x6ED9EBA1;
- uint temp = Rol5(a) + f + e + k + this.w[i]; e = d; d = c; c = Rol30(b); b = a; a = temp;
- }
-
- for (int i = 40; i != 60; i++)
- {
- uint f = (b & c) | (b & d) | (c & d);
- const uint k = 0x8F1BBCDC;
- uint temp = Rol5(a) + f + e + k + this.w[i]; e = d; d = c; c = Rol30(b); b = a; a = temp;
- }
-
- for (int i = 60; i != 80; i++)
- {
- uint f = b ^ c ^ d;
- const uint k = 0xCA62C1D6;
- uint temp = Rol5(a) + f + e + k + this.w[i]; e = d; d = c; c = Rol30(b); b = a; a = temp;
- }
-
- this.w[80] += a;
- this.w[81] += b;
- this.w[82] += c;
- this.w[83] += d;
- this.w[84] += e;
- }
-
- this.length += 512; // 64 bytes == 512 bits
- this.pos = 0;
- }
-
- private static uint Rol1(uint input)
- {
- return (input << 1) | (input >> 31);
- }
-
- private static uint Rol5(uint input)
- {
- return (input << 5) | (input >> 27);
- }
-
- private static uint Rol30(uint input)
- {
- return (input << 30) | (input >> 2);
- }
- }
-
- private static Guid GenerateGuidFromName(string name)
- {
- byte[] bytes = Encoding.BigEndianUnicode.GetBytes(name);
- var hash = new Sha1ForNonSecretPurposes();
- hash.Start();
- hash.Append(namespaceBytes);
- hash.Append(bytes);
- Array.Resize(ref bytes, 16);
- hash.Finish(bytes);
-
- bytes[7] = unchecked((byte)((bytes[7] & 0x0F) | 0x50)); // Set high 4 bits of octet 7 to 5, as per RFC 4122
- return new Guid(bytes);
- }
-
- private unsafe object DecodeObject(int eventId, int parameterId, ref EventSource.EventData* data)
- {
- // TODO FIX : We use reflection which in turn uses EventSource, right now we carefully avoid
- // the recursion, but can we do this in a robust way?
-
- IntPtr dataPointer = data->DataPointer;
- // advance to next EventData in array
- ++data;
-
- Type dataType = GetDataType(m_eventData[eventId], parameterId);
-
- Again:
- if (dataType == typeof(IntPtr))
- {
- return *((IntPtr*)dataPointer);
- }
- else if (dataType == typeof(int))
- {
- return *((int*)dataPointer);
- }
- else if (dataType == typeof(uint))
- {
- return *((uint*)dataPointer);
- }
- else if (dataType == typeof(long))
- {
- return *((long*)dataPointer);
- }
- else if (dataType == typeof(ulong))
- {
- return *((ulong*)dataPointer);
- }
- else if (dataType == typeof(byte))
- {
- return *((byte*)dataPointer);
- }
- else if (dataType == typeof(sbyte))
- {
- return *((sbyte*)dataPointer);
- }
- else if (dataType == typeof(short))
- {
- return *((short*)dataPointer);
- }
- else if (dataType == typeof(ushort))
- {
- return *((ushort*)dataPointer);
- }
- else if (dataType == typeof(float))
- {
- return *((float*)dataPointer);
- }
- else if (dataType == typeof(double))
- {
- return *((double*)dataPointer);
- }
- else if (dataType == typeof(decimal))
- {
- return *((decimal*)dataPointer);
- }
- else if (dataType == typeof(bool))
- {
- // The manifest defines a bool as a 32bit type (WIN32 BOOL), not 1 bit as CLR Does.
- if (*((int*)dataPointer) == 1)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else if (dataType == typeof(Guid))
- {
- return *((Guid*)dataPointer);
- }
- else if (dataType == typeof(char))
- {
- return *((char*)dataPointer);
- }
- else if (dataType == typeof(DateTime))
- {
- long dateTimeTicks = *((long*)dataPointer);
- return DateTime.FromFileTimeUtc(dateTimeTicks);
- }
- else if (dataType == typeof(byte[]))
- {
- // byte[] are written to EventData* as an int followed by a blob
- int cbSize = *((int*)dataPointer);
- byte[] blob = new byte[cbSize];
- dataPointer = data->DataPointer;
- data++;
- for (int i = 0; i < cbSize; ++i)
- blob[i] = *((byte*)(dataPointer + i));
- return blob;
- }
- else if (dataType == typeof(byte*))
- {
- // TODO: how do we want to handle this? For now we ignore it...
- return null;
- }
- else
- {
- if (m_EventSourcePreventRecursion && m_EventSourceInDecodeObject)
- {
- return null;
- }
-
- try
- {
- m_EventSourceInDecodeObject = true;
-
- if (dataType.IsEnum())
- {
- dataType = Enum.GetUnderlyingType(dataType);
- goto Again;
- }
-
-
- // Everything else is marshaled as a string.
- // ETW strings are NULL-terminated, so marshal everything up to the first
- // null in the string.
- return System.Runtime.InteropServices.Marshal.PtrToStringUni(dataPointer);
-
- }
- finally
- {
- m_EventSourceInDecodeObject = false;
- }
- }
- }
-
- // Finds the Dispatcher (which holds the filtering state), for a given dispatcher for the current
- // eventSource).
- private EventDispatcher GetDispatcher(EventListener listener)
- {
- EventDispatcher dispatcher = m_Dispatchers;
- while (dispatcher != null)
- {
- if (dispatcher.m_Listener == listener)
- return dispatcher;
- dispatcher = dispatcher.m_Next;
- }
- return dispatcher;
- }
-
- private unsafe void WriteEventVarargs(int eventId, Guid* childActivityID, object[] args)
- {
- if (m_eventSourceEnabled)
- {
- try
- {
- Debug.Assert(m_eventData != null); // You must have initialized this if you enabled the source.
- if (childActivityID != null)
- {
- ValidateEventOpcodeForTransfer(ref m_eventData[eventId], m_eventData[eventId].Name);
-
- // If you use WriteEventWithRelatedActivityID you MUST declare the first argument to be a GUID
- // with the name 'relatedActivityID, and NOT pass this argument to the WriteEvent method.
- // During manifest creation we modify the ParameterInfo[] that we store to strip out any
- // first parameter that is of type Guid and named "relatedActivityId." Thus, if you call
- // WriteEventWithRelatedActivityID from a method that doesn't name its first parameter correctly
- // we can end up in a state where the ParameterInfo[] doesn't have its first parameter stripped,
- // and this leads to a mismatch between the number of arguments and the number of ParameterInfos,
- // which would cause a cryptic IndexOutOfRangeException later if we don't catch it here.
- if (!m_eventData[eventId].HasRelatedActivityID)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_NoRelatedActivityId"));
- }
- }
-
- LogEventArgsMismatches(m_eventData[eventId].Parameters, args);
-
- Guid* pActivityId = null;
- Guid activityId = Guid.Empty;
- Guid relatedActivityId = Guid.Empty;
- EventOpcode opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode;
- EventActivityOptions activityOptions = m_eventData[eventId].ActivityOptions;
-
- if (childActivityID == null &&
- ((activityOptions & EventActivityOptions.Disable) == 0))
- {
- if (opcode == EventOpcode.Start)
- {
- m_activityTracker.OnStart(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId, ref relatedActivityId, m_eventData[eventId].ActivityOptions);
- }
- else if (opcode == EventOpcode.Stop)
- {
- m_activityTracker.OnStop(m_name, m_eventData[eventId].Name, m_eventData[eventId].Descriptor.Task, ref activityId);
- }
-
- if (activityId != Guid.Empty)
- pActivityId = &activityId;
- if (relatedActivityId != Guid.Empty)
- childActivityID = &relatedActivityId;
- }
-
-#if FEATURE_MANAGED_ETW
- if (m_eventData[eventId].EnabledForETW)
- {
-#if FEATURE_ACTIVITYSAMPLING
- // this code should be kept in sync with WriteEventWithRelatedActivityIdCore().
- SessionMask etwSessions = SessionMask.All;
- // only compute etwSessions if there are *any* ETW filters enabled...
- if ((ulong)m_curLiveSessions != 0)
- etwSessions = GetEtwSessionMask(eventId, childActivityID);
-
- if ((ulong)etwSessions != 0 || m_legacySessions != null && m_legacySessions.Count > 0)
- {
- if (!SelfDescribingEvents)
- {
- if (etwSessions.IsEqualOrSupersetOf(m_curLiveSessions))
- {
- // by default the Descriptor.Keyword will have the perEventSourceSessionId bit
- // mask set to 0x0f so, when all ETW sessions want the event we don't need to
- // synthesize a new one
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, childActivityID, args))
- ThrowEventSourceException(m_eventData[eventId].Name);
- }
- else
- {
- long origKwd = unchecked((long)((ulong)m_eventData[eventId].Descriptor.Keywords & ~(SessionMask.All.ToEventKeywords())));
- // only some of the ETW sessions will receive this event. Synthesize a new
- // Descriptor whose Keywords field will have the appropriate bits set.
- var desc = new EventDescriptor(
- m_eventData[eventId].Descriptor.EventId,
- m_eventData[eventId].Descriptor.Version,
- m_eventData[eventId].Descriptor.Channel,
- m_eventData[eventId].Descriptor.Level,
- m_eventData[eventId].Descriptor.Opcode,
- m_eventData[eventId].Descriptor.Task,
- unchecked((long)etwSessions.ToEventKeywords() | origKwd));
-
- if (!m_provider.WriteEvent(ref desc, pActivityId, childActivityID, args))
- ThrowEventSourceException(m_eventData[eventId].Name);
- }
- }
- else
- {
- TraceLoggingEventTypes tlet = m_eventData[eventId].TraceLoggingEventTypes;
- if (tlet == null)
- {
- tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name,
- EventTags.None,
- m_eventData[eventId].Parameters);
- Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, tlet, null);
-
- }
- long origKwd = unchecked((long)((ulong)m_eventData[eventId].Descriptor.Keywords & ~(SessionMask.All.ToEventKeywords())));
- // TODO: activity ID support
- EventSourceOptions opt = new EventSourceOptions
- {
- Keywords = (EventKeywords)unchecked((long)etwSessions.ToEventKeywords() | origKwd),
- Level = (EventLevel)m_eventData[eventId].Descriptor.Level,
- Opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode
- };
-
- WriteMultiMerge(m_eventData[eventId].Name, ref opt, tlet, pActivityId, childActivityID, args);
- }
- }
-#else
- if (!SelfDescribingEvents)
- {
- if (!m_provider.WriteEvent(ref m_eventData[eventId].Descriptor, pActivityId, childActivityID, args))
- ThrowEventSourceException(m_eventData[eventId].Name);
- }
- else
- {
- TraceLoggingEventTypes tlet = m_eventData[eventId].TraceLoggingEventTypes;
- if (tlet == null)
- {
- tlet = new TraceLoggingEventTypes(m_eventData[eventId].Name,
- EventTags.None,
- m_eventData[eventId].Parameters);
- Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, tlet, null);
-
- }
- // TODO: activity ID support
- EventSourceOptions opt = new EventSourceOptions
- {
- Keywords = (EventKeywords)m_eventData[eventId].Descriptor.Keywords,
- Level = (EventLevel)m_eventData[eventId].Descriptor.Level,
- Opcode = (EventOpcode)m_eventData[eventId].Descriptor.Opcode
- };
-
- WriteMultiMerge(m_eventData[eventId].Name, ref opt, tlet, pActivityId, childActivityID, args);
- }
-#endif // FEATURE_ACTIVITYSAMPLING
- }
-#endif // FEATURE_MANAGED_ETW
- if (m_Dispatchers != null && m_eventData[eventId].EnabledForAnyListener)
- {
-#if (!ES_BUILD_STANDALONE && !PROJECTN)
- // Maintain old behavior - object identity is preserved
- if (AppContextSwitches.PreserveEventListnerObjectIdentity)
- {
- WriteToAllListeners(eventId, childActivityID, args);
- }
- else
-#endif // !ES_BUILD_STANDALONE
- {
- object[] serializedArgs = SerializeEventArgs(eventId, args);
- WriteToAllListeners(eventId, childActivityID, serializedArgs);
- }
- }
- }
- catch (Exception ex)
- {
- if (ex is EventSourceException)
- throw;
- else
- ThrowEventSourceException(m_eventData[eventId].Name, ex);
- }
- }
- }
-
- unsafe private object[] SerializeEventArgs(int eventId, object[] args)
- {
- TraceLoggingEventTypes eventTypes = m_eventData[eventId].TraceLoggingEventTypes;
- if (eventTypes == null)
- {
- eventTypes = new TraceLoggingEventTypes(m_eventData[eventId].Name,
- EventTags.None,
- m_eventData[eventId].Parameters);
- Interlocked.CompareExchange(ref m_eventData[eventId].TraceLoggingEventTypes, eventTypes, null);
- }
- var eventData = new object[eventTypes.typeInfos.Length];
- for (int i = 0; i < eventTypes.typeInfos.Length; i++)
- {
- eventData[i] = eventTypes.typeInfos[i].GetData(args[i]);
- }
- return eventData;
- }
-
- /// <summary>
- /// We expect that the arguments to the Event method and the arguments to WriteEvent match. This function
- /// checks that they in fact match and logs a warning to the debugger if they don't.
- /// </summary>
- /// <param name="infos"></param>
- /// <param name="args"></param>
- private void LogEventArgsMismatches(ParameterInfo[] infos, object[] args)
- {
-#if (!ES_BUILD_PCL && !PROJECTN)
- // It would be nice to have this on PCL builds, but it would be pointless since there isn't support for
- // writing to the debugger log on PCL.
- bool typesMatch = args.Length == infos.Length;
-
- int i = 0;
- while (typesMatch && i < args.Length)
- {
- Type pType = infos[i].ParameterType;
-
- // Checking to see if the Parameter types (from the Event method) match the supplied argument types.
- // Fail if one of two things hold : either the argument type is not equal to the parameter type, or the
- // argument is null and the parameter type is non-nullable.
- if ((args[i] != null && (args[i].GetType() != pType))
- || (args[i] == null && (!(pType.IsGenericType && pType.GetGenericTypeDefinition() == typeof(Nullable<>))))
- )
- {
- typesMatch = false;
- break;
- }
-
- ++i;
- }
-
- if (!typesMatch)
- {
- System.Diagnostics.Debugger.Log(0, null, Resources.GetResourceString("EventSource_VarArgsParameterMismatch") + "\r\n");
- }
-#endif //!ES_BUILD_PCL
- }
-
- private int GetParamLenghtIncludingByteArray(ParameterInfo[] parameters)
- {
- int sum = 0;
- foreach (ParameterInfo info in parameters)
- {
- if (info.ParameterType == typeof(byte[]))
- {
- sum += 2;
- }
- else
- {
- sum++;
- }
- }
-
- return sum;
- }
-
- unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, int eventDataCount, EventSource.EventData* data)
- {
- // We represent a byte[] as a integer denoting the length and then a blob of bytes in the data pointer. This causes a spurious
- // warning because eventDataCount is off by one for the byte[] case since a byte[] has 2 items associated it. So we want to check
- // that the number of parameters is correct against the byte[] case, but also we the args array would be one too long if
- // we just used the modifiedParamCount here -- so we need both.
- int paramCount = m_eventData[eventId].Parameters.Length;
- int modifiedParamCount = GetParamLenghtIncludingByteArray(m_eventData[eventId].Parameters);
- if (eventDataCount != modifiedParamCount)
- {
- ReportOutOfBandMessage(Resources.GetResourceString("EventSource_EventParametersMismatch", eventId, eventDataCount, paramCount), true);
- paramCount = Math.Min(paramCount, eventDataCount);
- }
-
- object[] args = new object[paramCount];
-
- EventSource.EventData* dataPtr = data;
- for (int i = 0; i < paramCount; i++)
- args[i] = DecodeObject(eventId, i, ref dataPtr);
- WriteToAllListeners(eventId, childActivityID, args);
- }
-
- // helper for writing to all EventListeners attached the current eventSource.
- unsafe private void WriteToAllListeners(int eventId, Guid* childActivityID, params object[] args)
- {
- EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
- eventCallbackArgs.EventId = eventId;
- if (childActivityID != null)
- eventCallbackArgs.RelatedActivityId = *childActivityID;
- eventCallbackArgs.EventName = m_eventData[eventId].Name;
- eventCallbackArgs.Message = m_eventData[eventId].Message;
- eventCallbackArgs.Payload = new ReadOnlyCollection<object>(args);
-
- DispatchToAllListeners(eventId, childActivityID, eventCallbackArgs);
- }
-
- private unsafe void DispatchToAllListeners(int eventId, Guid* childActivityID, EventWrittenEventArgs eventCallbackArgs)
- {
- Exception lastThrownException = null;
- for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)
- {
- Debug.Assert(dispatcher.m_EventEnabled != null);
- if (eventId == -1 || dispatcher.m_EventEnabled[eventId])
- {
-#if FEATURE_ACTIVITYSAMPLING
- var activityFilter = dispatcher.m_Listener.m_activityFilter;
- // order below is important as PassesActivityFilter will "flow" active activities
- // even when the current EventSource doesn't have filtering enabled. This allows
- // interesting activities to be updated so that sources that do sample can get
- // accurate data
- if (activityFilter == null ||
- ActivityFilter.PassesActivityFilter(activityFilter, childActivityID,
- m_eventData[eventId].TriggersActivityTracking > 0,
- this, eventId) ||
- !dispatcher.m_activityFilteringEnabled)
-#endif // FEATURE_ACTIVITYSAMPLING
- {
- try
- {
- dispatcher.m_Listener.OnEventWritten(eventCallbackArgs);
- }
- catch (Exception e)
- {
- ReportOutOfBandMessage("ERROR: Exception during EventSource.OnEventWritten: "
- + e.Message, false);
- lastThrownException = e;
- }
- }
- }
- }
-
- if (lastThrownException != null)
- {
- throw new EventSourceException(lastThrownException);
- }
- }
-
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- private unsafe void WriteEventString(EventLevel level, long keywords, string msgString)
- {
-#if FEATURE_MANAGED_ETW
- if (m_provider != null)
- {
- string eventName = "EventSourceMessage";
- if (SelfDescribingEvents)
- {
- EventSourceOptions opt = new EventSourceOptions
- {
- Keywords = (EventKeywords)unchecked(keywords),
- Level = level
- };
- var msg = new { message = msgString };
- var tlet = new TraceLoggingEventTypes(eventName, EventTags.None, new Type[] { msg.GetType() });
- WriteMultiMergeInner(eventName, ref opt, tlet, null, null, msg);
- }
- else
- {
- // We want the name of the provider to show up so if we don't have a manifest we create
- // on that at least has the provider name (I don't define any events).
- if (m_rawManifest == null && m_outOfBandMessageCount == 1)
- {
- ManifestBuilder manifestBuilder = new ManifestBuilder(Name, Guid, Name, null, EventManifestOptions.None);
- manifestBuilder.StartEvent(eventName, new EventAttribute(0) { Level = EventLevel.LogAlways, Task = (EventTask)0xFFFE });
- manifestBuilder.AddEventParameter(typeof(string), "message");
- manifestBuilder.EndEvent();
- SendManifest(manifestBuilder.CreateManifest());
- }
-
- // We use this low level routine to to bypass the enabled checking, since the eventSource itself is only partially inited.
- fixed (char* msgStringPtr = msgString)
- {
- EventDescriptor descr = new EventDescriptor(0, 0, 0, (byte)level, 0, 0, keywords);
- EventProvider.EventData data = new EventProvider.EventData();
- data.Ptr = (ulong)msgStringPtr;
- data.Size = (uint)(2 * (msgString.Length + 1));
- data.Reserved = 0;
- m_provider.WriteEvent(ref descr, null, null, 1, (IntPtr)((void*)&data));
- }
- }
- }
-#endif // FEATURE_MANAGED_ETW
- }
-
- /// <summary>
- /// Since this is a means of reporting errors (see ReportoutOfBandMessage) any failure encountered
- /// while writing the message to any one of the listeners will be silently ignored.
- /// </summary>
- private void WriteStringToAllListeners(string eventName, string msg)
- {
- EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
- eventCallbackArgs.EventId = 0;
- eventCallbackArgs.Message = msg;
- eventCallbackArgs.Payload = new ReadOnlyCollection<object>(new List<object>() { msg });
- eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>(new List<string> { "message" });
- eventCallbackArgs.EventName = eventName;
-
- for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)
- {
- bool dispatcherEnabled = false;
- if (dispatcher.m_EventEnabled == null)
- {
- // if the listeners that weren't correctly initialized, we will send to it
- // since this is an error message and we want to see it go out.
- dispatcherEnabled = true;
- }
- else
- {
- // if there's *any* enabled event on the dispatcher we'll write out the string
- // otherwise we'll treat the listener as disabled and skip it
- for (int evtId = 0; evtId < dispatcher.m_EventEnabled.Length; ++evtId)
- {
- if (dispatcher.m_EventEnabled[evtId])
- {
- dispatcherEnabled = true;
- break;
- }
- }
- }
- try
- {
- if (dispatcherEnabled)
- dispatcher.m_Listener.OnEventWritten(eventCallbackArgs);
- }
- catch
- {
- // ignore any exceptions thrown by listeners' OnEventWritten
- }
- }
- }
-
-#if FEATURE_ACTIVITYSAMPLING
- unsafe private SessionMask GetEtwSessionMask(int eventId, Guid* childActivityID)
- {
- SessionMask etwSessions = new SessionMask();
-
- for (int i = 0; i < SessionMask.MAX; ++i)
- {
- EtwSession etwSession = m_etwSessionIdMap[i];
- if (etwSession != null)
- {
- ActivityFilter activityFilter = etwSession.m_activityFilter;
- // PassesActivityFilter() will flow "interesting" activities, so make sure
- // to perform this test first, before ORing with ~m_activityFilteringForETWEnabled
- // (note: the first test for !m_activityFilteringForETWEnabled[i] ensures we
- // do not fire events indiscriminately, when no filters are specified, but only
- // if, in addition, the session did not also enable ActivitySampling)
- if (activityFilter == null && !m_activityFilteringForETWEnabled[i] ||
- activityFilter != null &&
- ActivityFilter.PassesActivityFilter(activityFilter, childActivityID,
- m_eventData[eventId].TriggersActivityTracking > 0, this, eventId) ||
- !m_activityFilteringForETWEnabled[i])
- {
- etwSessions[i] = true;
- }
- }
- }
- // flow "interesting" activities for all legacy sessions in which there's some
- // level of activity tracing enabled (even other EventSources)
- if (m_legacySessions != null && m_legacySessions.Count > 0 &&
- (EventOpcode)m_eventData[eventId].Descriptor.Opcode == EventOpcode.Send)
- {
- // only calculate InternalCurrentThreadActivityId once
- Guid* pCurrentActivityId = null;
- Guid currentActivityId;
- foreach (var legacyEtwSession in m_legacySessions)
- {
- if (legacyEtwSession == null)
- continue;
-
- ActivityFilter activityFilter = legacyEtwSession.m_activityFilter;
- if (activityFilter != null)
- {
- if (pCurrentActivityId == null)
- {
- currentActivityId = InternalCurrentThreadActivityId;
- pCurrentActivityId = &currentActivityId;
- }
- ActivityFilter.FlowActivityIfNeeded(activityFilter, pCurrentActivityId, childActivityID);
- }
- }
- }
-
- return etwSessions;
- }
-#endif // FEATURE_ACTIVITYSAMPLING
-
- /// <summary>
- /// Returns true if 'eventNum' is enabled if you only consider the level and matchAnyKeyword filters.
- /// It is possible that eventSources turn off the event based on additional filtering criteria.
- /// </summary>
- private bool IsEnabledByDefault(int eventNum, bool enable, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword)
- {
- if (!enable)
- return false;
-
- EventLevel eventLevel = (EventLevel)m_eventData[eventNum].Descriptor.Level;
- EventKeywords eventKeywords = unchecked((EventKeywords)((ulong)m_eventData[eventNum].Descriptor.Keywords & (~(SessionMask.All.ToEventKeywords()))));
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- EventChannel channel = unchecked((EventChannel)m_eventData[eventNum].Descriptor.Channel);
-#else
- EventChannel channel = EventChannel.None;
-#endif
-
- return IsEnabledCommon(enable, currentLevel, currentMatchAnyKeyword, eventLevel, eventKeywords, channel);
- }
-
- private bool IsEnabledCommon(bool enabled, EventLevel currentLevel, EventKeywords currentMatchAnyKeyword,
- EventLevel eventLevel, EventKeywords eventKeywords, EventChannel eventChannel)
- {
- if (!enabled)
- return false;
-
- // does is pass the level test?
- if ((currentLevel != 0) && (currentLevel < eventLevel))
- return false;
-
- // if yes, does it pass the keywords test?
- if (currentMatchAnyKeyword != 0 && eventKeywords != 0)
- {
-#if FEATURE_MANAGED_ETW_CHANNELS
- // is there a channel with keywords that match currentMatchAnyKeyword?
- if (eventChannel != EventChannel.None && this.m_channelData != null && this.m_channelData.Length > (int)eventChannel)
- {
- EventKeywords channel_keywords = unchecked((EventKeywords)(m_channelData[(int)eventChannel] | (ulong)eventKeywords));
- if (channel_keywords != 0 && (channel_keywords & currentMatchAnyKeyword) == 0)
- return false;
- }
- else
-#endif
- {
- if ((unchecked((ulong)eventKeywords & (ulong)currentMatchAnyKeyword)) == 0)
- return false;
- }
- }
- return true;
-
- }
- [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
- private void ThrowEventSourceException(string eventName, Exception innerEx = null)
- {
- // If we fail during out of band logging we may end up trying
- // to throw another EventSourceException, thus hitting a StackOverflowException.
- // Avoid StackOverflow by making sure we do not recursively call this method.
- if (m_EventSourceExceptionRecurenceCount > 0)
- return;
- try
- {
- m_EventSourceExceptionRecurenceCount++;
-
- string errorPrefix = "EventSourceException";
- if (eventName != null)
- {
- errorPrefix += " while processing event \"" + eventName + "\"";
- }
-
- // TODO Create variations of EventSourceException that indicate more information using the error code.
- switch (EventProvider.GetLastWriteEventError())
- {
- case EventProvider.WriteEventErrorCode.EventTooBig:
- ReportOutOfBandMessage(errorPrefix + ": " + Resources.GetResourceString("EventSource_EventTooBig"), true);
- if (ThrowOnEventWriteErrors) throw new EventSourceException(Resources.GetResourceString("EventSource_EventTooBig"), innerEx);
- break;
- case EventProvider.WriteEventErrorCode.NoFreeBuffers:
- ReportOutOfBandMessage(errorPrefix + ": " + Resources.GetResourceString("EventSource_NoFreeBuffers"), true);
- if (ThrowOnEventWriteErrors) throw new EventSourceException(Resources.GetResourceString("EventSource_NoFreeBuffers"), innerEx);
- break;
- case EventProvider.WriteEventErrorCode.NullInput:
- ReportOutOfBandMessage(errorPrefix + ": " + Resources.GetResourceString("EventSource_NullInput"), true);
- if (ThrowOnEventWriteErrors) throw new EventSourceException(Resources.GetResourceString("EventSource_NullInput"), innerEx);
- break;
- case EventProvider.WriteEventErrorCode.TooManyArgs:
- ReportOutOfBandMessage(errorPrefix + ": " + Resources.GetResourceString("EventSource_TooManyArgs"), true);
- if (ThrowOnEventWriteErrors) throw new EventSourceException(Resources.GetResourceString("EventSource_TooManyArgs"), innerEx);
- break;
- default:
- if (innerEx != null)
- ReportOutOfBandMessage(errorPrefix + ": " + innerEx.GetType() + ":" + innerEx.Message, true);
- else
- ReportOutOfBandMessage(errorPrefix, true);
- if (ThrowOnEventWriteErrors) throw new EventSourceException(innerEx);
- break;
- }
- }
- finally
- {
- m_EventSourceExceptionRecurenceCount--;
- }
- }
-
- private void ValidateEventOpcodeForTransfer(ref EventMetadata eventData, string eventName)
- {
- if ((EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Send &&
- (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Receive &&
- (EventOpcode)eventData.Descriptor.Opcode != EventOpcode.Start)
- {
- ThrowEventSourceException(eventName);
- }
- }
-
- internal static EventOpcode GetOpcodeWithDefault(EventOpcode opcode, string eventName)
- {
- if (opcode == EventOpcode.Info && eventName != null)
- {
- if (eventName.EndsWith(s_ActivityStartSuffix, StringComparison.Ordinal))
- {
- return EventOpcode.Start;
- }
- else if (eventName.EndsWith(s_ActivityStopSuffix, StringComparison.Ordinal))
- {
- return EventOpcode.Stop;
- }
- }
-
- return opcode;
- }
-
-#if FEATURE_MANAGED_ETW
- /// <summary>
- /// This class lets us hook the 'OnEventCommand' from the eventSource.
- /// </summary>
- private class OverideEventProvider : EventProvider
- {
- public OverideEventProvider(EventSource eventSource)
- {
- this.m_eventSource = eventSource;
- }
- protected override void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments,
- int perEventSourceSessionId, int etwSessionId)
- {
- // We use null to represent the ETW EventListener.
- EventListener listener = null;
- m_eventSource.SendCommand(listener, perEventSourceSessionId, etwSessionId,
- (EventCommand)command, IsEnabled(), Level, MatchAnyKeyword, arguments);
- }
- private EventSource m_eventSource;
- }
-#endif
-
- /// <summary>
- /// Used to hold all the static information about an event. This includes everything in the event
- /// descriptor as well as some stuff we added specifically for EventSource. see the
- /// code:m_eventData for where we use this.
- /// </summary>
- internal partial struct EventMetadata
- {
- public EventDescriptor Descriptor;
- public EventTags Tags;
- public bool EnabledForAnyListener; // true if any dispatcher has this event turned on
- public bool EnabledForETW; // is this event on for the OS ETW data dispatcher?
-
- public bool HasRelatedActivityID; // Set if the event method's first parameter is a Guid named 'relatedActivityId'
-#if !FEATURE_ACTIVITYSAMPLING
-#pragma warning disable 0649
-#endif
- public byte TriggersActivityTracking; // count of listeners that marked this event as trigger for start of activity logging.
-#if !FEATURE_ACTIVITYSAMPLING
-#pragma warning restore 0649
-#endif
- public string Name; // the name of the event
- public string Message; // If the event has a message associated with it, this is it.
- public ParameterInfo[] Parameters; // TODO can we remove?
-
- public TraceLoggingEventTypes TraceLoggingEventTypes;
- public EventActivityOptions ActivityOptions;
-
-#if PROJECTN
- public EventParameterType[] ParameterTypes;
-#endif
- };
-
- // This is the internal entry point that code:EventListeners call when wanting to send a command to a
- // eventSource. The logic is as follows
- //
- // * if Command == Update
- // * perEventSourceSessionId specifies the per-provider ETW session ID that the command applies
- // to (if listener != null)
- // perEventSourceSessionId = 0 - reserved for EventListeners
- // perEventSourceSessionId = 1..SessionMask.MAX - reserved for activity tracing aware ETW sessions
- // perEventSourceSessionId-1 represents the bit in the reserved field (bits 44..47) in
- // Keywords that identifies the session
- // perEventSourceSessionId = SessionMask.MAX+1 - reserved for legacy ETW sessions; these are
- // discriminated by etwSessionId
- // * etwSessionId specifies a machine-wide ETW session ID; this allows correlation of
- // activity tracing across different providers (which might have different sessionIds
- // for the same ETW session)
- // * enable, level, matchAnyKeywords are used to set a default for all events for the
- // eventSource. In particular, if 'enabled' is false, 'level' and
- // 'matchAnyKeywords' are not used.
- // * OnEventCommand is invoked, which may cause calls to
- // code:EventSource.EnableEventForDispatcher which may cause changes in the filtering
- // depending on the logic in that routine.
- // * else (command != Update)
- // * Simply call OnEventCommand. The expectation is that filtering is NOT changed.
- // * The 'enabled' 'level', matchAnyKeyword' arguments are ignored (must be true, 0, 0).
- //
- // dispatcher == null has special meaning. It is the 'ETW' dispatcher.
- internal void SendCommand(EventListener listener, int perEventSourceSessionId, int etwSessionId,
- EventCommand command, bool enable,
- EventLevel level, EventKeywords matchAnyKeyword,
- IDictionary<string, string> commandArguments)
- {
- var commandArgs = new EventCommandEventArgs(command, commandArguments, this, listener, perEventSourceSessionId, etwSessionId, enable, level, matchAnyKeyword);
- lock (EventListener.EventListenersLock)
- {
- if (m_completelyInited)
- {
- // After the first command arrive after construction, we are ready to get rid of the deferred commands
- this.m_deferredCommands = null;
- // We are fully initialized, do the command
- DoCommand(commandArgs);
- }
- else
- {
- // We can't do the command, simply remember it and we do it when we are fully constructed.
- commandArgs.nextCommand = m_deferredCommands;
- m_deferredCommands = commandArgs;
- }
- }
- }
-
- /// <summary>
- /// We want the eventSource to be fully initialized when we do commands because that way we can send
- /// error messages and other logging directly to the event stream. Unfortunately we can get callbacks
- /// when we are not fully initialized. In that case we store them in 'commandArgs' and do them later.
- /// This helper actually does all actual command logic.
- /// </summary>
- internal void DoCommand(EventCommandEventArgs commandArgs)
- {
- // PRECONDITION: We should be holding the EventListener.EventListenersLock
- // We defer commands until we are completely inited. This allows error messages to be sent.
- Debug.Assert(m_completelyInited);
-
-#if FEATURE_MANAGED_ETW
- if (m_provider == null) // If we failed to construct
- return;
-#endif // FEATURE_MANAGED_ETW
-
- m_outOfBandMessageCount = 0;
- bool shouldReport = (commandArgs.perEventSourceSessionId > 0) && (commandArgs.perEventSourceSessionId <= SessionMask.MAX);
- try
- {
- EnsureDescriptorsInitialized();
- Debug.Assert(m_eventData != null);
-
- // Find the per-EventSource dispatcher corresponding to registered dispatcher
- commandArgs.dispatcher = GetDispatcher(commandArgs.listener);
- if (commandArgs.dispatcher == null && commandArgs.listener != null) // dispatcher == null means ETW dispatcher
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_ListenerNotFound"));
- }
-
- if (commandArgs.Arguments == null)
- commandArgs.Arguments = new Dictionary<string, string>();
-
- if (commandArgs.Command == EventCommand.Update)
- {
- // Set it up using the 'standard' filtering bitfields (use the "global" enable, not session specific one)
- for (int i = 0; i < m_eventData.Length; i++)
- EnableEventForDispatcher(commandArgs.dispatcher, i, IsEnabledByDefault(i, commandArgs.enable, commandArgs.level, commandArgs.matchAnyKeyword));
-
- if (commandArgs.enable)
- {
- if (!m_eventSourceEnabled)
- {
- // EventSource turned on for the first time, simply copy the bits.
- m_level = commandArgs.level;
- m_matchAnyKeyword = commandArgs.matchAnyKeyword;
- }
- else
- {
- // Already enabled, make it the most verbose of the existing and new filter
- if (commandArgs.level > m_level)
- m_level = commandArgs.level;
- if (commandArgs.matchAnyKeyword == 0)
- m_matchAnyKeyword = 0;
- else if (m_matchAnyKeyword != 0)
- m_matchAnyKeyword = unchecked(m_matchAnyKeyword | commandArgs.matchAnyKeyword);
- }
- }
-
- // interpret perEventSourceSessionId's sign, and adjust perEventSourceSessionId to
- // represent 0-based positive values
- bool bSessionEnable = (commandArgs.perEventSourceSessionId >= 0);
- if (commandArgs.perEventSourceSessionId == 0 && commandArgs.enable == false)
- bSessionEnable = false;
-
- if (commandArgs.listener == null)
- {
- if (!bSessionEnable)
- commandArgs.perEventSourceSessionId = -commandArgs.perEventSourceSessionId;
- // for "global" enable/disable (passed in with listener == null and
- // perEventSourceSessionId == 0) perEventSourceSessionId becomes -1
- --commandArgs.perEventSourceSessionId;
- }
-
- commandArgs.Command = bSessionEnable ? EventCommand.Enable : EventCommand.Disable;
-
- // perEventSourceSessionId = -1 when ETW sent a notification, but the set of active sessions
- // hasn't changed.
- // sesisonId = SessionMask.MAX when one of the legacy ETW sessions changed
- // 0 <= perEventSourceSessionId < SessionMask.MAX for activity-tracing aware sessions
- Debug.Assert(commandArgs.perEventSourceSessionId >= -1 && commandArgs.perEventSourceSessionId <= SessionMask.MAX);
-
- // Send the manifest if we are enabling an ETW session
- if (bSessionEnable && commandArgs.dispatcher == null)
- {
- // eventSourceDispatcher == null means this is the ETW manifest
-
- // Note that we unconditionally send the manifest whenever we are enabled, even if
- // we were already enabled. This is because there may be multiple sessions active
- // and we can't know that all the sessions have seen the manifest.
- if (!SelfDescribingEvents)
- SendManifest(m_rawManifest);
- }
-
-#if FEATURE_ACTIVITYSAMPLING
- if (bSessionEnable && commandArgs.perEventSourceSessionId != -1)
- {
- bool participateInSampling = false;
- string activityFilters;
- int sessionIdBit;
-
- ParseCommandArgs(commandArgs.Arguments, out participateInSampling,
- out activityFilters, out sessionIdBit);
-
- if (commandArgs.listener == null && commandArgs.Arguments.Count > 0 && commandArgs.perEventSourceSessionId != sessionIdBit)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_SessionIdError",
- commandArgs.perEventSourceSessionId + SessionMask.SHIFT_SESSION_TO_KEYWORD,
- sessionIdBit + SessionMask.SHIFT_SESSION_TO_KEYWORD));
- }
-
- if (commandArgs.listener == null)
- {
- UpdateEtwSession(commandArgs.perEventSourceSessionId, commandArgs.etwSessionId, true, activityFilters, participateInSampling);
- }
- else
- {
- ActivityFilter.UpdateFilter(ref commandArgs.listener.m_activityFilter, this, 0, activityFilters);
- commandArgs.dispatcher.m_activityFilteringEnabled = participateInSampling;
- }
- }
- else if (!bSessionEnable && commandArgs.listener == null)
- {
- // if we disable an ETW session, indicate that in a synthesized command argument
- if (commandArgs.perEventSourceSessionId >= 0 && commandArgs.perEventSourceSessionId < SessionMask.MAX)
- {
- commandArgs.Arguments["EtwSessionKeyword"] = (commandArgs.perEventSourceSessionId + SessionMask.SHIFT_SESSION_TO_KEYWORD).ToString(CultureInfo.InvariantCulture);
- }
- }
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // Turn on the enable bit before making the OnEventCommand callback This allows you to do useful
- // things like log messages, or test if keywords are enabled in the callback.
- if (commandArgs.enable)
- {
- Debug.Assert(m_eventData != null);
- m_eventSourceEnabled = true;
- }
-
- this.OnEventCommand(commandArgs);
- var eventCommandCallback = this.m_eventCommandExecuted;
- if (eventCommandCallback != null)
- eventCommandCallback(this, commandArgs);
-
-#if FEATURE_ACTIVITYSAMPLING
- if (commandArgs.listener == null && !bSessionEnable && commandArgs.perEventSourceSessionId != -1)
- {
- // if we disable an ETW session, complete disabling it
- UpdateEtwSession(commandArgs.perEventSourceSessionId, commandArgs.etwSessionId, false, null, false);
- }
-#endif // FEATURE_ACTIVITYSAMPLING
-
- if (!commandArgs.enable)
- {
- // If we are disabling, maybe we can turn on 'quick checks' to filter
- // quickly. These are all just optimizations (since later checks will still filter)
-
-#if FEATURE_ACTIVITYSAMPLING
- // Turn off (and forget) any information about Activity Tracing.
- if (commandArgs.listener == null)
- {
- // reset all filtering information for activity-tracing-aware sessions
- for (int i = 0; i < SessionMask.MAX; ++i)
- {
- EtwSession etwSession = m_etwSessionIdMap[i];
- if (etwSession != null)
- ActivityFilter.DisableFilter(ref etwSession.m_activityFilter, this);
- }
- m_activityFilteringForETWEnabled = new SessionMask(0);
- m_curLiveSessions = new SessionMask(0);
- // reset activity-tracing-aware sessions
- if (m_etwSessionIdMap != null)
- for (int i = 0; i < SessionMask.MAX; ++i)
- m_etwSessionIdMap[i] = null;
- // reset legacy sessions
- if (m_legacySessions != null)
- m_legacySessions.Clear();
- }
- else
- {
- ActivityFilter.DisableFilter(ref commandArgs.listener.m_activityFilter, this);
- commandArgs.dispatcher.m_activityFilteringEnabled = false;
- }
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // There is a good chance EnabledForAnyListener are not as accurate as
- // they could be, go ahead and get a better estimate.
- for (int i = 0; i < m_eventData.Length; i++)
- {
- bool isEnabledForAnyListener = false;
- for (EventDispatcher dispatcher = m_Dispatchers; dispatcher != null; dispatcher = dispatcher.m_Next)
- {
- if (dispatcher.m_EventEnabled[i])
- {
- isEnabledForAnyListener = true;
- break;
- }
- }
- m_eventData[i].EnabledForAnyListener = isEnabledForAnyListener;
- }
-
- // If no events are enabled, disable the global enabled bit.
- if (!AnyEventEnabled())
- {
- m_level = 0;
- m_matchAnyKeyword = 0;
- m_eventSourceEnabled = false;
- }
- }
-#if FEATURE_ACTIVITYSAMPLING
- UpdateKwdTriggers(commandArgs.enable);
-#endif // FEATURE_ACTIVITYSAMPLING
- }
- else
- {
- if (commandArgs.Command == EventCommand.SendManifest)
- {
- // TODO: should we generate the manifest here if we hadn't already?
- if (m_rawManifest != null)
- SendManifest(m_rawManifest);
- }
-
- // These are not used for non-update commands and thus should always be 'default' values
- // Debug.Assert(enable == true);
- // Debug.Assert(level == EventLevel.LogAlways);
- // Debug.Assert(matchAnyKeyword == EventKeywords.None);
-
- this.OnEventCommand(commandArgs);
- var eventCommandCallback = m_eventCommandExecuted;
- if (eventCommandCallback != null)
- eventCommandCallback(this, commandArgs);
- }
-
-#if FEATURE_ACTIVITYSAMPLING
- if (m_completelyInited && (commandArgs.listener != null || shouldReport))
- {
- SessionMask m = SessionMask.FromId(commandArgs.perEventSourceSessionId);
- ReportActivitySamplingInfo(commandArgs.listener, m);
- }
-#endif // FEATURE_ACTIVITYSAMPLING
- }
- catch (Exception e)
- {
- // When the ETW session is created after the EventSource has registered with the ETW system
- // we can send any error messages here.
- ReportOutOfBandMessage("ERROR: Exception in Command Processing for EventSource " + Name + ": " + e.Message, true);
- // We never throw when doing a command.
- }
- }
-
-#if FEATURE_ACTIVITYSAMPLING
-
- internal void UpdateEtwSession(
- int sessionIdBit,
- int etwSessionId,
- bool bEnable,
- string activityFilters,
- bool participateInSampling)
- {
- if (sessionIdBit < SessionMask.MAX)
- {
- // activity-tracing-aware etw session
- if (bEnable)
- {
- var etwSession = EtwSession.GetEtwSession(etwSessionId, true);
- ActivityFilter.UpdateFilter(ref etwSession.m_activityFilter, this, sessionIdBit, activityFilters);
- m_etwSessionIdMap[sessionIdBit] = etwSession;
- m_activityFilteringForETWEnabled[sessionIdBit] = participateInSampling;
- }
- else
- {
- var etwSession = EtwSession.GetEtwSession(etwSessionId);
- m_etwSessionIdMap[sessionIdBit] = null;
- m_activityFilteringForETWEnabled[sessionIdBit] = false;
- if (etwSession != null)
- {
- ActivityFilter.DisableFilter(ref etwSession.m_activityFilter, this);
- // the ETW session is going away; remove it from the global list
- EtwSession.RemoveEtwSession(etwSession);
- }
- }
- m_curLiveSessions[sessionIdBit] = bEnable;
- }
- else
- {
- // legacy etw session
- if (bEnable)
- {
- if (m_legacySessions == null)
- m_legacySessions = new List<EtwSession>(8);
- var etwSession = EtwSession.GetEtwSession(etwSessionId, true);
- if (!m_legacySessions.Contains(etwSession))
- m_legacySessions.Add(etwSession);
- }
- else
- {
- var etwSession = EtwSession.GetEtwSession(etwSessionId);
- if (etwSession != null)
- {
- if (m_legacySessions != null)
- m_legacySessions.Remove(etwSession);
- // the ETW session is going away; remove it from the global list
- EtwSession.RemoveEtwSession(etwSession);
- }
- }
- }
- }
-
- internal static bool ParseCommandArgs(
- IDictionary<string, string> commandArguments,
- out bool participateInSampling,
- out string activityFilters,
- out int sessionIdBit)
- {
- bool res = true;
- participateInSampling = false;
- string activityFilterString;
- if (commandArguments.TryGetValue("ActivitySamplingStartEvent", out activityFilters))
- {
- // if a start event is specified default the event source to participate in sampling
- participateInSampling = true;
- }
-
- if (commandArguments.TryGetValue("ActivitySampling", out activityFilterString))
- {
- if (string.Compare(activityFilterString, "false", StringComparison.OrdinalIgnoreCase) == 0 ||
- activityFilterString == "0")
- participateInSampling = false;
- else
- participateInSampling = true;
- }
-
- string sSessionKwd;
- int sessionKwd = -1;
- if (!commandArguments.TryGetValue("EtwSessionKeyword", out sSessionKwd) ||
- !int.TryParse(sSessionKwd, out sessionKwd) ||
- sessionKwd < SessionMask.SHIFT_SESSION_TO_KEYWORD ||
- sessionKwd >= SessionMask.SHIFT_SESSION_TO_KEYWORD + SessionMask.MAX)
- {
- sessionIdBit = -1;
- res = false;
- }
- else
- {
- sessionIdBit = sessionKwd - SessionMask.SHIFT_SESSION_TO_KEYWORD;
- }
- return res;
- }
-
- internal void UpdateKwdTriggers(bool enable)
- {
- if (enable)
- {
- // recompute m_keywordTriggers
- ulong gKeywords = unchecked((ulong)m_matchAnyKeyword);
- if (gKeywords == 0)
- gKeywords = 0xFFFFffffFFFFffff;
-
- m_keywordTriggers = 0;
- for (int sessId = 0; sessId < SessionMask.MAX; ++sessId)
- {
- EtwSession etwSession = m_etwSessionIdMap[sessId];
- if (etwSession == null)
- continue;
-
- ActivityFilter activityFilter = etwSession.m_activityFilter;
- ActivityFilter.UpdateKwdTriggers(activityFilter, m_guid, this, unchecked((EventKeywords)gKeywords));
- }
- }
- else
- {
- m_keywordTriggers = 0;
- }
- }
-
-#endif // FEATURE_ACTIVITYSAMPLING
-
- /// <summary>
- /// If 'value is 'true' then set the eventSource so that 'dispatcher' will receive event with the eventId
- /// of 'eventId. If value is 'false' disable the event for that dispatcher. If 'eventId' is out of
- /// range return false, otherwise true.
- /// </summary>
- internal bool EnableEventForDispatcher(EventDispatcher dispatcher, int eventId, bool value)
- {
- if (dispatcher == null)
- {
- if (eventId >= m_eventData.Length)
- return false;
-#if FEATURE_MANAGED_ETW
- if (m_provider != null)
- m_eventData[eventId].EnabledForETW = value;
-#endif
- }
- else
- {
- if (eventId >= dispatcher.m_EventEnabled.Length)
- return false;
- dispatcher.m_EventEnabled[eventId] = value;
- if (value)
- m_eventData[eventId].EnabledForAnyListener = true;
- }
- return true;
- }
-
- /// <summary>
- /// Returns true if any event at all is on.
- /// </summary>
- private bool AnyEventEnabled()
- {
- for (int i = 0; i < m_eventData.Length; i++)
- if (m_eventData[i].EnabledForETW || m_eventData[i].EnabledForAnyListener)
- return true;
- return false;
- }
-
- private bool IsDisposed
- {
- get { return m_eventSourceDisposed; }
- }
-
- private void EnsureDescriptorsInitialized()
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
-#endif
- if (m_eventData == null)
- {
- Guid eventSourceGuid = Guid.Empty;
- string eventSourceName = null;
- EventMetadata[] eventData = null;
- byte[] manifest = null;
-
- // Try the GetMetadata provided by the ILTransform in ProjectN. The default sets all to null, and in that case we fall back
- // to the reflection approach.
- GetMetadata(out eventSourceGuid, out eventSourceName, out eventData, out manifest);
-
- if (eventSourceGuid.Equals(Guid.Empty) || eventSourceName == null || eventData == null || manifest == null)
- {
- // GetMetadata failed, so we have to set it via reflection.
- Debug.Assert(m_rawManifest == null);
- m_rawManifest = CreateManifestAndDescriptors(this.GetType(), Name, this);
- Debug.Assert(m_eventData != null);
-
- }
- else
- {
- // GetMetadata worked, so set the fields as appropriate.
- m_name = eventSourceName;
- m_guid = eventSourceGuid;
- m_eventData = eventData;
- m_rawManifest = manifest;
- }
- // TODO Enforce singleton pattern
- foreach (WeakReference eventSourceRef in EventListener.s_EventSources)
- {
- EventSource eventSource = eventSourceRef.Target as EventSource;
- if (eventSource != null && eventSource.Guid == m_guid && !eventSource.IsDisposed)
- {
- if (eventSource != this)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_EventSourceGuidInUse", m_guid));
- }
- }
- }
-
- // Make certain all dispatchers also have their arrays initialized
- EventDispatcher dispatcher = m_Dispatchers;
- while (dispatcher != null)
- {
- if (dispatcher.m_EventEnabled == null)
- dispatcher.m_EventEnabled = new bool[m_eventData.Length];
- dispatcher = dispatcher.m_Next;
- }
- }
- if (s_currentPid == 0)
- {
-#if ES_BUILD_STANDALONE && !ES_BUILD_PCL && !CORECLR
- // for non-BCL EventSource we must assert SecurityPermission
- new SecurityPermission(PermissionState.Unrestricted).Assert();
-#endif
- s_currentPid = Win32Native.GetCurrentProcessId();
- }
- }
-
- // Send out the ETW manifest XML out to ETW
- // Today, we only send the manifest to ETW, custom listeners don't get it.
- private unsafe bool SendManifest(byte[] rawManifest)
- {
- bool success = true;
-
- if (rawManifest == null)
- return false;
-
- Debug.Assert(!SelfDescribingEvents);
-
-#if FEATURE_MANAGED_ETW
- fixed (byte* dataPtr = rawManifest)
- {
- // we don't want the manifest to show up in the event log channels so we specify as keywords
- // everything but the first 8 bits (reserved for the 8 channels)
- var manifestDescr = new EventDescriptor(0xFFFE, 1, 0, 0, 0xFE, 0xFFFE, 0x00ffFFFFffffFFFF);
- ManifestEnvelope envelope = new ManifestEnvelope();
-
- envelope.Format = ManifestEnvelope.ManifestFormats.SimpleXmlFormat;
- envelope.MajorVersion = 1;
- envelope.MinorVersion = 0;
- envelope.Magic = 0x5B; // An unusual number that can be checked for consistency.
- int dataLeft = rawManifest.Length;
- envelope.ChunkNumber = 0;
-
- EventProvider.EventData* dataDescrs = stackalloc EventProvider.EventData[2];
-
- dataDescrs[0].Ptr = (ulong)&envelope;
- dataDescrs[0].Size = (uint)sizeof(ManifestEnvelope);
- dataDescrs[0].Reserved = 0;
-
- dataDescrs[1].Ptr = (ulong)dataPtr;
- dataDescrs[1].Reserved = 0;
-
- int chunkSize = ManifestEnvelope.MaxChunkSize;
- TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE:
- envelope.TotalChunks = (ushort)((dataLeft + (chunkSize - 1)) / chunkSize);
- while (dataLeft > 0)
- {
- dataDescrs[1].Size = (uint)Math.Min(dataLeft, chunkSize);
- if (m_provider != null)
- {
- if (!m_provider.WriteEvent(ref manifestDescr, null, null, 2, (IntPtr)dataDescrs))
- {
- // Turns out that if users set the BufferSize to something less than 64K then WriteEvent
- // can fail. If we get this failure on the first chunk try again with something smaller
- // The smallest BufferSize is 1K so if we get to 256 (to account for envelope overhead), we can give up making it smaller.
- if (EventProvider.GetLastWriteEventError() == EventProvider.WriteEventErrorCode.EventTooBig)
- {
- if (envelope.ChunkNumber == 0 && chunkSize > 256)
- {
- chunkSize = chunkSize / 2;
- goto TRY_AGAIN_WITH_SMALLER_CHUNK_SIZE;
- }
- }
- success = false;
- if (ThrowOnEventWriteErrors)
- ThrowEventSourceException("SendManifest");
- break;
- }
- }
- dataLeft -= chunkSize;
- dataDescrs[1].Ptr += (uint)chunkSize;
- envelope.ChunkNumber++;
-
- // For large manifests we want to not overflow any receiver's buffer. Most manifests will fit within
- // 5 chunks, so only the largest manifests will hit the pause.
- if ((envelope.ChunkNumber % 5) == 0)
- Thread.Sleep(15);
- }
- }
-#endif // FEATURE_MANAGED_ETW
- return success;
- }
-
-#if (ES_BUILD_PCL || PROJECTN)
- internal static Attribute GetCustomAttributeHelper(Type type, Type attributeType, EventManifestOptions flags = EventManifestOptions.None)
- {
- return GetCustomAttributeHelper(type.GetTypeInfo(), attributeType, flags);
- }
-#endif
-
- // Helper to deal with the fact that the type we are reflecting over might be loaded in the ReflectionOnly context.
- // When that is the case, we have the build the custom assemblies on a member by hand.
- internal static Attribute GetCustomAttributeHelper(MemberInfo member, Type attributeType, EventManifestOptions flags = EventManifestOptions.None)
- {
- if (!member.Module.Assembly.ReflectionOnly() && (flags & EventManifestOptions.AllowEventSourceOverride) == 0)
- {
- // Let the runtime to the work for us, since we can execute code in this context.
- Attribute firstAttribute = null;
- foreach (var attribute in member.GetCustomAttributes(attributeType, false))
- {
- firstAttribute = (Attribute)attribute;
- break;
- }
- return firstAttribute;
- }
-
-#if (!ES_BUILD_PCL && !PROJECTN)
- // In the reflection only context, we have to do things by hand.
- string fullTypeNameToFind = attributeType.FullName;
-
-#if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT
- fullTypeNameToFind = fullTypeNameToFind.Replace("System.Diagnostics.Eventing", "System.Diagnostics.Tracing");
-#endif
-
- foreach (CustomAttributeData data in CustomAttributeData.GetCustomAttributes(member))
- {
- if (AttributeTypeNamesMatch(attributeType, data.Constructor.ReflectedType))
- {
- Attribute attr = null;
-
- Debug.Assert(data.ConstructorArguments.Count <= 1);
-
- if (data.ConstructorArguments.Count == 1)
- {
- attr = (Attribute)Activator.CreateInstance(attributeType, new object[] { data.ConstructorArguments[0].Value });
- }
- else if (data.ConstructorArguments.Count == 0)
- {
- attr = (Attribute)Activator.CreateInstance(attributeType);
- }
-
- if (attr != null)
- {
- Type t = attr.GetType();
-
- foreach (CustomAttributeNamedArgument namedArgument in data.NamedArguments)
- {
- PropertyInfo p = t.GetProperty(namedArgument.MemberInfo.Name, BindingFlags.Public | BindingFlags.Instance);
- object value = namedArgument.TypedValue.Value;
-
- if (p.PropertyType.IsEnum)
- {
- value = Enum.Parse(p.PropertyType, value.ToString());
- }
-
- p.SetValue(attr, value, null);
- }
-
- return attr;
- }
- }
- }
-
- return null;
-#else // ES_BUILD_PCL && PROJECTN
- throw new ArgumentException(Resources.GetResourceString("EventSource", nameof(EventSource_PCLPlatformNotSupportedReflection)));
-#endif
- }
-
- /// <summary>
- /// Evaluates if two related "EventSource"-domain types should be considered the same
- /// </summary>
- /// <param name="attributeType">The attribute type in the load context - it's associated with the running
- /// EventSource type. This type may be different fromt he base type of the user-defined EventSource.</param>
- /// <param name="reflectedAttributeType">The attribute type in the reflection context - it's associated with
- /// the user-defined EventSource, and is in the same assembly as the eventSourceType passed to
- /// </param>
- /// <returns>True - if the types should be considered equivalent, False - otherwise</returns>
- private static bool AttributeTypeNamesMatch(Type attributeType, Type reflectedAttributeType)
- {
- return
- // are these the same type?
- attributeType == reflectedAttributeType ||
- // are the full typenames equal?
- string.Equals(attributeType.FullName, reflectedAttributeType.FullName, StringComparison.Ordinal) ||
- // are the typenames equal and the namespaces under "Diagnostics.Tracing" (typically
- // either Microsoft.Diagnostics.Tracing or System.Diagnostics.Tracing)?
- string.Equals(attributeType.Name, reflectedAttributeType.Name, StringComparison.Ordinal) &&
- attributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal) &&
- (reflectedAttributeType.Namespace.EndsWith("Diagnostics.Tracing", StringComparison.Ordinal)
-#if EVENT_SOURCE_LEGACY_NAMESPACE_SUPPORT
- || reflectedAttributeType.Namespace.EndsWith("Diagnostics.Eventing", StringComparison.Ordinal)
-#endif
-);
- }
-
- private static Type GetEventSourceBaseType(Type eventSourceType, bool allowEventSourceOverride, bool reflectionOnly)
- {
- // return false for "object" and interfaces
- if (eventSourceType.BaseType() == null)
- return null;
-
- // now go up the inheritance chain until hitting a concrete type ("object" at worse)
- do
- {
- eventSourceType = eventSourceType.BaseType();
- }
- while (eventSourceType != null && eventSourceType.IsAbstract());
-
- if (eventSourceType != null)
- {
- if (!allowEventSourceOverride)
- {
- if (reflectionOnly && eventSourceType.FullName != typeof(EventSource).FullName ||
- !reflectionOnly && eventSourceType != typeof(EventSource))
- return null;
- }
- else
- {
- if (eventSourceType.Name != "EventSource")
- return null;
- }
- }
- return eventSourceType;
- }
-
- // Use reflection to look at the attributes of a class, and generate a manifest for it (as UTF8) and
- // return the UTF8 bytes. It also sets up the code:EventData structures needed to dispatch events
- // at run time. 'source' is the event source to place the descriptors. If it is null,
- // then the descriptors are not creaed, and just the manifest is generated.
- private static byte[] CreateManifestAndDescriptors(Type eventSourceType, string eventSourceDllName, EventSource source,
- EventManifestOptions flags = EventManifestOptions.None)
- {
- ManifestBuilder manifest = null;
- bool bNeedsManifest = source != null ? !source.SelfDescribingEvents : true;
- Exception exception = null; // exception that might get raised during validation b/c we couldn't/didn't recover from a previous error
- byte[] res = null;
-
- if (eventSourceType.IsAbstract() && (flags & EventManifestOptions.Strict) == 0)
- return null;
-
-#if DEBUG && ES_BUILD_STANDALONE
- TestSupport.TestHooks.MaybeThrow(eventSourceType,
- TestSupport.Category.ManifestError,
- "EventSource_CreateManifestAndDescriptors",
- new ArgumentException("EventSource_CreateManifestAndDescriptors"));
-#endif
-
- try
- {
- MethodInfo[] methods = eventSourceType.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- EventAttribute defaultEventAttribute;
- int eventId = 1; // The number given to an event that does not have a explicitly given ID.
- EventMetadata[] eventData = null;
- Dictionary<string, string> eventsByName = null;
- if (source != null || (flags & EventManifestOptions.Strict) != 0)
- {
- eventData = new EventMetadata[methods.Length + 1];
- eventData[0].Name = ""; // Event 0 is the 'write messages string' event, and has an empty name.
- }
-
- // See if we have localization information.
- ResourceManager resources = null;
- EventSourceAttribute eventSourceAttrib = (EventSourceAttribute)GetCustomAttributeHelper(eventSourceType, typeof(EventSourceAttribute), flags);
- if (eventSourceAttrib != null && eventSourceAttrib.LocalizationResources != null)
- resources = new ResourceManager(eventSourceAttrib.LocalizationResources, eventSourceType.Assembly());
-
- manifest = new ManifestBuilder(GetName(eventSourceType, flags), GetGuid(eventSourceType), eventSourceDllName,
- resources, flags);
-
- // Add an entry unconditionally for event ID 0 which will be for a string message.
- manifest.StartEvent("EventSourceMessage", new EventAttribute(0) { Level = EventLevel.LogAlways, Task = (EventTask)0xFFFE });
- manifest.AddEventParameter(typeof(string), "message");
- manifest.EndEvent();
-
- // eventSourceType must be sealed and must derive from this EventSource
- if ((flags & EventManifestOptions.Strict) != 0)
- {
- bool typeMatch = GetEventSourceBaseType(eventSourceType, (flags & EventManifestOptions.AllowEventSourceOverride) != 0, eventSourceType.Assembly().ReflectionOnly()) != null;
-
- if (!typeMatch)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_TypeMustDeriveFromEventSource"));
- }
- if (!eventSourceType.IsAbstract() && !eventSourceType.IsSealed())
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_TypeMustBeSealedOrAbstract"));
- }
- }
-
- // Collect task, opcode, keyword and channel information
-#if FEATURE_MANAGED_ETW_CHANNELS && FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- foreach (var providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes", "Channels" })
-#else
- foreach (var providerEnumKind in new string[] { "Keywords", "Tasks", "Opcodes" })
-#endif
- {
- Type nestedType = eventSourceType.GetNestedType(providerEnumKind);
- if (nestedType != null)
- {
- if (eventSourceType.IsAbstract())
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_AbstractMustNotDeclareKTOC", nestedType.Name));
- }
- else
- {
- foreach (FieldInfo staticField in nestedType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
- {
- AddProviderEnumKind(manifest, staticField, providerEnumKind);
- }
- }
- }
- }
- // ensure we have keywords for the session-filtering reserved bits
- {
- manifest.AddKeyword("Session3", (long)0x1000 << 32);
- manifest.AddKeyword("Session2", (long)0x2000 << 32);
- manifest.AddKeyword("Session1", (long)0x4000 << 32);
- manifest.AddKeyword("Session0", (long)0x8000 << 32);
- }
-
- if (eventSourceType != typeof(EventSource))
- {
- for (int i = 0; i < methods.Length; i++)
- {
- MethodInfo method = methods[i];
- ParameterInfo[] args = method.GetParameters();
-
- // Get the EventDescriptor (from the Custom attributes)
- EventAttribute eventAttribute = (EventAttribute)GetCustomAttributeHelper(method, typeof(EventAttribute), flags);
-
- // Compat: until v4.5.1 we ignored any non-void returning methods as well as virtual methods for
- // the only reason of limiting the number of methods considered to be events. This broke a common
- // design of having event sources implement specific interfaces. To fix this in a compatible way
- // we will now allow both non-void returning and virtual methods to be Event methods, as long
- // as they are marked with the [Event] attribute
- if (/* method.IsVirtual || */ method.IsStatic)
- {
- continue;
- }
-
- if (eventSourceType.IsAbstract())
- {
- if (eventAttribute != null)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", method.Name, eventAttribute.EventId));
- }
- continue;
- }
- else if (eventAttribute == null)
- {
- // Methods that don't return void can't be events, if they're NOT marked with [Event].
- // (see Compat comment above)
- if (method.ReturnType != typeof(void))
- {
- continue;
- }
-
- // Continue to ignore virtual methods if they do NOT have the [Event] attribute
- // (see Compat comment above)
- if (method.IsVirtual)
- {
- continue;
- }
-
- // If we explicitly mark the method as not being an event, then honor that.
- if (GetCustomAttributeHelper(method, typeof(NonEventAttribute), flags) != null)
- continue;
-
- defaultEventAttribute = new EventAttribute(eventId);
- eventAttribute = defaultEventAttribute;
- }
- else if (eventAttribute.EventId <= 0)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_NeedPositiveId", method.Name), true);
- continue; // don't validate anything else for this event
- }
- if (method.Name.LastIndexOf('.') >= 0)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_EventMustNotBeExplicitImplementation", method.Name, eventAttribute.EventId));
- }
-
- eventId++;
- string eventName = method.Name;
-
- if (eventAttribute.Opcode == EventOpcode.Info) // We are still using the default opcode.
- {
- // By default pick a task ID derived from the EventID, starting with the highest task number and working back
- bool noTask = (eventAttribute.Task == EventTask.None);
- if (noTask)
- eventAttribute.Task = (EventTask)(0xFFFE - eventAttribute.EventId);
-
- // Unless we explicitly set the opcode to Info (to override the auto-generate of Start or Stop opcodes,
- // pick a default opcode based on the event name (either Info or start or stop if the name ends with that suffix).
- if (!eventAttribute.IsOpcodeSet)
- eventAttribute.Opcode = GetOpcodeWithDefault(EventOpcode.Info, eventName);
-
- // Make the stop opcode have the same task as the start opcode.
- if (noTask)
- {
- if (eventAttribute.Opcode == EventOpcode.Start)
- {
- string taskName = eventName.Substring(0, eventName.Length - s_ActivityStartSuffix.Length); // Remove the Stop suffix to get the task name
- if (string.Compare(eventName, 0, taskName, 0, taskName.Length) == 0 &&
- string.Compare(eventName, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(eventName.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0)
- {
- // Add a task that is just the task name for the start event. This suppress the auto-task generation
- // That would otherwise happen (and create 'TaskName'Start as task name rather than just 'TaskName'
- manifest.AddTask(taskName, (int)eventAttribute.Task);
- }
- }
- else if (eventAttribute.Opcode == EventOpcode.Stop)
- {
- // Find the start associated with this stop event. We require start to be immediately before the stop
- int startEventId = eventAttribute.EventId - 1;
- if (eventData != null && startEventId < eventData.Length)
- {
- Debug.Assert(0 <= startEventId); // Since we reserve id 0, we know that id-1 is <= 0
- EventMetadata startEventMetadata = eventData[startEventId];
-
- // If you remove the Stop and add a Start does that name match the Start Event's Name?
- // Ideally we would throw an error
- string taskName = eventName.Substring(0, eventName.Length - s_ActivityStopSuffix.Length); // Remove the Stop suffix to get the task name
- if (startEventMetadata.Descriptor.Opcode == (byte)EventOpcode.Start &&
- string.Compare(startEventMetadata.Name, 0, taskName, 0, taskName.Length) == 0 &&
- string.Compare(startEventMetadata.Name, taskName.Length, s_ActivityStartSuffix, 0, Math.Max(startEventMetadata.Name.Length - taskName.Length, s_ActivityStartSuffix.Length)) == 0)
- {
-
- // Make the stop event match the start event
- eventAttribute.Task = (EventTask)startEventMetadata.Descriptor.Task;
- noTask = false;
- }
- }
- if (noTask && (flags & EventManifestOptions.Strict) != 0) // Throw an error if we can compatibly.
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_StopsFollowStarts"));
- }
- }
- }
- }
-
- bool hasRelatedActivityID = RemoveFirstArgIfRelatedActivityId(ref args);
- if (!(source != null && source.SelfDescribingEvents))
- {
- manifest.StartEvent(eventName, eventAttribute);
- for (int fieldIdx = 0; fieldIdx < args.Length; fieldIdx++)
- {
- manifest.AddEventParameter(args[fieldIdx].ParameterType, args[fieldIdx].Name);
- }
- manifest.EndEvent();
- }
-
- if (source != null || (flags & EventManifestOptions.Strict) != 0)
- {
- // Do checking for user errors (optional, but not a big deal so we do it).
- DebugCheckEvent(ref eventsByName, eventData, method, eventAttribute, manifest, flags);
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- // add the channel keyword for Event Viewer channel based filters. This is added for creating the EventDescriptors only
- // and is not required for the manifest
- if (eventAttribute.Channel != EventChannel.None)
- {
- unchecked
- {
- eventAttribute.Keywords |= (EventKeywords)manifest.GetChannelKeyword(eventAttribute.Channel, (ulong)eventAttribute.Keywords);
- }
- }
-#endif
- string eventKey = "event_" + eventName;
- string msg = manifest.GetLocalizedMessage(eventKey, CultureInfo.CurrentUICulture, etwFormat: false);
- // overwrite inline message with the localized message
- if (msg != null) eventAttribute.Message = msg;
-
- AddEventDescriptor(ref eventData, eventName, eventAttribute, args, hasRelatedActivityID);
- }
- }
- }
-
- // Tell the TraceLogging stuff where to start allocating its own IDs.
- NameInfo.ReserveEventIDsBelow(eventId);
-
- if (source != null)
- {
- TrimEventDescriptors(ref eventData);
- source.m_eventData = eventData; // officially initialize it. We do this at most once (it is racy otherwise).
-#if FEATURE_MANAGED_ETW_CHANNELS
- source.m_channelData = manifest.GetChannelData();
-#endif
- }
-
- // if this is an abstract event source we've already performed all the validation we can
- if (!eventSourceType.IsAbstract() && (source == null || !source.SelfDescribingEvents))
- {
- bNeedsManifest = (flags & EventManifestOptions.OnlyIfNeededForRegistration) == 0
-#if FEATURE_MANAGED_ETW_CHANNELS
- || manifest.GetChannelData().Length > 0
-#endif
-;
-
- // if the manifest is not needed and we're not requested to validate the event source return early
- if (!bNeedsManifest && (flags & EventManifestOptions.Strict) == 0)
- return null;
-
- res = manifest.CreateManifest();
- }
- }
- catch (Exception e)
- {
- // if this is a runtime manifest generation let the exception propagate
- if ((flags & EventManifestOptions.Strict) == 0)
- throw;
- // else store it to include it in the Argument exception we raise below
- exception = e;
- }
-
- if ((flags & EventManifestOptions.Strict) != 0 && (manifest.Errors.Count > 0 || exception != null))
- {
- string msg = String.Empty;
- if (manifest.Errors.Count > 0)
- {
- bool firstError = true;
- foreach (string error in manifest.Errors)
- {
- if (!firstError)
- msg += Environment.NewLine;
- firstError = false;
- msg += error;
- }
- }
- else
- msg = "Unexpected error: " + exception.Message;
-
- throw new ArgumentException(msg, exception);
- }
-
- return bNeedsManifest ? res : null;
- }
-
- private static bool RemoveFirstArgIfRelatedActivityId(ref ParameterInfo[] args)
- {
- // If the first parameter is (case insensitive) 'relatedActivityId' then skip it.
- if (args.Length > 0 && args[0].ParameterType == typeof(Guid) &&
- string.Compare(args[0].Name, "relatedActivityId", StringComparison.OrdinalIgnoreCase) == 0)
- {
- var newargs = new ParameterInfo[args.Length - 1];
- Array.Copy(args, 1, newargs, 0, args.Length - 1);
- args = newargs;
-
- return true;
- }
-
- return false;
- }
-
- // adds a enumeration (keyword, opcode, task or channel) represented by 'staticField'
- // to the manifest.
- private static void AddProviderEnumKind(ManifestBuilder manifest, FieldInfo staticField, string providerEnumKind)
- {
- bool reflectionOnly = staticField.Module.Assembly.ReflectionOnly();
- Type staticFieldType = staticField.FieldType;
- if (!reflectionOnly && (staticFieldType == typeof(EventOpcode)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventOpcode)))
- {
- if (providerEnumKind != "Opcodes") goto Error;
- int value = (int)staticField.GetRawConstantValue();
- manifest.AddOpcode(staticField.Name, value);
- }
- else if (!reflectionOnly && (staticFieldType == typeof(EventTask)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventTask)))
- {
- if (providerEnumKind != "Tasks") goto Error;
- int value = (int)staticField.GetRawConstantValue();
- manifest.AddTask(staticField.Name, value);
- }
- else if (!reflectionOnly && (staticFieldType == typeof(EventKeywords)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventKeywords)))
- {
- if (providerEnumKind != "Keywords") goto Error;
- ulong value = unchecked((ulong)(long)staticField.GetRawConstantValue());
- manifest.AddKeyword(staticField.Name, value);
- }
-#if FEATURE_MANAGED_ETW_CHANNELS && FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- else if (!reflectionOnly && (staticFieldType == typeof(EventChannel)) || AttributeTypeNamesMatch(staticFieldType, typeof(EventChannel)))
- {
- if (providerEnumKind != "Channels") goto Error;
- var channelAttribute = (EventChannelAttribute)GetCustomAttributeHelper(staticField, typeof(EventChannelAttribute));
- manifest.AddChannel(staticField.Name, (byte)staticField.GetRawConstantValue(), channelAttribute);
- }
-#endif
- return;
- Error:
- manifest.ManifestError(Resources.GetResourceString("EventSource_EnumKindMismatch", staticField.Name, staticField.FieldType.Name, providerEnumKind));
- }
-
- // Helper used by code:CreateManifestAndDescriptors to add a code:EventData descriptor for a method
- // with the code:EventAttribute 'eventAttribute'. resourceManger may be null in which case we populate it
- // it is populated if we need to look up message resources
- private static void AddEventDescriptor(ref EventMetadata[] eventData, string eventName,
- EventAttribute eventAttribute, ParameterInfo[] eventParameters,
- bool hasRelatedActivityID)
- {
- if (eventData == null || eventData.Length <= eventAttribute.EventId)
- {
- EventMetadata[] newValues = new EventMetadata[Math.Max(eventData.Length + 16, eventAttribute.EventId + 1)];
- Array.Copy(eventData, 0, newValues, 0, eventData.Length);
- eventData = newValues;
- }
-
- eventData[eventAttribute.EventId].Descriptor = new EventDescriptor(
- eventAttribute.EventId,
- eventAttribute.Version,
-#if FEATURE_MANAGED_ETW_CHANNELS
- (byte)eventAttribute.Channel,
-#else
- (byte)0,
-#endif
- (byte)eventAttribute.Level,
- (byte)eventAttribute.Opcode,
- (int)eventAttribute.Task,
- unchecked((long)((ulong)eventAttribute.Keywords | SessionMask.All.ToEventKeywords())));
-
- eventData[eventAttribute.EventId].Tags = eventAttribute.Tags;
- eventData[eventAttribute.EventId].Name = eventName;
- eventData[eventAttribute.EventId].Parameters = eventParameters;
- eventData[eventAttribute.EventId].Message = eventAttribute.Message;
- eventData[eventAttribute.EventId].ActivityOptions = eventAttribute.ActivityOptions;
- eventData[eventAttribute.EventId].HasRelatedActivityID = hasRelatedActivityID;
- }
-
- // Helper used by code:CreateManifestAndDescriptors that trims the m_eventData array to the correct
- // size after all event descriptors have been added.
- private static void TrimEventDescriptors(ref EventMetadata[] eventData)
- {
- int idx = eventData.Length;
- while (0 < idx)
- {
- --idx;
- if (eventData[idx].Descriptor.EventId != 0)
- break;
- }
- if (eventData.Length - idx > 2) // allow one wasted slot.
- {
- EventMetadata[] newValues = new EventMetadata[idx + 1];
- Array.Copy(eventData, 0, newValues, 0, newValues.Length);
- eventData = newValues;
- }
- }
-
- // Helper used by code:EventListener.AddEventSource and code:EventListener.EventListener
- // when a listener gets attached to a eventSource
- internal void AddListener(EventListener listener)
- {
- lock (EventListener.EventListenersLock)
- {
- bool[] enabledArray = null;
- if (m_eventData != null)
- enabledArray = new bool[m_eventData.Length];
- m_Dispatchers = new EventDispatcher(m_Dispatchers, enabledArray, listener);
- listener.OnEventSourceCreated(this);
- }
- }
-
- // Helper used by code:CreateManifestAndDescriptors to find user mistakes like reusing an event
- // index for two distinct events etc. Throws exceptions when it finds something wrong.
- private static void DebugCheckEvent(ref Dictionary<string, string> eventsByName,
- EventMetadata[] eventData, MethodInfo method, EventAttribute eventAttribute,
- ManifestBuilder manifest, EventManifestOptions options)
- {
- int evtId = eventAttribute.EventId;
- string evtName = method.Name;
- int eventArg = GetHelperCallFirstArg(method);
- if (eventArg >= 0 && evtId != eventArg)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_MismatchIdToWriteEvent", evtName, evtId, eventArg), true);
- }
-
- if (evtId < eventData.Length && eventData[evtId].Descriptor.EventId != 0)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_EventIdReused", evtName, evtId, eventData[evtId].Name), true);
- }
-
- // We give a task to things if they don't have one.
- // TODO this is moderately expensive (N*N). We probably should not even bother....
- Debug.Assert(eventAttribute.Task != EventTask.None || eventAttribute.Opcode != EventOpcode.Info);
- for (int idx = 0; idx < eventData.Length; ++idx)
- {
- // skip unused Event IDs.
- if (eventData[idx].Name == null)
- continue;
-
- if (eventData[idx].Descriptor.Task == (int)eventAttribute.Task && eventData[idx].Descriptor.Opcode == (int)eventAttribute.Opcode)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_TaskOpcodePairReused",
- evtName, evtId, eventData[idx].Name, idx));
- // If we are not strict stop on first error. We have had problems with really large providers taking forever. because of many errors.
- if ((options & EventManifestOptions.Strict) == 0)
- break;
- }
- }
-
- // for non-default event opcodes the user must define a task!
- if (eventAttribute.Opcode != EventOpcode.Info)
- {
- bool failure = false;
- if (eventAttribute.Task == EventTask.None)
- failure = true;
- else
- {
- // If you have the auto-assigned Task, then you did not explicitly set one.
- // This is OK for Start events because we have special logic to assign the task to a prefix derived from the event name
- // But all other cases we want to catch the omission.
- var autoAssignedTask = (EventTask)(0xFFFE - evtId);
- if ((eventAttribute.Opcode != EventOpcode.Start && eventAttribute.Opcode != EventOpcode.Stop) && eventAttribute.Task == autoAssignedTask)
- failure = true;
- }
- if (failure)
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", evtName, evtId));
- }
- }
-
- // If we ever want to enforce the rule: MethodName = TaskName + OpcodeName here's how:
- // (the reason we don't is backwards compat and the need for handling this as a non-fatal error
- // by eventRegister.exe)
- // taskName & opcodeName could be passed in by the caller which has opTab & taskTab handy
- // if (!(((int)eventAttribute.Opcode == 0 && evtName == taskName) || (evtName == taskName+opcodeName)))
- // {
- // throw new WarningException(Resources.GetResourceString("EventSource_EventNameDoesNotEqualTaskPlusOpcode"));
- // }
-
- if (eventsByName == null)
- eventsByName = new Dictionary<string, string>();
-
- if (eventsByName.ContainsKey(evtName))
- {
- manifest.ManifestError(Resources.GetResourceString("EventSource_EventNameReused", evtName), true);
- }
-
- eventsByName[evtName] = evtName;
- }
-
- /// <summary>
- /// This method looks at the IL and tries to pattern match against the standard
- /// 'boilerplate' event body
- /// <code>
- /// { if (Enabled()) WriteEvent(#, ...) }
- /// </code>
- /// If the pattern matches, it returns the literal number passed as the first parameter to
- /// the WriteEvent. This is used to find common user errors (mismatching this
- /// number with the EventAttribute ID). It is only used for validation.
- /// </summary>
- /// <param name="method">The method to probe.</param>
- /// <returns>The literal value or -1 if the value could not be determined. </returns>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Switch statement is clearer than alternatives")]
- static private int GetHelperCallFirstArg(MethodInfo method)
- {
-#if (!ES_BUILD_PCL && !PROJECTN)
- // Currently searches for the following pattern
- //
- // ... // CAN ONLY BE THE INSTRUCTIONS BELOW
- // LDARG0
- // LDC.I4 XXX
- // ... // CAN ONLY BE THE INSTRUCTIONS BELOW CAN'T BE A BRANCH OR A CALL
- // CALL
- // NOP // 0 or more times
- // RET
- //
- // If we find this pattern we return the XXX. Otherwise we return -1.
-#if !CORECLR
- (new ReflectionPermission(ReflectionPermissionFlag.MemberAccess)).Assert();
-#endif
- byte[] instrs = method.GetMethodBody().GetILAsByteArray();
- int retVal = -1;
- for (int idx = 0; idx < instrs.Length;)
- {
- switch (instrs[idx])
- {
- case 0: // NOP
- case 1: // BREAK
- case 2: // LDARG_0
- case 3: // LDARG_1
- case 4: // LDARG_2
- case 5: // LDARG_3
- case 6: // LDLOC_0
- case 7: // LDLOC_1
- case 8: // LDLOC_2
- case 9: // LDLOC_3
- case 10: // STLOC_0
- case 11: // STLOC_1
- case 12: // STLOC_2
- case 13: // STLOC_3
- break;
- case 14: // LDARG_S
- case 16: // STARG_S
- idx++;
- break;
- case 20: // LDNULL
- break;
- case 21: // LDC_I4_M1
- case 22: // LDC_I4_0
- case 23: // LDC_I4_1
- case 24: // LDC_I4_2
- case 25: // LDC_I4_3
- case 26: // LDC_I4_4
- case 27: // LDC_I4_5
- case 28: // LDC_I4_6
- case 29: // LDC_I4_7
- case 30: // LDC_I4_8
- if (idx > 0 && instrs[idx - 1] == 2) // preceeded by LDARG0
- retVal = instrs[idx] - 22;
- break;
- case 31: // LDC_I4_S
- if (idx > 0 && instrs[idx - 1] == 2) // preceeded by LDARG0
- retVal = instrs[idx + 1];
- idx++;
- break;
- case 32: // LDC_I4
- idx += 4;
- break;
- case 37: // DUP
- break;
- case 40: // CALL
- idx += 4;
-
- if (retVal >= 0)
- {
- // Is this call just before return?
- for (int search = idx + 1; search < instrs.Length; search++)
- {
- if (instrs[search] == 42) // RET
- return retVal;
- if (instrs[search] != 0) // NOP
- break;
- }
- }
- retVal = -1;
- break;
- case 44: // BRFALSE_S
- case 45: // BRTRUE_S
- retVal = -1;
- idx++;
- break;
- case 57: // BRFALSE
- case 58: // BRTRUE
- retVal = -1;
- idx += 4;
- break;
- case 103: // CONV_I1
- case 104: // CONV_I2
- case 105: // CONV_I4
- case 106: // CONV_I8
- case 109: // CONV_U4
- case 110: // CONV_U8
- break;
- case 140: // BOX
- case 141: // NEWARR
- idx += 4;
- break;
- case 162: // STELEM_REF
- break;
- case 254: // PREFIX
- idx++;
- // Covers the CEQ instructions used in debug code for some reason.
- if (idx >= instrs.Length || instrs[idx] >= 6)
- goto default;
- break;
- default:
- /* Debug.Assert(false, "Warning: User validation code sub-optimial: Unsuported opcode " + instrs[idx] +
- " at " + idx + " in method " + method.Name); */
- return -1;
- }
- idx++;
- }
-#endif
- return -1;
- }
-
-#if false // This routine is not needed at all, it was used for unit test debugging.
- [Conditional("DEBUG")]
- private static void OutputDebugString(string msg)
- {
-#if !ES_BUILD_PCL
- msg = msg.TrimEnd('\r', '\n') +
- string.Format(CultureInfo.InvariantCulture, ", Thrd({0})" + Environment.NewLine, Thread.CurrentThread.ManagedThreadId);
- System.Diagnostics.Debugger.Log(0, null, msg);
-#endif
- }
-#endif
-
- /// <summary>
- /// Sends an error message to the debugger (outputDebugString), as well as the EventListeners
- /// It will do this even if the EventSource is not enabled.
- /// TODO remove flush parameter it is not used.
- /// </summary>
- [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
- internal void ReportOutOfBandMessage(string msg, bool flush)
- {
- try
- {
-#if (!ES_BUILD_PCL && !PROJECTN)
- // send message to debugger without delay
- System.Diagnostics.Debugger.Log(0, null, String.Format("EventSource Error: {0}{1}", msg, Environment.NewLine));
-#endif
-
- // Send it to all listeners.
- if (m_outOfBandMessageCount < 16 - 1) // Note this is only if size byte
- m_outOfBandMessageCount++;
- else
- {
- if (m_outOfBandMessageCount == 16)
- return;
- m_outOfBandMessageCount = 16; // Mark that we hit the limit. Notify them that this is the case.
- msg = "Reached message limit. End of EventSource error messages.";
- }
-
- WriteEventString(EventLevel.LogAlways, -1, msg);
- WriteStringToAllListeners("EventSourceMessage", msg);
- }
- catch (Exception) { } // If we fail during last chance logging, well, we have to give up....
- }
-
- private EventSourceSettings ValidateSettings(EventSourceSettings settings)
- {
- var evtFormatMask = EventSourceSettings.EtwManifestEventFormat |
- EventSourceSettings.EtwSelfDescribingEventFormat;
- if ((settings & evtFormatMask) == evtFormatMask)
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_InvalidEventFormat"), nameof(settings));
- }
-
- // If you did not explicitly ask for manifest, you get self-describing.
- if ((settings & evtFormatMask) == 0)
- settings |= EventSourceSettings.EtwSelfDescribingEventFormat;
- return settings;
- }
-
- private bool ThrowOnEventWriteErrors
- {
- get { return (m_config & EventSourceSettings.ThrowOnEventWriteErrors) != 0; }
- set
- {
- if (value) m_config |= EventSourceSettings.ThrowOnEventWriteErrors;
- else m_config &= ~EventSourceSettings.ThrowOnEventWriteErrors;
- }
- }
-
- private bool SelfDescribingEvents
- {
- get
- {
- Debug.Assert(((m_config & EventSourceSettings.EtwManifestEventFormat) != 0) !=
- ((m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0));
- return (m_config & EventSourceSettings.EtwSelfDescribingEventFormat) != 0;
- }
- set
- {
- if (!value)
- {
- m_config |= EventSourceSettings.EtwManifestEventFormat;
- m_config &= ~EventSourceSettings.EtwSelfDescribingEventFormat;
- }
- else
- {
- m_config |= EventSourceSettings.EtwSelfDescribingEventFormat;
- m_config &= ~EventSourceSettings.EtwManifestEventFormat;
- }
- }
- }
-
-#if FEATURE_ACTIVITYSAMPLING
- private void ReportActivitySamplingInfo(EventListener listener, SessionMask sessions)
- {
- Debug.Assert(listener == null || (uint)sessions == (uint)SessionMask.FromId(0));
-
- for (int perEventSourceSessionId = 0; perEventSourceSessionId < SessionMask.MAX; ++perEventSourceSessionId)
- {
- if (!sessions[perEventSourceSessionId])
- continue;
-
- ActivityFilter af;
- if (listener == null)
- {
- EtwSession etwSession = m_etwSessionIdMap[perEventSourceSessionId];
- Debug.Assert(etwSession != null);
- af = etwSession.m_activityFilter;
- }
- else
- {
- af = listener.m_activityFilter;
- }
-
- if (af == null)
- continue;
-
- SessionMask m = new SessionMask();
- m[perEventSourceSessionId] = true;
-
- foreach (var t in af.GetFilterAsTuple(m_guid))
- {
- WriteStringToListener(listener, string.Format(CultureInfo.InvariantCulture, "Session {0}: {1} = {2}", perEventSourceSessionId, t.Item1, t.Item2), m);
- }
-
- bool participateInSampling = (listener == null) ?
- m_activityFilteringForETWEnabled[perEventSourceSessionId] :
- GetDispatcher(listener).m_activityFilteringEnabled;
- WriteStringToListener(listener, string.Format(CultureInfo.InvariantCulture, "Session {0}: Activity Sampling support: {1}",
- perEventSourceSessionId, participateInSampling ? "enabled" : "disabled"), m);
- }
- }
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // private instance state
- private string m_name; // My friendly name (privided in ctor)
- internal int m_id; // A small integer that is unique to this instance.
- private Guid m_guid; // GUID representing the ETW eventSource to the OS.
- internal volatile EventMetadata[] m_eventData; // None per-event data
- private volatile byte[] m_rawManifest; // Bytes to send out representing the event schema
-
- private EventHandler<EventCommandEventArgs> m_eventCommandExecuted;
-
- private EventSourceSettings m_config; // configuration information
-
- private bool m_eventSourceDisposed; // has Dispose been called.
-
- // Enabling bits
- private bool m_eventSourceEnabled; // am I enabled (any of my events are enabled for any dispatcher)
- internal EventLevel m_level; // highest level enabled by any output dispatcher
- internal EventKeywords m_matchAnyKeyword; // the logical OR of all levels enabled by any output dispatcher (zero is a special case) meaning 'all keywords'
-
- // Dispatching state
- internal volatile EventDispatcher m_Dispatchers; // Linked list of code:EventDispatchers we write the data to (we also do ETW specially)
-#if FEATURE_MANAGED_ETW
- private volatile OverideEventProvider m_provider; // This hooks up ETW commands to our 'OnEventCommand' callback
-#endif
- private bool m_completelyInited; // The EventSource constructor has returned without exception.
- private Exception m_constructionException; // If there was an exception construction, this is it
- private byte m_outOfBandMessageCount; // The number of out of band messages sent (we throttle them
- private EventCommandEventArgs m_deferredCommands;// If we get commands before we are fully we store them here and run the when we are fully inited.
-
- private string[] m_traits; // Used to implement GetTraits
-
- internal static uint s_currentPid; // current process id, used in synthesizing quasi-GUIDs
- [ThreadStatic]
- private static byte m_EventSourceExceptionRecurenceCount = 0; // current recursion count inside ThrowEventSourceException
-
- [ThreadStatic]
- private static bool m_EventSourceInDecodeObject = false;
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- internal volatile ulong[] m_channelData;
-#endif
-
-#if FEATURE_ACTIVITYSAMPLING
- private SessionMask m_curLiveSessions; // the activity-tracing aware sessions' bits
- private EtwSession[] m_etwSessionIdMap; // the activity-tracing aware sessions
- private List<EtwSession> m_legacySessions; // the legacy ETW sessions listening to this source
- internal long m_keywordTriggers; // a bit is set if it corresponds to a keyword that's part of an enabled triggering event
- internal SessionMask m_activityFilteringForETWEnabled; // does THIS EventSource have activity filtering turned on for each ETW session
- static internal Action<Guid> s_activityDying; // Fires when something calls SetCurrentThreadToActivity()
- // Also used to mark that activity tracing is on for some case
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // We use a single instance of ActivityTracker for all EventSources instances to allow correlation between multiple event providers.
- // We have m_activityTracker field simply because instance field is more efficient than static field fetch.
- ActivityTracker m_activityTracker;
- internal const string s_ActivityStartSuffix = "Start";
- internal const string s_ActivityStopSuffix = "Stop";
-
- // used for generating GUID from eventsource name
- private static readonly byte[] namespaceBytes = new byte[] {
- 0x48, 0x2C, 0x2D, 0xB2, 0xC3, 0x90, 0x47, 0xC8,
- 0x87, 0xF8, 0x1A, 0x15, 0xBF, 0xC1, 0x30, 0xFB,
- };
-
- #endregion
- }
-
- /// <summary>
- /// Enables specifying event source configuration options to be used in the EventSource constructor.
- /// </summary>
- [Flags]
- public enum EventSourceSettings
- {
- /// <summary>
- /// This specifies none of the special configuration options should be enabled.
- /// </summary>
- Default = 0,
- /// <summary>
- /// Normally an EventSource NEVER throws; setting this option will tell it to throw when it encounters errors.
- /// </summary>
- ThrowOnEventWriteErrors = 1,
- /// <summary>
- /// Setting this option is a directive to the ETW listener should use manifest-based format when
- /// firing events. This is the default option when defining a type derived from EventSource
- /// (using the protected EventSource constructors).
- /// Only one of EtwManifestEventFormat or EtwSelfDescribingEventFormat should be specified
- /// </summary>
- EtwManifestEventFormat = 4,
- /// <summary>
- /// Setting this option is a directive to the ETW listener should use self-describing event format
- /// when firing events. This is the default option when creating a new instance of the EventSource
- /// type (using the public EventSource constructors).
- /// Only one of EtwManifestEventFormat or EtwSelfDescribingEventFormat should be specified
- /// </summary>
- EtwSelfDescribingEventFormat = 8,
- }
-
- /// <summary>
- /// An EventListener represents a target for the events generated by EventSources (that is subclasses
- /// of <see cref="EventSource"/>), in the current appdomain. When a new EventListener is created
- /// it is logically attached to all eventSources in that appdomain. When the EventListener is Disposed, then
- /// it is disconnected from the event eventSources. Note that there is a internal list of STRONG references
- /// to EventListeners, which means that relying on the lack of references to EventListeners to clean up
- /// EventListeners will NOT work. You must call EventListener.Dispose explicitly when a dispatcher is no
- /// longer needed.
- /// <para>
- /// Once created, EventListeners can enable or disable on a per-eventSource basis using verbosity levels
- /// (<see cref="EventLevel"/>) and bitfields (<see cref="EventKeywords"/>) to further restrict the set of
- /// events to be sent to the dispatcher. The dispatcher can also send arbitrary commands to a particular
- /// eventSource using the 'SendCommand' method. The meaning of the commands are eventSource specific.
- /// </para><para>
- /// The Null Guid (that is (new Guid()) has special meaning as a wildcard for 'all current eventSources in
- /// the appdomain'. Thus it is relatively easy to turn on all events in the appdomain if desired.
- /// </para><para>
- /// It is possible for there to be many EventListener's defined in a single appdomain. Each dispatcher is
- /// logically independent of the other listeners. Thus when one dispatcher enables or disables events, it
- /// affects only that dispatcher (other listeners get the events they asked for). It is possible that
- /// commands sent with 'SendCommand' would do a semantic operation that would affect the other listeners
- /// (like doing a GC, or flushing data ...), but this is the exception rather than the rule.
- /// </para><para>
- /// Thus the model is that each EventSource keeps a list of EventListeners that it is sending events
- /// to. Associated with each EventSource-dispatcher pair is a set of filtering criteria that determine for
- /// that eventSource what events that dispatcher will receive.
- /// </para><para>
- /// Listeners receive the events on their 'OnEventWritten' method. Thus subclasses of EventListener must
- /// override this method to do something useful with the data.
- /// </para><para>
- /// In addition, when new eventSources are created, the 'OnEventSourceCreate' method is called. The
- /// invariant associated with this callback is that every eventSource gets exactly one
- /// 'OnEventSourceCreate' call for ever eventSource that can potentially send it log messages. In
- /// particular when a EventListener is created, typically a series of OnEventSourceCreate' calls are
- /// made to notify the new dispatcher of all the eventSources that existed before the EventListener was
- /// created.
- /// </para>
- /// </summary>
- public class EventListener : IDisposable
- {
- private event EventHandler<EventSourceCreatedEventArgs> _EventSourceCreated;
-
- /// <summary>
- /// This event is raised whenever a new eventSource is 'attached' to the dispatcher.
- /// This can happen for all existing EventSources when the EventListener is created
- /// as well as for any EventSources that come into existence after the EventListener
- /// has been created.
- ///
- /// These 'catch up' events are called during the construction of the EventListener.
- /// Subclasses need to be prepared for that.
- ///
- /// In a multi-threaded environment, it is possible that 'EventSourceEventWrittenCallback'
- /// events for a particular eventSource to occur BEFORE the EventSourceCreatedCallback is issued.
- /// </summary>
- public event EventHandler<EventSourceCreatedEventArgs> EventSourceCreated
- {
- add
- {
- CallBackForExistingEventSources(false, value);
-
- this._EventSourceCreated = (EventHandler<EventSourceCreatedEventArgs>)Delegate.Combine(_EventSourceCreated, value);
- }
- remove
- {
- this._EventSourceCreated = (EventHandler<EventSourceCreatedEventArgs>)Delegate.Remove(_EventSourceCreated, value);
- }
- }
-
- /// <summary>
- /// This event is raised whenever an event has been written by a EventSource for which
- /// the EventListener has enabled events.
- /// </summary>
- public event EventHandler<EventWrittenEventArgs> EventWritten;
-
- /// <summary>
- /// Create a new EventListener in which all events start off turned off (use EnableEvents to turn
- /// them on).
- /// </summary>
- public EventListener()
- {
- // This will cause the OnEventSourceCreated callback to fire.
- CallBackForExistingEventSources(true, (obj, args) => args.EventSource.AddListener((EventListener)obj));
- }
-
- /// <summary>
- /// Dispose should be called when the EventListener no longer desires 'OnEvent*' callbacks. Because
- /// there is an internal list of strong references to all EventListeners, calling 'Dispose' directly
- /// is the only way to actually make the listen die. Thus it is important that users of EventListener
- /// call Dispose when they are done with their logging.
- /// </summary>
-#if ES_BUILD_STANDALONE
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1063:ImplementIDisposableCorrectly")]
-#endif
- public virtual void Dispose()
- {
- lock (EventListenersLock)
- {
- if (s_Listeners != null)
- {
- if (this == s_Listeners)
- {
- EventListener cur = s_Listeners;
- s_Listeners = this.m_Next;
- RemoveReferencesToListenerInEventSources(cur);
- }
- else
- {
- // Find 'this' from the s_Listeners linked list.
- EventListener prev = s_Listeners;
- for (;;)
- {
- EventListener cur = prev.m_Next;
- if (cur == null)
- break;
- if (cur == this)
- {
- // Found our Listener, remove references to to it in the eventSources
- prev.m_Next = cur.m_Next; // Remove entry.
- RemoveReferencesToListenerInEventSources(cur);
- break;
- }
- prev = cur;
- }
- }
- }
- Validate();
- }
- }
- // We don't expose a Dispose(bool), because the contract is that you don't have any non-syncronous
- // 'cleanup' associated with this object
-
- /// <summary>
- /// Enable all events from the eventSource identified by 'eventSource' to the current
- /// dispatcher that have a verbosity level of 'level' or lower.
- ///
- /// This call can have the effect of REDUCING the number of events sent to the
- /// dispatcher if 'level' indicates a less verbose level than was previously enabled.
- ///
- /// This call never has an effect on other EventListeners.
- ///
- /// </summary>
- public void EnableEvents(EventSource eventSource, EventLevel level)
- {
- EnableEvents(eventSource, level, EventKeywords.None);
- }
- /// <summary>
- /// Enable all events from the eventSource identified by 'eventSource' to the current
- /// dispatcher that have a verbosity level of 'level' or lower and have a event keyword
- /// matching any of the bits in 'matchAnyKeyword'.
- ///
- /// This call can have the effect of REDUCING the number of events sent to the
- /// dispatcher if 'level' indicates a less verbose level than was previously enabled or
- /// if 'matchAnyKeyword' has fewer keywords set than where previously set.
- ///
- /// This call never has an effect on other EventListeners.
- /// </summary>
- public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword)
- {
- EnableEvents(eventSource, level, matchAnyKeyword, null);
- }
- /// <summary>
- /// Enable all events from the eventSource identified by 'eventSource' to the current
- /// dispatcher that have a verbosity level of 'level' or lower and have a event keyword
- /// matching any of the bits in 'matchAnyKeyword' as well as any (eventSource specific)
- /// effect passing additional 'key-value' arguments 'arguments' might have.
- ///
- /// This call can have the effect of REDUCING the number of events sent to the
- /// dispatcher if 'level' indicates a less verbose level than was previously enabled or
- /// if 'matchAnyKeyword' has fewer keywords set than where previously set.
- ///
- /// This call never has an effect on other EventListeners.
- /// </summary>
- public void EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword, IDictionary<string, string> arguments)
- {
- if (eventSource == null)
- {
- throw new ArgumentNullException(nameof(eventSource));
- }
- Contract.EndContractBlock();
-
- eventSource.SendCommand(this, 0, 0, EventCommand.Update, true, level, matchAnyKeyword, arguments);
- }
- /// <summary>
- /// Disables all events coming from eventSource identified by 'eventSource'.
- ///
- /// This call never has an effect on other EventListeners.
- /// </summary>
- public void DisableEvents(EventSource eventSource)
- {
- if (eventSource == null)
- {
- throw new ArgumentNullException(nameof(eventSource));
- }
- Contract.EndContractBlock();
-
- eventSource.SendCommand(this, 0, 0, EventCommand.Update, false, EventLevel.LogAlways, EventKeywords.None, null);
- }
-
- /// <summary>
- /// EventSourceIndex is small non-negative integer (suitable for indexing in an array)
- /// identifying EventSource. It is unique per-appdomain. Some EventListeners might find
- /// it useful to store additional information about each eventSource connected to it,
- /// and EventSourceIndex allows this extra information to be efficiently stored in a
- /// (growable) array (eg List(T)).
- /// </summary>
- public static int EventSourceIndex(EventSource eventSource) { return eventSource.m_id; }
-
- /// <summary>
- /// This method is called whenever a new eventSource is 'attached' to the dispatcher.
- /// This can happen for all existing EventSources when the EventListener is created
- /// as well as for any EventSources that come into existence after the EventListener
- /// has been created.
- ///
- /// These 'catch up' events are called during the construction of the EventListener.
- /// Subclasses need to be prepared for that.
- ///
- /// In a multi-threaded environment, it is possible that 'OnEventWritten' callbacks
- /// for a particular eventSource to occur BEFORE the OnEventSourceCreated is issued.
- /// </summary>
- /// <param name="eventSource"></param>
- internal protected virtual void OnEventSourceCreated(EventSource eventSource)
- {
- EventHandler<EventSourceCreatedEventArgs> callBack = this._EventSourceCreated;
- if (callBack != null)
- {
- EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs();
- args.EventSource = eventSource;
- callBack(this, args);
- }
- }
-
- /// <summary>
- /// This method is called whenever an event has been written by a EventSource for which
- /// the EventListener has enabled events.
- /// </summary>
- /// <param name="eventData"></param>
- internal protected virtual void OnEventWritten(EventWrittenEventArgs eventData)
- {
- EventHandler<EventWrittenEventArgs> callBack = this.EventWritten;
- if (callBack != null)
- {
- callBack(this, eventData);
- }
- }
-
-
- #region private
- /// <summary>
- /// This routine adds newEventSource to the global list of eventSources, it also assigns the
- /// ID to the eventSource (which is simply the ordinal in the global list).
- ///
- /// EventSources currently do not pro-actively remove themselves from this list. Instead
- /// when eventSources's are GCed, the weak handle in this list naturally gets nulled, and
- /// we will reuse the slot. Today this list never shrinks (but we do reuse entries
- /// that are in the list). This seems OK since the expectation is that EventSources
- /// tend to live for the lifetime of the appdomain anyway (they tend to be used in
- /// global variables).
- /// </summary>
- /// <param name="newEventSource"></param>
- internal static void AddEventSource(EventSource newEventSource)
- {
- lock (EventListenersLock)
- {
- if (s_EventSources == null)
- s_EventSources = new List<WeakReference>(2);
-
- if (!s_EventSourceShutdownRegistered)
- {
- s_EventSourceShutdownRegistered = true;
- }
-
-
- // Periodically search the list for existing entries to reuse, this avoids
- // unbounded memory use if we keep recycling eventSources (an unlikely thing).
- int newIndex = -1;
- if (s_EventSources.Count % 64 == 63) // on every block of 64, fill up the block before continuing
- {
- int i = s_EventSources.Count; // Work from the top down.
- while (0 < i)
- {
- --i;
- WeakReference weakRef = s_EventSources[i];
- if (!weakRef.IsAlive)
- {
- newIndex = i;
- weakRef.Target = newEventSource;
- break;
- }
- }
- }
- if (newIndex < 0)
- {
- newIndex = s_EventSources.Count;
- s_EventSources.Add(new WeakReference(newEventSource));
- }
- newEventSource.m_id = newIndex;
-
- // Add every existing dispatcher to the new EventSource
- for (EventListener listener = s_Listeners; listener != null; listener = listener.m_Next)
- newEventSource.AddListener(listener);
-
- Validate();
- }
- }
-
- // Whenver we have async callbacks from native code, there is an ugly issue where
- // during .NET shutdown native code could be calling the callback, but the CLR
- // has already prohibited callbacks to managed code in the appdomain, causing the CLR
- // to throw a COMPLUS_BOOT_EXCEPTION. The guideline we give is that you must unregister
- // such callbacks on process shutdown or appdomain so that unmanaged code will never
- // do this. This is what this callback is for.
- // See bug 724140 for more
- private static void DisposeOnShutdown(object sender, EventArgs e)
- {
- lock (EventListenersLock)
- {
- foreach (var esRef in s_EventSources)
- {
- EventSource es = esRef.Target as EventSource;
- if (es != null)
- es.Dispose();
- }
- }
- }
-
- /// <summary>
- /// Helper used in code:Dispose that removes any references to 'listenerToRemove' in any of the
- /// eventSources in the appdomain.
- ///
- /// The EventListenersLock must be held before calling this routine.
- /// </summary>
- private static void RemoveReferencesToListenerInEventSources(EventListener listenerToRemove)
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
-#endif
- // Foreach existing EventSource in the appdomain
- foreach (WeakReference eventSourceRef in s_EventSources)
- {
- EventSource eventSource = eventSourceRef.Target as EventSource;
- if (eventSource != null)
- {
- // Is the first output dispatcher the dispatcher we are removing?
- if (eventSource.m_Dispatchers.m_Listener == listenerToRemove)
- eventSource.m_Dispatchers = eventSource.m_Dispatchers.m_Next;
- else
- {
- // Remove 'listenerToRemove' from the eventSource.m_Dispatchers linked list.
- EventDispatcher prev = eventSource.m_Dispatchers;
- for (;;)
- {
- EventDispatcher cur = prev.m_Next;
- if (cur == null)
- {
- Debug.Assert(false, "EventSource did not have a registered EventListener!");
- break;
- }
- if (cur.m_Listener == listenerToRemove)
- {
- prev.m_Next = cur.m_Next; // Remove entry.
- break;
- }
- prev = cur;
- }
- }
- }
- }
- }
-
- /// <summary>
- /// Checks internal consistency of EventSources/Listeners.
- /// </summary>
- [Conditional("DEBUG")]
- internal static void Validate()
- {
- lock (EventListenersLock)
- {
- // Get all listeners
- Dictionary<EventListener, bool> allListeners = new Dictionary<EventListener, bool>();
- EventListener cur = s_Listeners;
- while (cur != null)
- {
- allListeners.Add(cur, true);
- cur = cur.m_Next;
- }
-
- // For all eventSources
- int id = -1;
- foreach (WeakReference eventSourceRef in s_EventSources)
- {
- id++;
- EventSource eventSource = eventSourceRef.Target as EventSource;
- if (eventSource == null)
- continue;
- Debug.Assert(eventSource.m_id == id, "Unexpected event source ID.");
-
- // None listeners on eventSources exist in the dispatcher list.
- EventDispatcher dispatcher = eventSource.m_Dispatchers;
- while (dispatcher != null)
- {
- Debug.Assert(allListeners.ContainsKey(dispatcher.m_Listener), "EventSource has a listener not on the global list.");
- dispatcher = dispatcher.m_Next;
- }
-
- // Every dispatcher is on Dispatcher List of every eventSource.
- foreach (EventListener listener in allListeners.Keys)
- {
- dispatcher = eventSource.m_Dispatchers;
- for (;;)
- {
- Debug.Assert(dispatcher != null, "Listener is not on all eventSources.");
- if (dispatcher.m_Listener == listener)
- break;
- dispatcher = dispatcher.m_Next;
- }
- }
- }
- }
- }
-
- /// <summary>
- /// Gets a global lock that is intended to protect the code:s_Listeners linked list and the
- /// code:s_EventSources WeakReference list. (We happen to use the s_EventSources list as
- /// the lock object)
- /// </summary>
- internal static object EventListenersLock
- {
- get
- {
- if (s_EventSources == null)
- Interlocked.CompareExchange(ref s_EventSources, new List<WeakReference>(2), null);
- return s_EventSources;
- }
- }
-
- private void CallBackForExistingEventSources(bool addToListenersList, EventHandler<EventSourceCreatedEventArgs> callback)
- {
- lock (EventListenersLock)
- {
- // Disallow creating EventListener reentrancy.
- if (s_CreatingListener)
- {
- throw new InvalidOperationException(Resources.GetResourceString("EventSource_ListenerCreatedInsideCallback"));
- }
-
- try
- {
- s_CreatingListener = true;
-
- if (addToListenersList)
- {
- // Add to list of listeners in the system, do this BEFORE firing the 'OnEventSourceCreated' so that
- // Those added sources see this listener.
- this.m_Next = s_Listeners;
- s_Listeners = this;
- }
-
- // Find all existing eventSources call OnEventSourceCreated to 'catchup'
- // Note that we DO have reentrancy here because 'AddListener' calls out to user code (via OnEventSourceCreated callback)
- // We tolerate this by iterating over a copy of the list here. New event sources will take care of adding listeners themselves
- // EventSources are not guaranteed to be added at the end of the s_EventSource list -- We re-use slots when a new source
- // is created.
- WeakReference[] eventSourcesSnapshot = s_EventSources.ToArray();
-
- for (int i = 0; i < eventSourcesSnapshot.Length; i++)
- {
- WeakReference eventSourceRef = eventSourcesSnapshot[i];
- EventSource eventSource = eventSourceRef.Target as EventSource;
- if (eventSource != null)
- {
- EventSourceCreatedEventArgs args = new EventSourceCreatedEventArgs();
- args.EventSource = eventSource;
- callback(this, args);
- }
- }
-
- Validate();
- }
- finally
- {
- s_CreatingListener = false;
- }
- }
-
- }
-
- // Instance fields
- internal volatile EventListener m_Next; // These form a linked list in s_Listeners
-#if FEATURE_ACTIVITYSAMPLING
- internal ActivityFilter m_activityFilter; // If we are filtering by activity on this Listener, this keeps track of it.
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // static fields
-
- /// <summary>
- /// The list of all listeners in the appdomain. Listeners must be explicitly disposed to remove themselves
- /// from this list. Note that EventSources point to their listener but NOT the reverse.
- /// </summary>
- internal static EventListener s_Listeners;
- /// <summary>
- /// The list of all active eventSources in the appdomain. Note that eventSources do NOT
- /// remove themselves from this list this is a weak list and the GC that removes them may
- /// not have happened yet. Thus it can contain event sources that are dead (thus you have
- /// to filter those out.
- /// </summary>
- internal static List<WeakReference> s_EventSources;
-
- /// <summary>
- /// Used to disallow reentrancy.
- /// </summary>
- private static bool s_CreatingListener = false;
-
- /// <summary>
- /// Used to register AD/Process shutdown callbacks.
- /// </summary>
- private static bool s_EventSourceShutdownRegistered = false;
- #endregion
- }
-
- /// <summary>
- /// Passed to the code:EventSource.OnEventCommand callback
- /// </summary>
- public class EventCommandEventArgs : EventArgs
- {
- /// <summary>
- /// Gets the command for the callback.
- /// </summary>
- public EventCommand Command { get; internal set; }
-
- /// <summary>
- /// Gets the arguments for the callback.
- /// </summary>
- public IDictionary<String, String> Arguments { get; internal set; }
-
- /// <summary>
- /// Enables the event that has the specified identifier.
- /// </summary>
- /// <param name="eventId">Event ID of event to be enabled</param>
- /// <returns>true if eventId is in range</returns>
- public bool EnableEvent(int eventId)
- {
- if (Command != EventCommand.Enable && Command != EventCommand.Disable)
- throw new InvalidOperationException();
- return eventSource.EnableEventForDispatcher(dispatcher, eventId, true);
- }
-
- /// <summary>
- /// Disables the event that have the specified identifier.
- /// </summary>
- /// <param name="eventId">Event ID of event to be disabled</param>
- /// <returns>true if eventId is in range</returns>
- public bool DisableEvent(int eventId)
- {
- if (Command != EventCommand.Enable && Command != EventCommand.Disable)
- throw new InvalidOperationException();
- return eventSource.EnableEventForDispatcher(dispatcher, eventId, false);
- }
-
- #region private
-
- internal EventCommandEventArgs(EventCommand command, IDictionary<string, string> arguments, EventSource eventSource,
- EventListener listener, int perEventSourceSessionId, int etwSessionId, bool enable, EventLevel level, EventKeywords matchAnyKeyword)
- {
- this.Command = command;
- this.Arguments = arguments;
- this.eventSource = eventSource;
- this.listener = listener;
- this.perEventSourceSessionId = perEventSourceSessionId;
- this.etwSessionId = etwSessionId;
- this.enable = enable;
- this.level = level;
- this.matchAnyKeyword = matchAnyKeyword;
- }
-
- internal EventSource eventSource;
- internal EventDispatcher dispatcher;
-
- // These are the arguments of sendCommand and are only used for deferring commands until after we are fully initialized.
- internal EventListener listener;
- internal int perEventSourceSessionId;
- internal int etwSessionId;
- internal bool enable;
- internal EventLevel level;
- internal EventKeywords matchAnyKeyword;
- internal EventCommandEventArgs nextCommand; // We form a linked list of these deferred commands.
-
- #endregion
- }
-
- /// <summary>
- /// EventSourceCreatedEventArgs is passed to <see cref="EventListener.EventSourceCreated"/>
- /// </summary>
- public class EventSourceCreatedEventArgs : EventArgs
- {
- /// <summary>
- /// The EventSource that is attaching to the listener.
- /// </summary>
- public EventSource EventSource
- {
- get;
- internal set;
- }
- }
-
- /// <summary>
- /// EventWrittenEventArgs is passed to the user-provided override for
- /// <see cref="EventListener.OnEventWritten"/> when an event is fired.
- /// </summary>
- public class EventWrittenEventArgs : EventArgs
- {
- /// <summary>
- /// The name of the event.
- /// </summary>
- public string EventName
- {
- get
- {
- if (m_eventName != null || EventId < 0) // TraceLogging convention EventID == -1
- {
- return m_eventName;
- }
- else
- return m_eventSource.m_eventData[EventId].Name;
- }
- internal set
- {
- m_eventName = value;
- }
- }
-
- /// <summary>
- /// Gets the event ID for the event that was written.
- /// </summary>
- public int EventId { get; internal set; }
-
- /// <summary>
- /// Gets the activity ID for the thread on which the event was written.
- /// </summary>
- public Guid ActivityId
- {
- get { return EventSource.CurrentThreadActivityId; }
- }
-
- /// <summary>
- /// Gets the related activity ID if one was specified when the event was written.
- /// </summary>
- public Guid RelatedActivityId
- {
- get;
- internal set;
- }
-
- /// <summary>
- /// Gets the payload for the event.
- /// </summary>
- public ReadOnlyCollection<Object> Payload { get; internal set; }
-
- /// <summary>
- /// Gets the payload argument names.
- /// </summary>
- public ReadOnlyCollection<string> PayloadNames
- {
- get
- {
- // For contract based events we create the list lazily.
- if (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)
- {
- names.Add(parameter.Name);
- }
- m_payloadNames = new ReadOnlyCollection<string>(names);
- }
-
- return m_payloadNames;
- }
-
- internal set
- {
- m_payloadNames = value;
- }
- }
-
- /// <summary>
- /// Gets the event source object.
- /// </summary>
- public EventSource EventSource { get { return m_eventSource; } }
-
- /// <summary>
- /// Gets the keywords for the event.
- /// </summary>
- public EventKeywords Keywords
- {
- get
- {
- if (EventId < 0) // TraceLogging convention EventID == -1
- return m_keywords;
-
- return (EventKeywords)m_eventSource.m_eventData[EventId].Descriptor.Keywords;
- }
- }
-
- /// <summary>
- /// Gets the operation code for the event.
- /// </summary>
- public EventOpcode Opcode
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return m_opcode;
- return (EventOpcode)m_eventSource.m_eventData[EventId].Descriptor.Opcode;
- }
- }
-
- /// <summary>
- /// Gets the task for the event.
- /// </summary>
- public EventTask Task
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return EventTask.None;
-
- return (EventTask)m_eventSource.m_eventData[EventId].Descriptor.Task;
- }
- }
-
- /// <summary>
- /// Any provider/user defined options associated with the event.
- /// </summary>
- public EventTags Tags
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return m_tags;
- return m_eventSource.m_eventData[EventId].Tags;
- }
- }
-
- /// <summary>
- /// Gets the message for the event. If the message has {N} parameters they are NOT substituted.
- /// </summary>
- public string Message
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return m_message;
- else
- return m_eventSource.m_eventData[EventId].Message;
- }
- internal set
- {
- m_message = value;
- }
- }
-
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- /// <summary>
- /// Gets the channel for the event.
- /// </summary>
- public EventChannel Channel
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return EventChannel.None;
- return (EventChannel)m_eventSource.m_eventData[EventId].Descriptor.Channel;
- }
- }
-#endif
-
- /// <summary>
- /// Gets the version of the event.
- /// </summary>
- public byte Version
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return 0;
- return m_eventSource.m_eventData[EventId].Descriptor.Version;
- }
- }
-
- /// <summary>
- /// Gets the level for the event.
- /// </summary>
- public EventLevel Level
- {
- get
- {
- if (EventId <= 0) // TraceLogging convention EventID == -1
- return m_level;
- return (EventLevel)m_eventSource.m_eventData[EventId].Descriptor.Level;
- }
- }
-
- #region private
- internal EventWrittenEventArgs(EventSource eventSource)
- {
- m_eventSource = eventSource;
- }
- private string m_message;
- private string m_eventName;
- private EventSource m_eventSource;
- private ReadOnlyCollection<string> m_payloadNames;
- internal EventTags m_tags;
- internal EventOpcode m_opcode;
- internal EventLevel m_level;
- internal EventKeywords m_keywords;
- #endregion
- }
-
- /// <summary>
- /// Allows customizing defaults and specifying localization support for the event source class to which it is applied.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class)]
- public sealed class EventSourceAttribute : Attribute
- {
- /// <summary>
- /// Overrides the ETW name of the event source (which defaults to the class name)
- /// </summary>
- public string Name { get; set; }
-
- /// <summary>
- /// Overrides the default (calculated) Guid of an EventSource type. Explicitly defining a GUID is discouraged,
- /// except when upgrading existing ETW providers to using event sources.
- /// </summary>
- public string Guid { get; set; }
-
- /// <summary>
- /// <para>
- /// EventSources support localization of events. The names used for events, opcodes, tasks, keywords and maps
- /// can be localized to several languages if desired. This works by creating a ResX style string table
- /// (by simply adding a 'Resource File' to your project). This resource file is given a name e.g.
- /// 'DefaultNameSpace.ResourceFileName' which can be passed to the ResourceManager constructor to read the
- /// resources. This name is the value of the LocalizationResources property.
- /// </para><para>
- /// If LocalizationResources property is non-null, then EventSource will look up the localized strings for events by
- /// using the following resource naming scheme
- /// </para>
- /// <para>* event_EVENTNAME</para>
- /// <para>* task_TASKNAME</para>
- /// <para>* keyword_KEYWORDNAME</para>
- /// <para>* map_MAPNAME</para>
- /// <para>
- /// where the capitalized name is the name of the event, task, keyword, or map value that should be localized.
- /// Note that the localized string for an event corresponds to the Message string, and can have {0} values
- /// which represent the payload values.
- /// </para>
- /// </summary>
- public string LocalizationResources { get; set; }
- }
-
- /// <summary>
- /// Any instance methods in a class that subclasses <see cref="EventSource"/> and that return void are
- /// assumed by default to be methods that generate an ETW event. Enough information can be deduced from the
- /// name of the method and its signature to generate basic schema information for the event. The
- /// <see cref="EventAttribute"/> class allows you to specify additional event schema information for an event if
- /// desired.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method)]
- public sealed class EventAttribute : Attribute
- {
- /// <summary>Construct an EventAttribute with specified eventId</summary>
- /// <param name="eventId">ID of the ETW event (an integer between 1 and 65535)</param>
- public EventAttribute(int eventId) { this.EventId = eventId; Level = EventLevel.Informational; this.m_opcodeSet = false; }
- /// <summary>Event's ID</summary>
- public int EventId { get; private set; }
- /// <summary>Event's severity level: indicates the severity or verbosity of the event</summary>
- public EventLevel Level { get; set; }
- /// <summary>Event's keywords: allows classification of events by "categories"</summary>
- public EventKeywords Keywords { get; set; }
- /// <summary>Event's operation code: allows defining operations, generally used with Tasks</summary>
- public EventOpcode Opcode
- {
- get
- {
- return m_opcode;
- }
- set
- {
- this.m_opcode = value;
- this.m_opcodeSet = true;
- }
- }
-
- internal bool IsOpcodeSet
- {
- get
- {
- return m_opcodeSet;
- }
- }
-
- /// <summary>Event's task: allows logical grouping of events</summary>
- public EventTask Task { get; set; }
-#if FEATURE_MANAGED_ETW_CHANNELS
- /// <summary>Event's channel: defines an event log as an additional destination for the event</summary>
- public EventChannel Channel { get; set; }
-#endif
- /// <summary>Event's version</summary>
- public byte Version { get; set; }
-
- /// <summary>
- /// This can be specified to enable formatting and localization of the event's payload. You can
- /// use standard .NET substitution operators (eg {1}) in the string and they will be replaced
- /// with the 'ToString()' of the corresponding part of the event payload.
- /// </summary>
- public string Message { get; set; }
-
- /// <summary>
- /// User defined options associated with the event. These do not have meaning to the EventSource but
- /// are passed through to listeners which given them semantics.
- /// </summary>
- public EventTags Tags { get; set; }
-
- /// <summary>
- /// Allows fine control over the Activity IDs generated by start and stop events
- /// </summary>
- public EventActivityOptions ActivityOptions { get; set; }
-
- #region private
- EventOpcode m_opcode;
- private bool m_opcodeSet;
- #endregion
- }
-
- /// <summary>
- /// By default all instance methods in a class that subclasses code:EventSource that and return
- /// void are assumed to be methods that generate an event. This default can be overridden by specifying
- /// the code:NonEventAttribute
- /// </summary>
- [AttributeUsage(AttributeTargets.Method)]
- public sealed class NonEventAttribute : Attribute
- {
- /// <summary>
- /// Constructs a default NonEventAttribute
- /// </summary>
- public NonEventAttribute() { }
- }
-
- // FUTURE we may want to expose this at some point once we have a partner that can help us validate the design.
-#if FEATURE_MANAGED_ETW_CHANNELS
- /// <summary>
- /// EventChannelAttribute allows customizing channels supported by an EventSource. This attribute must be
- /// applied to an member of type EventChannel defined in a Channels class nested in the EventSource class:
- /// <code>
- /// public static class Channels
- /// {
- /// [Channel(Enabled = true, EventChannelType = EventChannelType.Admin)]
- /// public const EventChannel Admin = (EventChannel)16;
- ///
- /// [Channel(Enabled = false, EventChannelType = EventChannelType.Operational)]
- /// public const EventChannel Operational = (EventChannel)17;
- /// }
- /// </code>
- /// </summary>
- [AttributeUsage(AttributeTargets.Field)]
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- public
-#endif
- class EventChannelAttribute : Attribute
- {
- /// <summary>
- /// Specified whether the channel is enabled by default
- /// </summary>
- public bool Enabled { get; set; }
-
- /// <summary>
- /// Legal values are in EventChannelType
- /// </summary>
- public EventChannelType EventChannelType { get; set; }
-
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- /// <summary>
- /// Specifies the isolation for the channel
- /// </summary>
- public EventChannelIsolation Isolation { get; set; }
-
- /// <summary>
- /// Specifies an SDDL access descriptor that controls access to the log file that backs the channel.
- /// See MSDN ((http://msdn.microsoft.com/en-us/library/windows/desktop/aa382741.aspx) for details.
- /// </summary>
- public string Access { get; set; }
-
- /// <summary>
- /// Allows importing channels defined in external manifests
- /// </summary>
- public string ImportChannel { get; set; }
-#endif
-
- // TODO: there is a convention that the name is the Provider/Type Should we provide an override?
- // public string Name { get; set; }
- }
-
- /// <summary>
- /// Allowed channel types
- /// </summary>
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- public
-#endif
- enum EventChannelType
- {
- /// <summary>The admin channel</summary>
- Admin = 1,
- /// <summary>The operational channel</summary>
- Operational,
- /// <summary>The Analytic channel</summary>
- Analytic,
- /// <summary>The debug channel</summary>
- Debug,
- }
-
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- /// <summary>
- /// Allowed isolation levels. See MSDN (http://msdn.microsoft.com/en-us/library/windows/desktop/aa382741.aspx)
- /// for the default permissions associated with each level. EventChannelIsolation and Access allows control over the
- /// access permissions for the channel and backing file.
- /// </summary>
- public
- enum EventChannelIsolation
- {
- /// <summary>
- /// This is the default isolation level. All channels that specify Application isolation use the same ETW session
- /// </summary>
- Application = 1,
- /// <summary>
- /// All channels that specify System isolation use the same ETW session
- /// </summary>
- System,
- /// <summary>
- /// Use sparingly! When specifying Custom isolation, a separate ETW session is created for the channel.
- /// Using Custom isolation lets you control the access permissions for the channel and backing file.
- /// Because there are only 64 ETW sessions available, you should limit your use of Custom isolation.
- /// </summary>
- Custom,
- }
-#endif
-#endif
-
- /// <summary>
- /// Describes the pre-defined command (EventCommandEventArgs.Command property) that is passed to the OnEventCommand callback.
- /// </summary>
- public enum EventCommand
- {
- /// <summary>
- /// Update EventSource state
- /// </summary>
- Update = 0,
- /// <summary>
- /// Request EventSource to generate and send its manifest
- /// </summary>
- SendManifest = -1,
- /// <summary>
- /// Enable event
- /// </summary>
- Enable = -2,
- /// <summary>
- /// Disable event
- /// </summary>
- Disable = -3
- };
-
-
- #region private classes
-
-#if FEATURE_ACTIVITYSAMPLING
-
- /// <summary>
- /// ActivityFilter is a helper structure that is used to keep track of run-time state
- /// associated with activity filtering. It is 1-1 with EventListeners (logically
- /// every listener has one of these, however we actually allocate them lazily), as well
- /// as 1-to-1 with tracing-aware EtwSessions.
- ///
- /// This structure also keeps track of the sampling counts associated with 'trigger'
- /// events. Because these trigger events are rare, and you typically only have one of
- /// them, we store them here as a linked list.
- /// </summary>
- internal sealed class ActivityFilter : IDisposable
- {
- /// <summary>
- /// Disable all activity filtering for the listener associated with 'filterList',
- /// (in the session associated with it) that is triggered by any event in 'source'.
- /// </summary>
- public static void DisableFilter(ref ActivityFilter filterList, EventSource source)
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
-#endif
-
- if (filterList == null)
- return;
-
- ActivityFilter cur;
- // Remove it from anywhere in the list (except the first element, which has to
- // be treated specially)
- ActivityFilter prev = filterList;
- cur = prev.m_next;
- while (cur != null)
- {
- if (cur.m_providerGuid == source.Guid)
- {
- // update TriggersActivityTracking bit
- if (cur.m_eventId >= 0 && cur.m_eventId < source.m_eventData.Length)
- --source.m_eventData[cur.m_eventId].TriggersActivityTracking;
-
- // Remove it from the linked list.
- prev.m_next = cur.m_next;
- // dispose of the removed node
- cur.Dispose();
- // update cursor
- cur = prev.m_next;
- }
- else
- {
- // update cursors
- prev = cur;
- cur = prev.m_next;
- }
- }
-
- // Sadly we have to treat the first element specially in linked list removal in C#
- if (filterList.m_providerGuid == source.Guid)
- {
- // update TriggersActivityTracking bit
- if (filterList.m_eventId >= 0 && filterList.m_eventId < source.m_eventData.Length)
- --source.m_eventData[filterList.m_eventId].TriggersActivityTracking;
-
- // We are the first element in the list.
- var first = filterList;
- filterList = first.m_next;
- // dispose of the removed node
- first.Dispose();
- }
- // the above might have removed the one ActivityFilter in the session that contains the
- // cleanup delegate; re-create the delegate if needed
- if (filterList != null)
- {
- EnsureActivityCleanupDelegate(filterList);
- }
- }
-
- /// <summary>
- /// Currently this has "override" semantics. We first disable all filters
- /// associated with 'source', and next we add new filters for each entry in the
- /// string 'startEvents'. participateInSampling specifies whether non-startEvents
- /// always trigger or only trigger when current activity is 'active'.
- /// </summary>
- public static void UpdateFilter(
- ref ActivityFilter filterList,
- EventSource source,
- int perEventSourceSessionId,
- string startEvents)
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
-#endif
-
- // first remove all filters associated with 'source'
- DisableFilter(ref filterList, source);
-
- if (!string.IsNullOrEmpty(startEvents))
- {
- // ActivitySamplingStartEvents is a space-separated list of Event:Frequency pairs.
- // The Event may be specified by name or by ID. Errors in parsing such a pair
- // result in the error being reported to the listeners, and the pair being ignored.
- // E.g. "CustomActivityStart:1000 12:10" specifies that for event CustomActivityStart
- // we should initiate activity tracing once every 1000 events, *and* for event ID 12
- // we should initiate activity tracing once every 10 events.
- string[] activityFilterStrings = startEvents.Split(' ');
-
- for (int i = 0; i < activityFilterStrings.Length; ++i)
- {
- string activityFilterString = activityFilterStrings[i];
- int sampleFreq = 1;
- int eventId = -1;
- int colonIdx = activityFilterString.IndexOf(':');
- if (colonIdx < 0)
- {
- source.ReportOutOfBandMessage("ERROR: Invalid ActivitySamplingStartEvent specification: " +
- activityFilterString, false);
- // ignore failure...
- continue;
- }
- string sFreq = activityFilterString.Substring(colonIdx + 1);
- if (!int.TryParse(sFreq, out sampleFreq))
- {
- source.ReportOutOfBandMessage("ERROR: Invalid sampling frequency specification: " + sFreq, false);
- continue;
- }
- activityFilterString = activityFilterString.Substring(0, colonIdx);
- if (!int.TryParse(activityFilterString, out eventId))
- {
- // reset eventId
- eventId = -1;
- // see if it's an event name
- for (int j = 0; j < source.m_eventData.Length; j++)
- {
- EventSource.EventMetadata[] ed = source.m_eventData;
- if (ed[j].Name != null && ed[j].Name.Length == activityFilterString.Length &&
- string.Compare(ed[j].Name, activityFilterString, StringComparison.OrdinalIgnoreCase) == 0)
- {
- eventId = ed[j].Descriptor.EventId;
- break;
- }
- }
- }
- if (eventId < 0 || eventId >= source.m_eventData.Length)
- {
- source.ReportOutOfBandMessage("ERROR: Invalid eventId specification: " + activityFilterString, false);
- continue;
- }
- EnableFilter(ref filterList, source, perEventSourceSessionId, eventId, sampleFreq);
- }
- }
- }
-
- /// <summary>
- /// Returns the first ActivityFilter from 'filterList' corresponding to 'source'.
- /// </summary>
- public static ActivityFilter GetFilter(ActivityFilter filterList, EventSource source)
- {
- for (var af = filterList; af != null; af = af.m_next)
- {
- if (af.m_providerGuid == source.Guid && af.m_samplingFreq != -1)
- return af;
- }
- return null;
- }
-
- /// <summary>
- /// 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
- /// 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.
- ///
- /// If 'childActivityID' is present, it will be added to the active set if the
- /// current activity is active.
- /// </summary>
- unsafe public static bool PassesActivityFilter(
- ActivityFilter filterList,
- Guid* childActivityID,
- bool triggeringEvent,
- EventSource source,
- int eventId)
- {
- Debug.Assert(filterList != null && filterList.m_activeActivities != null);
- bool shouldBeLogged = false;
- if (triggeringEvent)
- {
- for (ActivityFilter af = filterList; af != null; af = af.m_next)
- {
- if (eventId == af.m_eventId && source.Guid == af.m_providerGuid)
- {
- // Update the sampling count with wrap-around
- int curSampleCount, newSampleCount;
- do
- {
- curSampleCount = af.m_curSampleCount;
- if (curSampleCount <= 1)
- newSampleCount = af.m_samplingFreq; // Wrap around, counting down to 1
- else
- newSampleCount = curSampleCount - 1;
- }
- while (Interlocked.CompareExchange(ref af.m_curSampleCount, newSampleCount, curSampleCount) != curSampleCount);
- // If we hit zero, then start tracking the activity.
- if (curSampleCount <= 1)
- {
- Guid currentActivityId = EventSource.InternalCurrentThreadActivityId;
- Tuple<Guid, int> startId;
- // only add current activity if it's not already a root activity
- if (!af.m_rootActiveActivities.TryGetValue(currentActivityId, out startId))
- {
- // EventSource.OutputDebugString(string.Format(" PassesAF - Triggering(session {0}, evt {1})", af.m_perEventSourceSessionId, eventId));
- shouldBeLogged = true;
- af.m_activeActivities[currentActivityId] = Environment.TickCount;
- af.m_rootActiveActivities[currentActivityId] = Tuple.Create(source.Guid, eventId);
- }
- }
- else
- {
- // a start event following a triggering start event
- Guid currentActivityId = EventSource.InternalCurrentThreadActivityId;
- Tuple<Guid, int> startId;
- // only remove current activity if we added it
- if (af.m_rootActiveActivities.TryGetValue(currentActivityId, out startId) &&
- startId.Item1 == source.Guid && startId.Item2 == eventId)
- {
- // EventSource.OutputDebugString(string.Format("Activity dying: {0} -> StartEvent({1})", currentActivityId, eventId));
- // remove activity only from current logging scope (af)
- int dummy;
- af.m_activeActivities.TryRemove(currentActivityId, out dummy);
- }
- }
- break;
- }
- }
- }
-
- var activeActivities = GetActiveActivities(filterList);
- if (activeActivities != null)
- {
- // if we hadn't already determined this should be logged, test further
- if (!shouldBeLogged)
- {
- shouldBeLogged = !activeActivities.IsEmpty &&
- activeActivities.ContainsKey(EventSource.InternalCurrentThreadActivityId);
- }
- if (shouldBeLogged && childActivityID != null &&
- ((EventOpcode)source.m_eventData[eventId].Descriptor.Opcode == EventOpcode.Send))
- {
- FlowActivityIfNeeded(filterList, null, childActivityID);
- // EventSource.OutputDebugString(string.Format(" PassesAF - activity {0}", *childActivityID));
- }
- }
- // EventSource.OutputDebugString(string.Format(" PassesAF - shouldBeLogged(evt {0}) = {1:x}", eventId, shouldBeLogged));
- return shouldBeLogged;
- }
-
- public static bool IsCurrentActivityActive(ActivityFilter filterList)
- {
- var activeActivities = GetActiveActivities(filterList);
- if (activeActivities != null &&
- activeActivities.ContainsKey(EventSource.InternalCurrentThreadActivityId))
- return true;
-
- return false;
- }
-
- /// <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
- /// that the current activity is active.
- /// </summary>
- unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID)
- {
- Debug.Assert(childActivityID != null);
-
- var activeActivities = GetActiveActivities(filterList);
- Debug.Assert(activeActivities != null);
-
- // take currentActivityId == null to mean we *know* the current activity is "active"
- if (currentActivityId != null && !activeActivities.ContainsKey(*currentActivityId))
- return;
-
- if (activeActivities.Count > MaxActivityTrackCount)
- {
- TrimActiveActivityStore(activeActivities);
- // make sure current activity is still in the set:
- activeActivities[EventSource.InternalCurrentThreadActivityId] = Environment.TickCount;
- }
- // add child activity to list of actives
- activeActivities[*childActivityID] = Environment.TickCount;
-
- }
-
- /// <summary>
- /// </summary>
- public static void UpdateKwdTriggers(ActivityFilter activityFilter, Guid sourceGuid, EventSource source, EventKeywords sessKeywords)
- {
- for (var af = activityFilter; af != null; af = af.m_next)
- {
- if ((sourceGuid == af.m_providerGuid) &&
- (source.m_eventData[af.m_eventId].TriggersActivityTracking > 0 ||
- ((EventOpcode)source.m_eventData[af.m_eventId].Descriptor.Opcode == EventOpcode.Send)))
- {
- // we could be more precise here, if we tracked 'anykeywords' per session
- unchecked
- {
- source.m_keywordTriggers |= (source.m_eventData[af.m_eventId].Descriptor.Keywords & (long)sessKeywords);
- }
- }
- }
- }
-
- /// <summary>
- /// For the EventSource specified by 'sourceGuid' and the EventListener/EtwSession
- /// associated with 'this' ActivityFilter list, return configured sequence of
- /// [eventId, sampleFreq] pairs that defines the sampling policy.
- /// </summary>
- public IEnumerable<Tuple<int, int>> GetFilterAsTuple(Guid sourceGuid)
- {
- for (ActivityFilter af = this; af != null; af = af.m_next)
- {
- if (af.m_providerGuid == sourceGuid)
- yield return Tuple.Create(af.m_eventId, af.m_samplingFreq);
- }
- }
-
- /// <summary>
- /// The cleanup being performed consists of removing the m_myActivityDelegate from
- /// the static s_activityDying, therefore allowing the ActivityFilter to be reclaimed.
- /// </summary>
- public void Dispose()
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
-#endif
- // m_myActivityDelegate is still alive (held by the static EventSource.s_activityDying).
- // Therefore we are ok to take a dependency on m_myActivityDelegate being valid even
- // during the finalization of the ActivityFilter
- if (m_myActivityDelegate != null)
- {
- EventSource.s_activityDying = (Action<Guid>)Delegate.Remove(EventSource.s_activityDying, m_myActivityDelegate);
- m_myActivityDelegate = null;
- }
- }
-
- #region private
-
- /// <summary>
- /// Creates a new ActivityFilter that is triggered by 'eventId' from 'source' ever
- /// 'samplingFreq' times the event fires. You can have several of these forming a
- /// linked list.
- /// </summary>
- private ActivityFilter(EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq, ActivityFilter existingFilter = null)
- {
- m_providerGuid = source.Guid;
- m_perEventSourceSessionId = perEventSourceSessionId;
- m_eventId = eventId;
- m_samplingFreq = samplingFreq;
- m_next = existingFilter;
-
- Debug.Assert(existingFilter == null ||
- (existingFilter.m_activeActivities == null) == (existingFilter.m_rootActiveActivities == null));
-
- // if this is the first filter we add for this session, we need to create a new
- // table of activities. m_activeActivities is common across EventSources in the same
- // session
- ConcurrentDictionary<Guid, int> activeActivities = null;
- if (existingFilter == null ||
- (activeActivities = GetActiveActivities(existingFilter)) == null)
- {
- m_activeActivities = new ConcurrentDictionary<Guid, int>();
- m_rootActiveActivities = new ConcurrentDictionary<Guid, Tuple<Guid, int>>();
-
- // Add a delegate to the 'SetCurrentThreadToActivity callback so that I remove 'dead' activities
- m_myActivityDelegate = GetActivityDyingDelegate(this);
- EventSource.s_activityDying = (Action<Guid>)Delegate.Combine(EventSource.s_activityDying, m_myActivityDelegate);
- }
- else
- {
- m_activeActivities = activeActivities;
- m_rootActiveActivities = existingFilter.m_rootActiveActivities;
- }
-
- }
-
- /// <summary>
- /// Ensure there's at least one ActivityFilter in the 'filterList' that contains an
- /// activity-removing delegate for the listener/session associated with 'filterList'.
- /// </summary>
- private static void EnsureActivityCleanupDelegate(ActivityFilter filterList)
- {
- if (filterList == null)
- return;
-
- for (ActivityFilter af = filterList; af != null; af = af.m_next)
- {
- if (af.m_myActivityDelegate != null)
- return;
- }
-
- // we didn't find a delegate
- filterList.m_myActivityDelegate = GetActivityDyingDelegate(filterList);
- EventSource.s_activityDying = (Action<Guid>)Delegate.Combine(EventSource.s_activityDying, filterList.m_myActivityDelegate);
- }
-
- /// <summary>
- /// Builds the delegate to be called when an activity is dying. This is responsible
- /// for performing whatever cleanup is needed for the ActivityFilter list passed in.
- /// This gets "added" to EventSource.s_activityDying and ends up being called from
- /// EventSource.SetCurrentThreadActivityId and ActivityFilter.PassesActivityFilter.
- /// </summary>
- /// <returns>The delegate to be called when an activity is dying</returns>
- private static Action<Guid> GetActivityDyingDelegate(ActivityFilter filterList)
- {
- return (Guid oldActivity) =>
- {
- int dummy;
- filterList.m_activeActivities.TryRemove(oldActivity, out dummy);
- Tuple<Guid, int> dummyTuple;
- filterList.m_rootActiveActivities.TryRemove(oldActivity, out dummyTuple);
- };
- }
-
- /// <summary>
- /// Enables activity filtering for the listener associated with 'filterList', triggering on
- /// the event 'eventID' from 'source' with a sampling frequency of 'samplingFreq'
- ///
- /// if 'eventID' is out of range (e.g. negative), it means we are not triggering (but we are
- /// activitySampling if something else triggered).
- /// </summary>
- /// <returns>true if activity sampling is enabled the samplingFreq is non-zero </returns>
- private static bool EnableFilter(ref ActivityFilter filterList, EventSource source, int perEventSourceSessionId, int eventId, int samplingFreq)
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(Monitor.IsEntered(EventListener.EventListenersLock));
-#endif
- Debug.Assert(samplingFreq > 0);
- Debug.Assert(eventId >= 0);
-
- filterList = new ActivityFilter(source, perEventSourceSessionId, eventId, samplingFreq, filterList);
-
- // Mark the 'quick Check' that indicates this is a trigger event.
- // If eventId is out of range then this mark is not done which has the effect of ignoring
- // the trigger.
- if (0 <= eventId && eventId < source.m_eventData.Length)
- ++source.m_eventData[eventId].TriggersActivityTracking;
-
- return true;
- }
-
- /// <summary>
- /// Normally this code never runs, it is here just to prevent run-away resource usage.
- /// </summary>
- private static void TrimActiveActivityStore(ConcurrentDictionary<Guid, int> activities)
- {
- if (activities.Count > MaxActivityTrackCount)
- {
- // Remove half of the oldest activity ids.
- var keyValues = activities.ToArray();
- var tickNow = Environment.TickCount;
-
- // Sort by age, taking into account wrap-around. As long as x and y are within
- // 23 days of now then (0x7FFFFFFF & (tickNow - x.Value)) is the delta (even if
- // TickCount wraps). I then sort by DESCENDING age. (that is oldest value first)
- Array.Sort(keyValues, (x, y) => (0x7FFFFFFF & (tickNow - y.Value)) - (0x7FFFFFFF & (tickNow - x.Value)));
- for (int i = 0; i < keyValues.Length / 2; i++)
- {
- int dummy;
- activities.TryRemove(keyValues[i].Key, out dummy);
- }
- }
- }
-
- private static ConcurrentDictionary<Guid, int> GetActiveActivities(
- ActivityFilter filterList)
- {
- for (ActivityFilter af = filterList; af != null; af = af.m_next)
- {
- if (af.m_activeActivities != null)
- return af.m_activeActivities;
- }
- return null;
- }
-
- // m_activeActivities always points to the sample dictionary for EVERY ActivityFilter
- // in the m_next list. The 'int' value in the m_activities set is a timestamp
- // (Environment.TickCount) of when the entry was put in the system and is used to
- // remove 'old' entries that if the set gets too big.
- ConcurrentDictionary<Guid, int> m_activeActivities;
-
- // m_rootActiveActivities holds the "root" active activities, i.e. the activities
- // that were marked as active because a Start event fired on them. We need to keep
- // track of these to enable sampling in the scenario of an app's main thread that
- // never explicitly sets distinct activity IDs as it executes. To handle these
- // situations we manufacture a Guid from the thread's ID, and:
- // (a) we consider the firing of a start event when the sampling counter reaches
- // zero to mark the beginning of an interesting activity, and
- // (b) we consider the very next firing of the same start event to mark the
- // ending of that activity.
- // We use a ConcurrentDictionary to avoid taking explicit locks.
- // The key (a guid) represents the activity ID of the root active activity
- // The value is made up of the Guid of the event provider and the eventId of
- // the start event.
- ConcurrentDictionary<Guid, Tuple<Guid, int>> m_rootActiveActivities;
- Guid m_providerGuid; // We use the GUID rather than object identity because we don't want to keep the eventSource alive
- int m_eventId; // triggering event
- int m_samplingFreq; // Counter reset to this when it hits 0
- int m_curSampleCount; // We count down to 0 and then activate the activity.
- int m_perEventSourceSessionId; // session ID bit for ETW, 0 for EventListeners
-
- const int MaxActivityTrackCount = 100000; // maximum number of tracked activities
-
- ActivityFilter m_next; // We create a linked list of these
- Action<Guid> m_myActivityDelegate;
- #endregion
- };
-
-
- /// <summary>
- /// An EtwSession instance represents an activity-tracing-aware ETW session. Since these
- /// are limited to 8 concurrent sessions per machine (currently) we're going to store
- /// the active ones in a singly linked list.
- /// </summary>
- internal class EtwSession
- {
- public static EtwSession GetEtwSession(int etwSessionId, bool bCreateIfNeeded = false)
- {
- if (etwSessionId < 0)
- return null;
-
- EtwSession etwSession;
- foreach (var wrEtwSession in s_etwSessions)
- {
-#if ES_BUILD_STANDALONE
- if ((etwSession = (EtwSession) wrEtwSession.Target) != null && etwSession.m_etwSessionId == etwSessionId)
- return etwSession;
-#else
- if (wrEtwSession.TryGetTarget(out etwSession) && etwSession.m_etwSessionId == etwSessionId)
- return etwSession;
-#endif
- }
-
- if (!bCreateIfNeeded)
- return null;
-
-#if ES_BUILD_STANDALONE
- if (s_etwSessions == null)
- s_etwSessions = new List<WeakReference>();
-
- etwSession = new EtwSession(etwSessionId);
- s_etwSessions.Add(new WeakReference(etwSession));
-#else
- if (s_etwSessions == null)
- s_etwSessions = new List<WeakReference<EtwSession>>();
-
- etwSession = new EtwSession(etwSessionId);
- s_etwSessions.Add(new WeakReference<EtwSession>(etwSession));
-#endif
-
- if (s_etwSessions.Count > s_thrSessionCount)
- TrimGlobalList();
-
- return etwSession;
-
- }
-
- public static void RemoveEtwSession(EtwSession etwSession)
- {
- Debug.Assert(etwSession != null);
- if (s_etwSessions == null || etwSession == null)
- return;
-
- s_etwSessions.RemoveAll((wrEtwSession) =>
- {
- EtwSession session;
-#if ES_BUILD_STANDALONE
- return (session = (EtwSession) wrEtwSession.Target) != null &&
- (session.m_etwSessionId == etwSession.m_etwSessionId);
-#else
- return wrEtwSession.TryGetTarget(out session) &&
- (session.m_etwSessionId == etwSession.m_etwSessionId);
-#endif
- });
-
- if (s_etwSessions.Count > s_thrSessionCount)
- TrimGlobalList();
- }
-
- private static void TrimGlobalList()
- {
- if (s_etwSessions == null)
- return;
-
- s_etwSessions.RemoveAll((wrEtwSession) =>
- {
-#if ES_BUILD_STANDALONE
- return wrEtwSession.Target == null;
-#else
- EtwSession session;
- return !wrEtwSession.TryGetTarget(out session);
-#endif
- });
- }
-
- private EtwSession(int etwSessionId)
- {
- m_etwSessionId = etwSessionId;
- }
-
- public readonly int m_etwSessionId; // ETW session ID (as retrieved by EventProvider)
- public ActivityFilter m_activityFilter; // all filters enabled for this session
-
-#if ES_BUILD_STANDALONE
- private static List<WeakReference> s_etwSessions = new List<WeakReference>();
-#else
- private static List<WeakReference<EtwSession>> s_etwSessions = new List<WeakReference<EtwSession>>();
-#endif
- private const int s_thrSessionCount = 16;
- }
-
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // holds a bitfield representing a session mask
- /// <summary>
- /// A SessionMask represents a set of (at most MAX) sessions as a bit mask. The perEventSourceSessionId
- /// is the index in the SessionMask of the bit that will be set. These can translate to
- /// EventSource's reserved keywords bits using the provided ToEventKeywords() and
- /// FromEventKeywords() methods.
- /// </summary>
- internal struct SessionMask
- {
- public SessionMask(SessionMask m)
- { m_mask = m.m_mask; }
-
- public SessionMask(uint mask = 0)
- { m_mask = mask & MASK; }
-
- public bool IsEqualOrSupersetOf(SessionMask m)
- {
- return (this.m_mask | m.m_mask) == this.m_mask;
- }
-
- public static SessionMask All
- {
- get { return new SessionMask(MASK); }
- }
-
- public static SessionMask FromId(int perEventSourceSessionId)
- {
- Debug.Assert(perEventSourceSessionId < MAX);
- return new SessionMask((uint)1 << perEventSourceSessionId);
- }
-
- public ulong ToEventKeywords()
- {
- return (ulong)m_mask << SHIFT_SESSION_TO_KEYWORD;
- }
-
- public static SessionMask FromEventKeywords(ulong m)
- {
- return new SessionMask((uint)(m >> SHIFT_SESSION_TO_KEYWORD));
- }
-
- public bool this[int perEventSourceSessionId]
- {
- get
- {
- Debug.Assert(perEventSourceSessionId < MAX);
- return (m_mask & (1 << perEventSourceSessionId)) != 0;
- }
- set
- {
- Debug.Assert(perEventSourceSessionId < MAX);
- if (value) m_mask |= ((uint)1 << perEventSourceSessionId);
- else m_mask &= ~((uint)1 << perEventSourceSessionId);
- }
- }
-
- public static SessionMask operator |(SessionMask m1, SessionMask m2)
- {
- return new SessionMask(m1.m_mask | m2.m_mask);
- }
-
- public static SessionMask operator &(SessionMask m1, SessionMask m2)
- {
- return new SessionMask(m1.m_mask & m2.m_mask);
- }
-
- public static SessionMask operator ^(SessionMask m1, SessionMask m2)
- {
- return new SessionMask(m1.m_mask ^ m2.m_mask);
- }
-
- public static SessionMask operator ~(SessionMask m)
- {
- return new SessionMask(MASK & ~(m.m_mask));
- }
-
- public static explicit operator ulong(SessionMask m)
- { return m.m_mask; }
-
- public static explicit operator uint(SessionMask m)
- { return m.m_mask; }
-
- private uint m_mask;
-
- internal const int SHIFT_SESSION_TO_KEYWORD = 44; // bits 44-47 inclusive are reserved
- internal const uint MASK = 0x0fU; // the mask of 4 reserved bits
- internal const uint MAX = 4; // maximum number of simultaneous ETW sessions supported
- }
-
- /// <summary>
- /// code:EventDispatchers are a simple 'helper' structure that holds the filtering state
- /// (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
- /// 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
- /// associated with.
- /// </summary>
- internal class EventDispatcher
- {
- internal EventDispatcher(EventDispatcher next, bool[] eventEnabled, EventListener listener)
- {
- m_Next = next;
- m_EventEnabled = eventEnabled;
- m_Listener = listener;
- }
-
- // Instance fields
- readonly internal EventListener m_Listener; // The dispatcher this entry is for
- internal bool[] m_EventEnabled; // For every event in a the eventSource, is it enabled?
-#if FEATURE_ACTIVITYSAMPLING
- internal bool m_activityFilteringEnabled; // does THIS EventSource have activity filtering turned on for this listener?
-#endif // FEATURE_ACTIVITYSAMPLING
-
- // Only guaranteed to exist after a InsureInit()
- internal EventDispatcher m_Next; // These form a linked list in code:EventSource.m_Dispatchers
- // Of all listeners for that eventSource.
- }
-
- /// <summary>
- /// Flags that can be used with EventSource.GenerateManifest to control how the ETW manifest for the EventSource is
- /// generated.
- /// </summary>
- [Flags]
- public enum EventManifestOptions
- {
- /// <summary>
- /// Only the resources associated with current UI culture are included in the manifest
- /// </summary>
- None = 0x0,
- /// <summary>
- /// Throw exceptions for any inconsistency encountered
- /// </summary>
- Strict = 0x1,
- /// <summary>
- /// Generate a "resources" node under "localization" for every satellite assembly provided
- /// </summary>
- AllCultures = 0x2,
- /// <summary>
- /// Generate the manifest only if the event source needs to be registered on the machine,
- /// otherwise return null (but still perform validation if Strict is specified)
- /// </summary>
- OnlyIfNeededForRegistration = 0x4,
- /// <summary>
- /// When generating the manifest do *not* enforce the rule that the current EventSource class
- /// must be the base class for the user-defined type passed in. This allows validation of .net
- /// event sources using the new validation code
- /// </summary>
- AllowEventSourceOverride = 0x8,
- }
-
- /// <summary>
- /// ManifestBuilder is designed to isolate the details of the message of the event from the
- /// rest of EventSource. This one happens to create XML.
- /// </summary>
- internal partial class ManifestBuilder
- {
- /// <summary>
- /// Build a manifest for 'providerName' with the given GUID, which will be packaged into 'dllName'.
- /// 'resources, is a resource manager. If specified all messages are localized using that manager.
- /// </summary>
- public ManifestBuilder(string providerName, Guid providerGuid, string dllName, ResourceManager resources,
- EventManifestOptions flags)
- {
-#if FEATURE_MANAGED_ETW_CHANNELS
- this.providerName = providerName;
-#endif
- this.flags = flags;
-
- this.resources = resources;
- sb = new StringBuilder();
- events = new StringBuilder();
- templates = new StringBuilder();
- opcodeTab = new Dictionary<int, string>();
- stringTab = new Dictionary<string, string>();
- errors = new List<string>();
- perEventByteArrayArgIndices = new Dictionary<string, List<int>>();
-
- sb.AppendLine("<instrumentationManifest xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">");
- sb.AppendLine(" <instrumentation xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:win=\"http://manifests.microsoft.com/win/2004/08/windows/events\">");
- sb.AppendLine(" <events xmlns=\"http://schemas.microsoft.com/win/2004/08/events\">");
- sb.Append("<provider name=\"").Append(providerName).
- Append("\" guid=\"{").Append(providerGuid.ToString()).Append("}");
- if (dllName != null)
- sb.Append("\" resourceFileName=\"").Append(dllName).Append("\" messageFileName=\"").Append(dllName);
-
- var symbolsName = providerName.Replace("-", "").Replace(".", "_"); // Period and - are illegal replace them.
- sb.Append("\" symbol=\"").Append(symbolsName);
- sb.Append("\">").AppendLine();
- }
-
- public void AddOpcode(string name, int value)
- {
- if ((flags & EventManifestOptions.Strict) != 0)
- {
- if (value <= 10 || value >= 239)
- {
- ManifestError(Resources.GetResourceString("EventSource_IllegalOpcodeValue", name, value));
- }
- string prevName;
- if (opcodeTab.TryGetValue(value, out prevName) && !name.Equals(prevName, StringComparison.Ordinal))
- {
- ManifestError(Resources.GetResourceString("EventSource_OpcodeCollision", name, prevName, value));
- }
- }
- opcodeTab[value] = name;
- }
- public void AddTask(string name, int value)
- {
- if ((flags & EventManifestOptions.Strict) != 0)
- {
- if (value <= 0 || value >= 65535)
- {
- ManifestError(Resources.GetResourceString("EventSource_IllegalTaskValue", name, value));
- }
- string prevName;
- if (taskTab != null && taskTab.TryGetValue(value, out prevName) && !name.Equals(prevName, StringComparison.Ordinal))
- {
- ManifestError(Resources.GetResourceString("EventSource_TaskCollision", name, prevName, value));
- }
- }
- if (taskTab == null)
- taskTab = new Dictionary<int, string>();
- taskTab[value] = name;
- }
- public void AddKeyword(string name, ulong value)
- {
- if ((value & (value - 1)) != 0) // Is it a power of 2?
- {
- ManifestError(Resources.GetResourceString("EventSource_KeywordNeedPowerOfTwo", "0x" + value.ToString("x", CultureInfo.CurrentCulture), name), true);
- }
- if ((flags & EventManifestOptions.Strict) != 0)
- {
- if (value >= 0x0000100000000000UL && !name.StartsWith("Session", StringComparison.Ordinal))
- {
- ManifestError(Resources.GetResourceString("EventSource_IllegalKeywordsValue", name, "0x" + value.ToString("x", CultureInfo.CurrentCulture)));
- }
- string prevName;
- if (keywordTab != null && keywordTab.TryGetValue(value, out prevName) && !name.Equals(prevName, StringComparison.Ordinal))
- {
- ManifestError(Resources.GetResourceString("EventSource_KeywordCollision", name, prevName, "0x" + value.ToString("x", CultureInfo.CurrentCulture)));
- }
- }
- if (keywordTab == null)
- keywordTab = new Dictionary<ulong, string>();
- keywordTab[value] = name;
- }
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- /// <summary>
- /// Add a channel. channelAttribute can be null
- /// </summary>
- public void AddChannel(string name, int value, EventChannelAttribute channelAttribute)
- {
- EventChannel chValue = (EventChannel)value;
- if (value < (int)EventChannel.Admin || value > 255)
- ManifestError(Resources.GetResourceString("EventSource_EventChannelOutOfRange", name, value));
- else if (chValue >= EventChannel.Admin && chValue <= EventChannel.Debug &&
- channelAttribute != null && EventChannelToChannelType(chValue) != channelAttribute.EventChannelType)
- {
- // we want to ensure developers do not define EventChannels that conflict with the builtin ones,
- // but we want to allow them to override the default ones...
- ManifestError(Resources.GetResourceString("EventSource_ChannelTypeDoesNotMatchEventChannelValue",
- name, ((EventChannel)value).ToString()));
- }
-
- // TODO: validate there are no conflicting manifest exposed names (generally following the format "provider/type")
-
- ulong kwd = GetChannelKeyword(chValue);
-
- if (channelTab == null)
- channelTab = new Dictionary<int, ChannelInfo>(4);
- channelTab[value] = new ChannelInfo { Name = name, Keywords = kwd, Attribs = channelAttribute };
- }
-
- private EventChannelType EventChannelToChannelType(EventChannel channel)
- {
-#if !ES_BUILD_STANDALONE
- Debug.Assert(channel >= EventChannel.Admin && channel <= EventChannel.Debug);
-#endif
- return (EventChannelType)((int)channel - (int)EventChannel.Admin + (int)EventChannelType.Admin);
- }
- private EventChannelAttribute GetDefaultChannelAttribute(EventChannel channel)
- {
- EventChannelAttribute attrib = new EventChannelAttribute();
- attrib.EventChannelType = EventChannelToChannelType(channel);
- if (attrib.EventChannelType <= EventChannelType.Operational)
- attrib.Enabled = true;
- return attrib;
- }
-
- public ulong[] GetChannelData()
- {
- if (this.channelTab == null)
- {
- return new ulong[0];
- }
-
- // We create an array indexed by the channel id for fast look up.
- // E.g. channelMask[Admin] will give you the bit mask for Admin channel.
- int maxkey = -1;
- foreach (var item in this.channelTab.Keys)
- {
- if (item > maxkey)
- {
- maxkey = item;
- }
- }
-
- ulong[] channelMask = new ulong[maxkey + 1];
- foreach (var item in this.channelTab)
- {
- channelMask[item.Key] = item.Value.Keywords;
- }
-
- return channelMask;
- }
-
-#endif
- public void StartEvent(string eventName, EventAttribute eventAttribute)
- {
- Debug.Assert(numParams == 0);
- Debug.Assert(this.eventName == null);
- this.eventName = eventName;
- numParams = 0;
- byteArrArgIndices = null;
-
- events.Append(" <event").
- Append(" value=\"").Append(eventAttribute.EventId).Append("\"").
- Append(" version=\"").Append(eventAttribute.Version).Append("\"").
- Append(" level=\"").Append(GetLevelName(eventAttribute.Level)).Append("\"").
- Append(" symbol=\"").Append(eventName).Append("\"");
-
- // at this point we add to the manifest's stringTab a message that is as-of-yet
- // "untranslated to manifest convention", b/c we don't have the number or position
- // of any byte[] args (which require string format index updates)
- WriteMessageAttrib(events, "event", eventName, eventAttribute.Message);
-
- if (eventAttribute.Keywords != 0)
- events.Append(" keywords=\"").Append(GetKeywords((ulong)eventAttribute.Keywords, eventName)).Append("\"");
- if (eventAttribute.Opcode != 0)
- events.Append(" opcode=\"").Append(GetOpcodeName(eventAttribute.Opcode, eventName)).Append("\"");
- if (eventAttribute.Task != 0)
- events.Append(" task=\"").Append(GetTaskName(eventAttribute.Task, eventName)).Append("\"");
-#if FEATURE_MANAGED_ETW_CHANNELS
- if (eventAttribute.Channel != 0)
- {
- events.Append(" channel=\"").Append(GetChannelName(eventAttribute.Channel, eventName, eventAttribute.Message)).Append("\"");
- }
-#endif
- }
-
- public void AddEventParameter(Type type, string name)
- {
- if (numParams == 0)
- templates.Append(" <template tid=\"").Append(eventName).Append("Args\">").AppendLine();
- if (type == typeof(byte[]))
- {
- // mark this index as "extraneous" (it has no parallel in the managed signature)
- // we use these values in TranslateToManifestConvention()
- if (byteArrArgIndices == null)
- byteArrArgIndices = new List<int>(4);
- byteArrArgIndices.Add(numParams);
-
- // add an extra field to the template representing the length of the binary blob
- numParams++;
- templates.Append(" <data name=\"").Append(name).Append("Size\" inType=\"win:UInt32\"/>").AppendLine();
- }
- numParams++;
- templates.Append(" <data name=\"").Append(name).Append("\" inType=\"").Append(GetTypeName(type)).Append("\"");
- // TODO: for 'byte*' types it assumes the user provided length is named using the same naming convention
- // as for 'byte[]' args (blob_arg_name + "Size")
- if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte))
- {
- // add "length" attribute to the "blob" field in the template (referencing the field added above)
- templates.Append(" length=\"").Append(name).Append("Size\"");
- }
- // ETW does not support 64-bit value maps, so we don't specify these as ETW maps
- if (type.IsEnum() && Enum.GetUnderlyingType(type) != typeof(UInt64) && Enum.GetUnderlyingType(type) != typeof(Int64))
- {
- templates.Append(" map=\"").Append(type.Name).Append("\"");
- if (mapsTab == null)
- mapsTab = new Dictionary<string, Type>();
- if (!mapsTab.ContainsKey(type.Name))
- mapsTab.Add(type.Name, type); // Remember that we need to dump the type enumeration
- }
-
- templates.Append("/>").AppendLine();
- }
- public void EndEvent()
- {
- if (numParams > 0)
- {
- templates.Append(" </template>").AppendLine();
- events.Append(" template=\"").Append(eventName).Append("Args\"");
- }
- events.Append("/>").AppendLine();
-
- if (byteArrArgIndices != null)
- perEventByteArrayArgIndices[eventName] = byteArrArgIndices;
-
- // at this point we have all the information we need to translate the C# Message
- // to the manifest string we'll put in the stringTab
- string msg;
- if (stringTab.TryGetValue("event_" + eventName, out msg))
- {
- msg = TranslateToManifestConvention(msg, eventName);
- stringTab["event_" + eventName] = msg;
- }
-
- eventName = null;
- numParams = 0;
- byteArrArgIndices = null;
- }
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- // Channel keywords are generated one per channel to allow channel based filtering in event viewer. These keywords are autogenerated
- // by mc.exe for compiling a manifest and are based on the order of the channels (fields) in the Channels inner class (when advanced
- // channel support is enabled), or based on the order the predefined channels appear in the EventAttribute properties (for simple
- // support). The manifest generated *MUST* have the channels specified in the same order (that's how our computed keywords are mapped
- // to channels by the OS infrastructure).
- // If channelKeyworkds is present, and has keywords bits in the ValidPredefinedChannelKeywords then it is
- // assumed that that the keyword for that channel should be that bit.
- // otherwise we allocate a channel bit for the channel.
- // explicit channel bits are only used by WCF to mimic an existing manifest,
- // so we don't dont do error checking.
- public ulong GetChannelKeyword(EventChannel channel, ulong channelKeyword = 0)
- {
- // strip off any non-channel keywords, since we are only interested in channels here.
- channelKeyword &= ValidPredefinedChannelKeywords;
- if (channelTab == null)
- {
- channelTab = new Dictionary<int, ChannelInfo>(4);
- }
-
- if (channelTab.Count == MaxCountChannels)
- ManifestError(Resources.GetResourceString("EventSource_MaxChannelExceeded"));
-
- ChannelInfo info;
- if (!channelTab.TryGetValue((int)channel, out info))
- {
- // If we were not given an explicit channel, allocate one.
- if (channelKeyword != 0)
- {
- channelKeyword = nextChannelKeywordBit;
- nextChannelKeywordBit >>= 1;
- }
- }
- else
- {
- channelKeyword = info.Keywords;
- }
-
- return channelKeyword;
- }
-#endif
-
- public byte[] CreateManifest()
- {
- string str = CreateManifestString();
- return Encoding.UTF8.GetBytes(str);
- }
-
- public IList<string> Errors { get { return errors; } }
-
- /// <summary>
- /// When validating an event source it adds the error to the error collection.
- /// When not validating it throws an exception if runtimeCritical is "true".
- /// Otherwise the error is ignored.
- /// </summary>
- /// <param name="msg"></param>
- /// <param name="runtimeCritical"></param>
- public void ManifestError(string msg, bool runtimeCritical = false)
- {
- if ((flags & EventManifestOptions.Strict) != 0)
- errors.Add(msg);
- else if (runtimeCritical)
- throw new ArgumentException(msg);
- }
-
- private string CreateManifestString()
- {
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- // Write out the channels
- if (channelTab != null)
- {
- sb.Append(" <channels>").AppendLine();
- var sortedChannels = new List<KeyValuePair<int, ChannelInfo>>();
- foreach (KeyValuePair<int, ChannelInfo> p in channelTab) { sortedChannels.Add(p); }
- sortedChannels.Sort((p1, p2) => -Comparer<ulong>.Default.Compare(p1.Value.Keywords, p2.Value.Keywords));
- foreach (var kvpair in sortedChannels)
- {
- int channel = kvpair.Key;
- ChannelInfo channelInfo = kvpair.Value;
-
- string channelType = null;
- string elementName = "channel";
- bool enabled = false;
- string fullName = null;
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- string isolation = null;
- string access = null;
-#endif
- if (channelInfo.Attribs != null)
- {
- var attribs = channelInfo.Attribs;
- if (Enum.IsDefined(typeof(EventChannelType), attribs.EventChannelType))
- channelType = attribs.EventChannelType.ToString();
- enabled = attribs.Enabled;
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- if (attribs.ImportChannel != null)
- {
- fullName = attribs.ImportChannel;
- elementName = "importChannel";
- }
- if (Enum.IsDefined(typeof(EventChannelIsolation), attribs.Isolation))
- isolation = attribs.Isolation.ToString();
- access = attribs.Access;
-#endif
- }
- if (fullName == null)
- fullName = providerName + "/" + channelInfo.Name;
-
- sb.Append(" <").Append(elementName);
- sb.Append(" chid=\"").Append(channelInfo.Name).Append("\"");
- sb.Append(" name=\"").Append(fullName).Append("\"");
- if (elementName == "channel") // not applicable to importChannels.
- {
- WriteMessageAttrib(sb, "channel", channelInfo.Name, null);
- sb.Append(" value=\"").Append(channel).Append("\"");
- if (channelType != null)
- sb.Append(" type=\"").Append(channelType).Append("\"");
- sb.Append(" enabled=\"").Append(enabled.ToString().ToLower()).Append("\"");
-#if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
- if (access != null)
- sb.Append(" access=\"").Append(access).Append("\"");
- if (isolation != null)
- sb.Append(" isolation=\"").Append(isolation).Append("\"");
-#endif
- }
- sb.Append("/>").AppendLine();
- }
- sb.Append(" </channels>").AppendLine();
- }
-#endif
-
- // Write out the tasks
- if (taskTab != null)
- {
-
- sb.Append(" <tasks>").AppendLine();
- var sortedTasks = new List<int>(taskTab.Keys);
- sortedTasks.Sort();
- foreach (int task in sortedTasks)
- {
- sb.Append(" <task");
- WriteNameAndMessageAttribs(sb, "task", taskTab[task]);
- sb.Append(" value=\"").Append(task).Append("\"/>").AppendLine();
- }
- sb.Append(" </tasks>").AppendLine();
- }
-
- // Write out the maps
- if (mapsTab != null)
- {
- sb.Append(" <maps>").AppendLine();
- foreach (Type enumType in mapsTab.Values)
- {
- bool isbitmap = EventSource.GetCustomAttributeHelper(enumType, typeof(FlagsAttribute), flags) != null;
- string mapKind = isbitmap ? "bitMap" : "valueMap";
- sb.Append(" <").Append(mapKind).Append(" name=\"").Append(enumType.Name).Append("\">").AppendLine();
-
- // write out each enum value
- FieldInfo[] staticFields = enumType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static);
- foreach (FieldInfo staticField in staticFields)
- {
- object constantValObj = staticField.GetRawConstantValue();
- if (constantValObj != null)
- {
- long hexValue;
- if (constantValObj is int)
- hexValue = ((int)constantValObj);
- else if (constantValObj is long)
- hexValue = ((long)constantValObj);
- else
- continue;
-
- // ETW requires all bitmap values to be powers of 2. Skip the ones that are not.
- // TODO: Warn people about the dropping of values.
- if (isbitmap && ((hexValue & (hexValue - 1)) != 0 || hexValue == 0))
- continue;
-
- sb.Append(" <map value=\"0x").Append(hexValue.ToString("x", CultureInfo.InvariantCulture)).Append("\"");
- WriteMessageAttrib(sb, "map", enumType.Name + "." + staticField.Name, staticField.Name);
- sb.Append("/>").AppendLine();
- }
- }
- sb.Append(" </").Append(mapKind).Append(">").AppendLine();
- }
- sb.Append(" </maps>").AppendLine();
- }
-
- // Write out the opcodes
- sb.Append(" <opcodes>").AppendLine();
- var sortedOpcodes = new List<int>(opcodeTab.Keys);
- sortedOpcodes.Sort();
- foreach (int opcode in sortedOpcodes)
- {
- sb.Append(" <opcode");
- WriteNameAndMessageAttribs(sb, "opcode", opcodeTab[opcode]);
- sb.Append(" value=\"").Append(opcode).Append("\"/>").AppendLine();
- }
- sb.Append(" </opcodes>").AppendLine();
-
- // Write out the keywords
- if (keywordTab != null)
- {
- sb.Append(" <keywords>").AppendLine();
- var sortedKeywords = new List<ulong>(keywordTab.Keys);
- sortedKeywords.Sort();
- foreach (ulong keyword in sortedKeywords)
- {
- sb.Append(" <keyword");
- WriteNameAndMessageAttribs(sb, "keyword", keywordTab[keyword]);
- sb.Append(" mask=\"0x").Append(keyword.ToString("x", CultureInfo.InvariantCulture)).Append("\"/>").AppendLine();
- }
- sb.Append(" </keywords>").AppendLine();
- }
-
- sb.Append(" <events>").AppendLine();
- sb.Append(events);
- sb.Append(" </events>").AppendLine();
-
- sb.Append(" <templates>").AppendLine();
- if (templates.Length > 0)
- {
- sb.Append(templates);
- }
- else
- {
- // Work around a cornercase ETW issue where a manifest with no templates causes
- // ETW events to not get sent to their associated channel.
- sb.Append(" <template tid=\"_empty\"></template>").AppendLine();
- }
- sb.Append(" </templates>").AppendLine();
-
- sb.Append("</provider>").AppendLine();
- sb.Append("</events>").AppendLine();
- sb.Append("</instrumentation>").AppendLine();
-
- // Output the localization information.
- sb.Append("<localization>").AppendLine();
-
- List<CultureInfo> cultures = null;
- if (resources != null && (flags & EventManifestOptions.AllCultures) != 0)
- {
- cultures = GetSupportedCultures(resources);
- }
- else
- {
- cultures = new List<CultureInfo>();
- cultures.Add(CultureInfo.CurrentUICulture);
- }
-#if ES_BUILD_STANDALONE || PROJECTN
- var sortedStrings = new List<string>(stringTab.Keys);
- sortedStrings.Sort();
-#else
- // DD 947936
- var sortedStrings = new string[stringTab.Keys.Count];
- stringTab.Keys.CopyTo(sortedStrings, 0);
- // Avoid using public Array.Sort as that attempts to access BinaryCompatibility. Unfortunately FrameworkEventSource gets called
- // very early in the app domain creation, when _FusionStore is not set up yet, resulting in a failure to run the static constructory
- // for BinaryCompatibility. This failure is then cached and a TypeInitializationException is thrown every time some code attampts to
- // access BinaryCompatibility.
- ArraySortHelper<string>.IntrospectiveSort(sortedStrings, 0, sortedStrings.Length, string.Compare);
-#endif
- foreach (var ci in cultures)
- {
- sb.Append(" <resources culture=\"").Append(ci.Name).Append("\">").AppendLine();
- sb.Append(" <stringTable>").AppendLine();
-
- foreach (var stringKey in sortedStrings)
- {
- string val = GetLocalizedMessage(stringKey, ci, etwFormat: true);
- sb.Append(" <string id=\"").Append(stringKey).Append("\" value=\"").Append(val).Append("\"/>").AppendLine();
- }
- sb.Append(" </stringTable>").AppendLine();
- sb.Append(" </resources>").AppendLine();
- }
- sb.Append("</localization>").AppendLine();
- sb.AppendLine("</instrumentationManifest>");
- return sb.ToString();
- }
-
- #region private
- private void WriteNameAndMessageAttribs(StringBuilder stringBuilder, string elementName, string name)
- {
- stringBuilder.Append(" name=\"").Append(name).Append("\"");
- WriteMessageAttrib(sb, elementName, name, name);
- }
- private void WriteMessageAttrib(StringBuilder stringBuilder, string elementName, string name, string value)
- {
- string key = elementName + "_" + name;
- // See if the user wants things localized.
- if (resources != null)
- {
- // resource fallback: strings in the neutral culture will take precedence over inline strings
- string localizedString = resources.GetString(key, CultureInfo.InvariantCulture);
- if (localizedString != null)
- value = localizedString;
- }
- if (value == null)
- return;
-
- stringBuilder.Append(" message=\"$(string.").Append(key).Append(")\"");
- string prevValue;
- if (stringTab.TryGetValue(key, out prevValue) && !prevValue.Equals(value))
- {
- ManifestError(Resources.GetResourceString("EventSource_DuplicateStringKey", key), true);
- return;
- }
-
- stringTab[key] = value;
- }
- internal string GetLocalizedMessage(string key, CultureInfo ci, bool etwFormat)
- {
- string value = null;
- if (resources != null)
- {
- string localizedString = resources.GetString(key, ci);
- if (localizedString != null)
- {
- value = localizedString;
- if (etwFormat && key.StartsWith("event_", StringComparison.Ordinal))
- {
- var evtName = key.Substring("event_".Length);
- value = TranslateToManifestConvention(value, evtName);
- }
- }
- }
- if (etwFormat && value == null)
- stringTab.TryGetValue(key, out value);
-
- return value;
- }
-
- /// <summary>
- /// There's no API to enumerate all languages an assembly is localized into, so instead
- /// we enumerate through all the "known" cultures and attempt to load a corresponding satellite
- /// assembly
- /// </summary>
- /// <param name="resources"></param>
- /// <returns></returns>
- private static List<CultureInfo> GetSupportedCultures(ResourceManager resources)
- {
- var cultures = new List<CultureInfo>();
-
- if (!cultures.Contains(CultureInfo.CurrentUICulture))
- cultures.Insert(0, CultureInfo.CurrentUICulture);
- return cultures;
- }
-
- private static string GetLevelName(EventLevel level)
- {
- return (((int)level >= 16) ? "" : "win:") + level.ToString();
- }
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- private string GetChannelName(EventChannel channel, string eventName, string eventMessage)
- {
- ChannelInfo info = null;
- if (channelTab == null || !channelTab.TryGetValue((int)channel, out info))
- {
- if (channel < EventChannel.Admin) // || channel > EventChannel.Debug)
- ManifestError(Resources.GetResourceString("EventSource_UndefinedChannel", channel, eventName));
-
- // allow channels to be auto-defined. The well known ones get their well known names, and the
- // rest get names Channel<N>. This allows users to modify the Manifest if they want more advanced features.
- if (channelTab == null)
- channelTab = new Dictionary<int, ChannelInfo>(4);
-
- string channelName = channel.ToString(); // For well know channels this is a nice name, otherwise a number
- if (EventChannel.Debug < channel)
- channelName = "Channel" + channelName; // Add a 'Channel' prefix for numbers.
-
- AddChannel(channelName, (int)channel, GetDefaultChannelAttribute(channel));
- if (!channelTab.TryGetValue((int)channel, out info))
- ManifestError(Resources.GetResourceString("EventSource_UndefinedChannel", channel, eventName));
- }
- // events that specify admin channels *must* have non-null "Message" attributes
- if (resources != null && eventMessage == null)
- eventMessage = resources.GetString("event_" + eventName, CultureInfo.InvariantCulture);
- if (info.Attribs.EventChannelType == EventChannelType.Admin && eventMessage == null)
- ManifestError(Resources.GetResourceString("EventSource_EventWithAdminChannelMustHaveMessage", eventName, info.Name));
- return info.Name;
- }
-#endif
- private string GetTaskName(EventTask task, string eventName)
- {
- if (task == EventTask.None)
- return "";
-
- string ret;
- if (taskTab == null)
- taskTab = new Dictionary<int, string>();
- if (!taskTab.TryGetValue((int)task, out ret))
- ret = taskTab[(int)task] = eventName;
- return ret;
- }
-
- private string GetOpcodeName(EventOpcode opcode, string eventName)
- {
- switch (opcode)
- {
- case EventOpcode.Info:
- return "win:Info";
- case EventOpcode.Start:
- return "win:Start";
- case EventOpcode.Stop:
- return "win:Stop";
- case EventOpcode.DataCollectionStart:
- return "win:DC_Start";
- case EventOpcode.DataCollectionStop:
- return "win:DC_Stop";
- case EventOpcode.Extension:
- return "win:Extension";
- case EventOpcode.Reply:
- return "win:Reply";
- case EventOpcode.Resume:
- return "win:Resume";
- case EventOpcode.Suspend:
- return "win:Suspend";
- case EventOpcode.Send:
- return "win:Send";
- case EventOpcode.Receive:
- return "win:Receive";
- }
-
- string ret;
- if (opcodeTab == null || !opcodeTab.TryGetValue((int)opcode, out ret))
- {
- ManifestError(Resources.GetResourceString("EventSource_UndefinedOpcode", opcode, eventName), true);
- ret = null;
- }
- return ret;
- }
-
- private string GetKeywords(ulong keywords, string eventName)
- {
- // ignore keywords associate with channels
- // See ValidPredefinedChannelKeywords def for more.
- keywords &= ~ValidPredefinedChannelKeywords;
-
- string ret = "";
- for (ulong bit = 1; bit != 0; bit <<= 1)
- {
- if ((keywords & bit) != 0)
- {
- string keyword = null;
- if ((keywordTab == null || !keywordTab.TryGetValue(bit, out keyword)) &&
- (bit >= (ulong)0x1000000000000))
- {
- // do not report Windows reserved keywords in the manifest (this allows the code
- // to be resilient to potential renaming of these keywords)
- keyword = string.Empty;
- }
- if (keyword == null)
- {
- ManifestError(Resources.GetResourceString("EventSource_UndefinedKeyword", "0x" + bit.ToString("x", CultureInfo.CurrentCulture), eventName), true);
- keyword = string.Empty;
- }
- if (ret.Length != 0 && keyword.Length != 0)
- ret = ret + " ";
- ret = ret + keyword;
- }
- }
- return ret;
- }
-
- private string GetTypeName(Type type)
- {
- if (type.IsEnum())
- {
- FieldInfo[] fields = type.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
- var typeName = GetTypeName(fields[0].FieldType);
- return typeName.Replace("win:Int", "win:UInt"); // ETW requires enums to be unsigned.
- }
-
- return GetTypeNameHelper(type);
- }
-
- private static void UpdateStringBuilder(ref StringBuilder stringBuilder, string eventMessage, int startIndex, int count)
- {
- if (stringBuilder == null)
- stringBuilder = new StringBuilder();
- stringBuilder.Append(eventMessage, startIndex, count);
- }
-
- private static readonly string[] s_escapes = { "&amp;", "&lt;", "&gt;", "&apos;", "&quot;", "%r", "%n", "%t" };
- // Manifest messages use %N conventions for their message substitutions. Translate from
- // .NET conventions. We can't use RegEx for this (we are in mscorlib), so we do it 'by hand'
- private string TranslateToManifestConvention(string eventMessage, string evtName)
- {
- StringBuilder stringBuilder = null; // We lazily create this
- int writtenSoFar = 0;
- int chIdx = -1;
- for (int i = 0; ;)
- {
- if (i >= eventMessage.Length)
- {
- if (stringBuilder == null)
- return eventMessage;
- UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar);
- return stringBuilder.ToString();
- }
-
- if (eventMessage[i] == '%')
- {
- // handle format message escaping character '%' by escaping it
- UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar);
- stringBuilder.Append("%%");
- i++;
- writtenSoFar = i;
- }
- else if (i < eventMessage.Length - 1 &&
- (eventMessage[i] == '{' && eventMessage[i + 1] == '{' || eventMessage[i] == '}' && eventMessage[i + 1] == '}'))
- {
- // handle C# escaped '{" and '}'
- UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar);
- stringBuilder.Append(eventMessage[i]);
- i++; i++;
- writtenSoFar = i;
- }
- else if (eventMessage[i] == '{')
- {
- int leftBracket = i;
- i++;
- int argNum = 0;
- while (i < eventMessage.Length && Char.IsDigit(eventMessage[i]))
- {
- argNum = argNum * 10 + eventMessage[i] - '0';
- i++;
- }
- if (i < eventMessage.Length && eventMessage[i] == '}')
- {
- i++;
- UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, leftBracket - writtenSoFar);
- int manIndex = TranslateIndexToManifestConvention(argNum, evtName);
- stringBuilder.Append('%').Append(manIndex);
- // An '!' after the insert specifier {n} will be interpreted as a literal.
- // We'll escape it so that mc.exe does not attempt to consider it the
- // beginning of a format string.
- if (i < eventMessage.Length && eventMessage[i] == '!')
- {
- i++;
- stringBuilder.Append("%!");
- }
- writtenSoFar = i;
- }
- else
- {
- ManifestError(Resources.GetResourceString("EventSource_UnsupportedMessageProperty", evtName, eventMessage));
- }
- }
- else if ((chIdx = "&<>'\"\r\n\t".IndexOf(eventMessage[i])) >= 0)
- {
- UpdateStringBuilder(ref stringBuilder, eventMessage, writtenSoFar, i - writtenSoFar);
- i++;
- stringBuilder.Append(s_escapes[chIdx]);
- writtenSoFar = i;
- }
- else
- i++;
- }
- }
-
- private int TranslateIndexToManifestConvention(int idx, string evtName)
- {
- List<int> byteArrArgIndices;
- if (perEventByteArrayArgIndices.TryGetValue(evtName, out byteArrArgIndices))
- {
- foreach (var byArrIdx in byteArrArgIndices)
- {
- if (idx >= byArrIdx)
- ++idx;
- else
- break;
- }
- }
- return idx + 1;
- }
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- class ChannelInfo
- {
- public string Name;
- public ulong Keywords;
- public EventChannelAttribute Attribs;
- }
-#endif
-
- Dictionary<int, string> opcodeTab;
- Dictionary<int, string> taskTab;
-#if FEATURE_MANAGED_ETW_CHANNELS
- Dictionary<int, ChannelInfo> channelTab;
-#endif
- Dictionary<ulong, string> keywordTab;
- Dictionary<string, Type> mapsTab;
-
- Dictionary<string, string> stringTab; // Maps unlocalized strings to localized ones
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- // WCF used EventSource to mimic a existing ETW manifest. To support this
- // in just their case, we allowed them to specify the keywords associated
- // with their channels explicitly. ValidPredefinedChannelKeywords is
- // this set of channel keywords that we allow to be explicitly set. You
- // can ignore these bits otherwise.
- internal const ulong ValidPredefinedChannelKeywords = 0xF000000000000000;
- ulong nextChannelKeywordBit = 0x8000000000000000; // available Keyword bit to be used for next channel definition, grows down
- const int MaxCountChannels = 8; // a manifest can defined at most 8 ETW channels
-#endif
-
- StringBuilder sb; // Holds the provider information.
- StringBuilder events; // Holds the events.
- StringBuilder templates;
-
-#if FEATURE_MANAGED_ETW_CHANNELS
- string providerName;
-#endif
- ResourceManager resources; // Look up localized strings here.
- EventManifestOptions flags;
- IList<string> errors; // list of currently encountered errors
- Dictionary<string, List<int>> perEventByteArrayArgIndices; // "event_name" -> List_of_Indices_of_Byte[]_Arg
-
- // State we track between StartEvent and EndEvent.
- string eventName; // Name of the event currently being processed.
- int numParams; // keeps track of the number of args the event has.
- List<int> byteArrArgIndices; // keeps track of the index of each byte[] argument
- #endregion
- }
-
- /// <summary>
- /// Used to send the m_rawManifest into the event dispatcher as a series of events.
- /// </summary>
- internal struct ManifestEnvelope
- {
- public const int MaxChunkSize = 0xFF00;
- public enum ManifestFormats : byte
- {
- SimpleXmlFormat = 1, // simply dump the XML manifest as UTF8
- }
-
- public ManifestFormats Format;
- public byte MajorVersion;
- public byte MinorVersion;
- public byte Magic;
- public ushort TotalChunks;
- public ushort ChunkNumber;
- };
-
- #endregion
-}
-
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs
deleted file mode 100644
index 3fc9d545b8..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSourceException.cs
+++ /dev/null
@@ -1,53 +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.Runtime.Serialization;
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Exception that is thrown when an error occurs during EventSource operation.
- /// </summary>
-#if (!ES_BUILD_PCL && !PROJECTN)
- [Serializable]
-#endif
- public class EventSourceException : Exception
- {
- /// <summary>
- /// Initializes a new instance of the EventSourceException class.
- /// </summary>
- public EventSourceException() :
- base(Resources.GetResourceString("EventSource_ListenerWriteFailure")) { }
-
- /// <summary>
- /// Initializes a new instance of the EventSourceException class with a specified error message.
- /// </summary>
- public EventSourceException(string message) : base(message) { }
-
- /// <summary>
- /// Initializes a new instance of the EventSourceException class with a specified error message
- /// and a reference to the inner exception that is the cause of this exception.
- /// </summary>
- public EventSourceException(string message, Exception innerException) : base(message, innerException) { }
-
-#if (!ES_BUILD_PCL && !PROJECTN)
- /// <summary>
- /// Initializes a new instance of the EventSourceException class with serialized data.
- /// </summary>
- protected EventSourceException(SerializationInfo info, StreamingContext context) : base(info, context) { }
-#endif
-
- internal EventSourceException(Exception innerException) :
- base(Resources.GetResourceString("EventSource_ListenerWriteFailure"), innerException) { }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
index 0a689efe92..b691dd38b9 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
@@ -128,12 +128,12 @@ namespace System.Diagnostics.Tracing
private static string GetResourceString(string key, params object[] args)
{
- return Environment.GetResourceString(key, args);
+ return SR.Format(SR.GetResourceString(key), args);
}
-
+
private static readonly bool m_EventSourcePreventRecursion = false;
}
-
+
internal partial class ManifestBuilder
{
private string GetTypeNameHelper(Type type)
@@ -174,13 +174,13 @@ namespace System.Diagnostics.Tracing
return "win:Pointer";
else if ((type.IsArray || type.IsPointer) && type.GetElementType() == typeof(byte))
return "win:Binary";
-
+
ManifestError(Resources.GetResourceString("EventSource_UnsupportedEventTypeInManifest", type.Name), true);
return string.Empty;
}
}
}
-
+
internal partial class EventProvider
{
internal unsafe int SetInformation(
@@ -197,7 +197,7 @@ namespace System.Diagnostics.Tracing
status = UnsafeNativeMethods.ManifestEtw.EventSetInformation(
m_regHandle,
eventInfoClass,
- (void *)data,
+ (void*)data,
(int)dataSize);
}
catch (TypeLoadException)
@@ -209,12 +209,12 @@ namespace System.Diagnostics.Tracing
return status;
}
}
-
+
internal static class Resources
{
internal static string GetResourceString(string key, params object[] args)
{
- return Environment.GetResourceString(key, args);
+ return SR.Format(SR.GetResourceString(key), args);
}
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs
index 80c524b350..d746f58f24 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/FrameworkEventSource.cs
@@ -8,6 +8,7 @@
//
// Managed event source for things that can version with MSCORLIB.
//
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -15,8 +16,8 @@ using System.Reflection;
using System.Text;
using System.Runtime.CompilerServices;
-namespace System.Diagnostics.Tracing {
-
+namespace System.Diagnostics.Tracing
+{
// To use the framework provider
//
// \\clrmain\tools\Perfmonitor /nokernel /noclr /provider:8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1 start
@@ -28,7 +29,8 @@ namespace System.Diagnostics.Tracing {
//
[FriendAccessAllowed]
[EventSource(Guid = "8E9F5090-2D75-4d03-8A81-E5AFBF85DAF1", Name = "System.Diagnostics.Eventing.FrameworkEventSource")]
- sealed internal class FrameworkEventSource : EventSource {
+ sealed internal class FrameworkEventSource : EventSource
+ {
// Defines the singleton instance for the Resources ETW provider
public static readonly FrameworkEventSource Log = new FrameworkEventSource();
@@ -36,16 +38,17 @@ namespace System.Diagnostics.Tracing {
// Often each task has a keyword, but where tasks are determined by subsystem, keywords are determined by
// usefulness to end users to filter. Generally users don't mind extra events if they are not high volume
// so grouping low volume events together in a single keywords is OK (users can post-filter by task if desired)
- public static class Keywords {
- public const EventKeywords Loader = (EventKeywords)0x0001; // This is bit 0
- public const EventKeywords ThreadPool = (EventKeywords)0x0002;
- public const EventKeywords NetClient = (EventKeywords)0x0004;
+ public static class Keywords
+ {
+ public const EventKeywords Loader = (EventKeywords)0x0001; // This is bit 0
+ public const EventKeywords ThreadPool = (EventKeywords)0x0002;
+ public const EventKeywords NetClient = (EventKeywords)0x0004;
//
// This is a private event we do not want to expose to customers. It is to be used for profiling
// uses of dynamic type loading by ProjectN applications running on the desktop CLR
//
public const EventKeywords DynamicTypeUsage = (EventKeywords)0x0008;
- public const EventKeywords ThreadTransfer = (EventKeywords)0x0010;
+ public const EventKeywords ThreadTransfer = (EventKeywords)0x0010;
}
/// <summary>ETW tasks that have start/stop events.</summary>
@@ -53,7 +56,7 @@ namespace System.Diagnostics.Tracing {
public static class Tasks // this name is important for EventSource
{
/// <summary>Begin / End - GetResponse.</summary>
- public const EventTask GetResponse = (EventTask)1;
+ public const EventTask GetResponse = (EventTask)1;
/// <summary>Begin / End - GetRequestStream</summary>
public const EventTask GetRequestStream = (EventTask)2;
/// <summary>Send / Receive - begin transfer/end transfer</summary>
@@ -211,18 +214,21 @@ namespace System.Diagnostics.Tracing {
// ResourceManager Event Definitions
[Event(1, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerLookupStarted(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerLookupStarted(String baseName, String mainAssemblyName, String cultureName)
+ {
WriteEvent(1, baseName, mainAssemblyName, cultureName);
}
[Event(2, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerLookingForResourceSet(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerLookingForResourceSet(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(2, baseName, mainAssemblyName, cultureName);
}
[Event(3, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerFoundResourceSetInCache(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerFoundResourceSetInCache(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(3, baseName, mainAssemblyName, cultureName);
}
@@ -231,119 +237,138 @@ namespace System.Diagnostics.Tracing {
// the cache. This can happen if you have an assembly load callback that called into this
// instance of the ResourceManager.
[Event(4, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(4, baseName, mainAssemblyName, cultureName);
}
// manifest resource stream lookup succeeded
[Event(5, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerStreamFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName) {
+ public void ResourceManagerStreamFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName)
+ {
if (IsEnabled())
WriteEvent(5, baseName, mainAssemblyName, cultureName, loadedAssemblyName, resourceFileName);
}
// manifest resource stream lookup failed
[Event(6, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerStreamNotFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName) {
+ public void ResourceManagerStreamNotFound(String baseName, String mainAssemblyName, String cultureName, String loadedAssemblyName, String resourceFileName)
+ {
if (IsEnabled())
WriteEvent(6, baseName, mainAssemblyName, cultureName, loadedAssemblyName, resourceFileName);
}
[Event(7, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, String mainAssemblyName, String cultureName, String assemblyName) {
+ public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, String mainAssemblyName, String cultureName, String assemblyName)
+ {
if (IsEnabled())
WriteEvent(7, baseName, mainAssemblyName, cultureName, assemblyName);
}
[Event(8, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, String mainAssemblyName, String cultureName, String assemblyName) {
+ public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, String mainAssemblyName, String cultureName, String assemblyName)
+ {
if (IsEnabled())
WriteEvent(8, baseName, mainAssemblyName, cultureName, assemblyName);
}
[Event(9, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName) {
+ public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName)
+ {
if (IsEnabled())
WriteEvent(9, baseName, mainAssemblyName, assemblyName, resourceFileName);
}
[Event(10, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName) {
+ public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, String mainAssemblyName, String assemblyName, String resourceFileName)
+ {
if (IsEnabled())
WriteEvent(10, baseName, mainAssemblyName, assemblyName, resourceFileName);
}
// Could not access the manifest resource the assembly
[Event(11, Level = EventLevel.Error, Keywords = Keywords.Loader)]
- public void ResourceManagerManifestResourceAccessDenied(String baseName, String mainAssemblyName, String assemblyName, String canonicalName) {
+ public void ResourceManagerManifestResourceAccessDenied(String baseName, String mainAssemblyName, String assemblyName, String canonicalName)
+ {
if (IsEnabled())
WriteEvent(11, baseName, mainAssemblyName, assemblyName, canonicalName);
}
// Neutral resources are sufficient for this culture. Skipping satellites
[Event(12, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerNeutralResourcesSufficient(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerNeutralResourcesSufficient(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(12, baseName, mainAssemblyName, cultureName);
}
[Event(13, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerNeutralResourceAttributeMissing(String mainAssemblyName) {
+ public void ResourceManagerNeutralResourceAttributeMissing(String mainAssemblyName)
+ {
if (IsEnabled())
WriteEvent(13, mainAssemblyName);
}
[Event(14, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName, String fileName) {
+ public void ResourceManagerCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName, String fileName)
+ {
if (IsEnabled())
WriteEvent(14, baseName, mainAssemblyName, cultureName, fileName);
}
[Event(15, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerNotCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerNotCreatingResourceSet(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(15, baseName, mainAssemblyName, cultureName);
}
[Event(16, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerLookupFailed(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerLookupFailed(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(16, baseName, mainAssemblyName, cultureName);
}
[Event(17, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerReleasingResources(String baseName, String mainAssemblyName) {
+ public void ResourceManagerReleasingResources(String baseName, String mainAssemblyName)
+ {
if (IsEnabled())
WriteEvent(17, baseName, mainAssemblyName);
}
[Event(18, Level = EventLevel.Warning, Keywords = Keywords.Loader)]
- public void ResourceManagerNeutralResourcesNotFound(String baseName, String mainAssemblyName, String resName) {
+ public void ResourceManagerNeutralResourcesNotFound(String baseName, String mainAssemblyName, String resName)
+ {
if (IsEnabled())
WriteEvent(18, baseName, mainAssemblyName, resName);
}
[Event(19, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerNeutralResourcesFound(String baseName, String mainAssemblyName, String resName) {
+ public void ResourceManagerNeutralResourcesFound(String baseName, String mainAssemblyName, String resName)
+ {
if (IsEnabled())
WriteEvent(19, baseName, mainAssemblyName, resName);
}
[Event(20, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerAddingCultureFromConfigFile(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerAddingCultureFromConfigFile(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(20, baseName, mainAssemblyName, cultureName);
}
[Event(21, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerCultureNotFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerCultureNotFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(21, baseName, mainAssemblyName, cultureName);
}
[Event(22, Level = EventLevel.Informational, Keywords = Keywords.Loader)]
- public void ResourceManagerCultureFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName) {
+ public void ResourceManagerCultureFoundInConfigFile(String baseName, String mainAssemblyName, String cultureName)
+ {
if (IsEnabled())
WriteEvent(22, baseName, mainAssemblyName, cultureName);
}
@@ -352,159 +377,185 @@ namespace System.Diagnostics.Tracing {
// ResourceManager Event Wrappers
[NonEvent]
- public void ResourceManagerLookupStarted(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerLookupStarted(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerLookupStarted(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerLookingForResourceSet(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerLookingForResourceSet(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerLookingForResourceSet(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerFoundResourceSetInCache(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerFoundResourceSetInCache(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerFoundResourceSetInCache(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerFoundResourceSetInCacheUnexpected(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerFoundResourceSetInCacheUnexpected(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerStreamFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName) {
+ public void ResourceManagerStreamFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName)
+ {
if (IsEnabled())
ResourceManagerStreamFound(baseName, GetName(mainAssembly), cultureName, GetName(loadedAssembly), resourceFileName);
}
[NonEvent]
- public void ResourceManagerStreamNotFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName) {
+ public void ResourceManagerStreamNotFound(String baseName, Assembly mainAssembly, String cultureName, Assembly loadedAssembly, String resourceFileName)
+ {
if (IsEnabled())
ResourceManagerStreamNotFound(baseName, GetName(mainAssembly), cultureName, GetName(loadedAssembly), resourceFileName);
}
[NonEvent]
- public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, Assembly mainAssembly, String cultureName, String assemblyName) {
+ public void ResourceManagerGetSatelliteAssemblySucceeded(String baseName, Assembly mainAssembly, String cultureName, String assemblyName)
+ {
if (IsEnabled())
ResourceManagerGetSatelliteAssemblySucceeded(baseName, GetName(mainAssembly), cultureName, assemblyName);
}
[NonEvent]
- public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, Assembly mainAssembly, String cultureName, String assemblyName) {
+ public void ResourceManagerGetSatelliteAssemblyFailed(String baseName, Assembly mainAssembly, String cultureName, String assemblyName)
+ {
if (IsEnabled())
ResourceManagerGetSatelliteAssemblyFailed(baseName, GetName(mainAssembly), cultureName, assemblyName);
}
[NonEvent]
- public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName) {
+ public void ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName)
+ {
if (IsEnabled())
ResourceManagerCaseInsensitiveResourceStreamLookupSucceeded(baseName, GetName(mainAssembly), assemblyName, resourceFileName);
}
[NonEvent]
- public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName) {
+ public void ResourceManagerCaseInsensitiveResourceStreamLookupFailed(String baseName, Assembly mainAssembly, String assemblyName, String resourceFileName)
+ {
if (IsEnabled())
ResourceManagerCaseInsensitiveResourceStreamLookupFailed(baseName, GetName(mainAssembly), assemblyName, resourceFileName);
}
[NonEvent]
- public void ResourceManagerManifestResourceAccessDenied(String baseName, Assembly mainAssembly, String assemblyName, String canonicalName) {
+ public void ResourceManagerManifestResourceAccessDenied(String baseName, Assembly mainAssembly, String assemblyName, String canonicalName)
+ {
if (IsEnabled())
ResourceManagerManifestResourceAccessDenied(baseName, GetName(mainAssembly), assemblyName, canonicalName);
}
[NonEvent]
- public void ResourceManagerNeutralResourcesSufficient(String baseName, Assembly mainAssembly, String cultureName) {
- if (IsEnabled())
+ public void ResourceManagerNeutralResourcesSufficient(String baseName, Assembly mainAssembly, String cultureName)
+ {
+ if (IsEnabled())
ResourceManagerNeutralResourcesSufficient(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerNeutralResourceAttributeMissing(Assembly mainAssembly) {
+ public void ResourceManagerNeutralResourceAttributeMissing(Assembly mainAssembly)
+ {
if (IsEnabled())
ResourceManagerNeutralResourceAttributeMissing(GetName(mainAssembly));
}
[NonEvent]
- public void ResourceManagerCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName, String fileName) {
+ public void ResourceManagerCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName, String fileName)
+ {
if (IsEnabled())
ResourceManagerCreatingResourceSet(baseName, GetName(mainAssembly), cultureName, fileName);
}
[NonEvent]
- public void ResourceManagerNotCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerNotCreatingResourceSet(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerNotCreatingResourceSet(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerLookupFailed(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerLookupFailed(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerLookupFailed(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerReleasingResources(String baseName, Assembly mainAssembly) {
+ public void ResourceManagerReleasingResources(String baseName, Assembly mainAssembly)
+ {
if (IsEnabled())
ResourceManagerReleasingResources(baseName, GetName(mainAssembly));
}
[NonEvent]
- public void ResourceManagerNeutralResourcesNotFound(String baseName, Assembly mainAssembly, String resName) {
+ public void ResourceManagerNeutralResourcesNotFound(String baseName, Assembly mainAssembly, String resName)
+ {
if (IsEnabled())
ResourceManagerNeutralResourcesNotFound(baseName, GetName(mainAssembly), resName);
}
[NonEvent]
- public void ResourceManagerNeutralResourcesFound(String baseName, Assembly mainAssembly, String resName) {
+ public void ResourceManagerNeutralResourcesFound(String baseName, Assembly mainAssembly, String resName)
+ {
if (IsEnabled())
ResourceManagerNeutralResourcesFound(baseName, GetName(mainAssembly), resName);
}
[NonEvent]
- public void ResourceManagerAddingCultureFromConfigFile(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerAddingCultureFromConfigFile(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerAddingCultureFromConfigFile(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerCultureNotFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerCultureNotFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerCultureNotFoundInConfigFile(baseName, GetName(mainAssembly), cultureName);
}
[NonEvent]
- public void ResourceManagerCultureFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName) {
+ public void ResourceManagerCultureFoundInConfigFile(String baseName, Assembly mainAssembly, String cultureName)
+ {
if (IsEnabled())
ResourceManagerCultureFoundInConfigFile(baseName, GetName(mainAssembly), cultureName);
}
- private static string GetName(Assembly assembly) {
+ private static string GetName(Assembly assembly)
+ {
if (assembly == null)
return "<<NULL>>";
else
return assembly.FullName;
}
- [Event(30, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool|Keywords.ThreadTransfer)]
- public void ThreadPoolEnqueueWork(long workID) {
+ [Event(30, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool | Keywords.ThreadTransfer)]
+ public void ThreadPoolEnqueueWork(long workID)
+ {
WriteEvent(30, workID);
}
[NonEvent]
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void ThreadPoolEnqueueWorkObject(object workID) {
+ public unsafe void ThreadPoolEnqueueWorkObject(object workID)
+ {
// convert the Object Id to a long
- ThreadPoolEnqueueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID)));
+ ThreadPoolEnqueueWork((long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref workID)));
}
- [Event(31, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool|Keywords.ThreadTransfer)]
- public void ThreadPoolDequeueWork(long workID) {
+ [Event(31, Level = EventLevel.Verbose, Keywords = Keywords.ThreadPool | Keywords.ThreadTransfer)]
+ public void ThreadPoolDequeueWork(long workID)
+ {
WriteEvent(31, workID);
}
@@ -512,36 +563,41 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void ThreadPoolDequeueWorkObject(object workID) {
+ public unsafe void ThreadPoolDequeueWorkObject(object workID)
+ {
// convert the Object Id to a long
- ThreadPoolDequeueWork((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref workID)));
+ ThreadPoolDequeueWork((long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref workID)));
}
// In the desktop runtime they don't use Tasks for the point at which the response happens, which means that the
// Activity ID created by start using implicit activity IDs does not match. Thus disable implicit activities (until we fix that)
- [Event(140, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable,
+ [Event(140, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions = EventActivityOptions.Disable,
Task = Tasks.GetResponse, Opcode = EventOpcode.Start, Version = 1)]
- private void GetResponseStart(long id, string uri, bool success, bool synchronous) {
+ private void GetResponseStart(long id, string uri, bool success, bool synchronous)
+ {
WriteEvent(140, id, uri, success, synchronous);
}
- [Event(141, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable,
+ [Event(141, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions = EventActivityOptions.Disable,
Task = Tasks.GetResponse, Opcode = EventOpcode.Stop, Version = 1)]
- private void GetResponseStop(long id, bool success, bool synchronous, int statusCode) {
+ private void GetResponseStop(long id, bool success, bool synchronous, int statusCode)
+ {
WriteEvent(141, id, success, synchronous, statusCode);
}
// In the desktop runtime they don't use Tasks for the point at which the response happens, which means that the
// Activity ID created by start using implicit activity IDs does not match. Thus disable implicit activities (until we fix that)
- [Event(142, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable,
+ [Event(142, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions = EventActivityOptions.Disable,
Task = Tasks.GetRequestStream, Opcode = EventOpcode.Start, Version = 1)]
- private void GetRequestStreamStart(long id, string uri, bool success, bool synchronous) {
+ private void GetRequestStreamStart(long id, string uri, bool success, bool synchronous)
+ {
WriteEvent(142, id, uri, success, synchronous);
}
- [Event(143, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions=EventActivityOptions.Disable,
+ [Event(143, Level = EventLevel.Informational, Keywords = Keywords.NetClient, ActivityOptions = EventActivityOptions.Disable,
Task = Tasks.GetRequestStream, Opcode = EventOpcode.Stop, Version = 1)]
- private void GetRequestStreamStop(long id, bool success, bool synchronous) {
+ private void GetRequestStreamStop(long id, bool success, bool synchronous)
+ {
WriteEvent(143, id, success, synchronous);
}
@@ -549,16 +605,18 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void BeginGetResponse(object id, string uri, bool success, bool synchronous) {
+ public unsafe void BeginGetResponse(object id, string uri, bool success, bool synchronous)
+ {
if (IsEnabled())
GetResponseStart(IdForObject(id), uri, success, synchronous);
}
-
+
[NonEvent]
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void EndGetResponse(object id, bool success, bool synchronous, int statusCode) {
+ public unsafe void EndGetResponse(object id, bool success, bool synchronous, int statusCode)
+ {
if (IsEnabled())
GetResponseStop(IdForObject(id), success, synchronous, statusCode);
}
@@ -567,7 +625,8 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void BeginGetRequestStream(object id, string uri, bool success, bool synchronous) {
+ public unsafe void BeginGetRequestStream(object id, string uri, bool success, bool synchronous)
+ {
if (IsEnabled())
GetRequestStreamStart(IdForObject(id), uri, success, synchronous);
}
@@ -576,7 +635,8 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void EndGetRequestStream(object id, bool success, bool synchronous) {
+ public unsafe void EndGetRequestStream(object id, bool success, bool synchronous)
+ {
if (IsEnabled())
GetRequestStreamStop(IdForObject(id), success, synchronous);
}
@@ -589,7 +649,8 @@ namespace System.Diagnostics.Tracing {
// 3 - WinRT dispatch operations
// info - any additional information user code might consider interesting
[Event(150, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Send)]
- public void ThreadTransferSend(long id, int kind, string info, bool multiDequeues) {
+ public void ThreadTransferSend(long id, int kind, string info, bool multiDequeues)
+ {
if (IsEnabled())
WriteEvent(150, id, kind, info, multiDequeues);
}
@@ -600,8 +661,9 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void ThreadTransferSendObj(object id, int kind, string info, bool multiDequeues) {
- ThreadTransferSend((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info, multiDequeues);
+ public unsafe void ThreadTransferSendObj(object id, int kind, string info, bool multiDequeues)
+ {
+ ThreadTransferSend((long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info, multiDequeues);
}
// id - represents a correlation ID that allows correlation of two activities, one stamped by
@@ -612,7 +674,8 @@ namespace System.Diagnostics.Tracing {
// 3 - WinRT dispatch operations
// info - any additional information user code might consider interesting
[Event(151, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = EventOpcode.Receive)]
- public void ThreadTransferReceive(long id, int kind, string info) {
+ public void ThreadTransferReceive(long id, int kind, string info)
+ {
if (IsEnabled())
WriteEvent(151, id, kind, info);
}
@@ -623,8 +686,9 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void ThreadTransferReceiveObj(object id, int kind, string info) {
- ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info);
+ public unsafe void ThreadTransferReceiveObj(object id, int kind, string info)
+ {
+ ThreadTransferReceive((long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info);
}
// id - represents a correlation ID that allows correlation of two activities, one stamped by
@@ -635,7 +699,8 @@ namespace System.Diagnostics.Tracing {
// 3 - WinRT dispatch operations
// info - any additional information user code might consider interesting
[Event(152, Level = EventLevel.Informational, Keywords = Keywords.ThreadTransfer, Task = Tasks.ThreadTransfer, Opcode = Opcodes.ReceiveHandled)]
- public void ThreadTransferReceiveHandled(long id, int kind, string info) {
+ public void ThreadTransferReceiveHandled(long id, int kind, string info)
+ {
if (IsEnabled())
WriteEvent(152, id, kind, info);
}
@@ -646,15 +711,17 @@ namespace System.Diagnostics.Tracing {
#if !CORECLR
[System.Security.SecuritySafeCritical]
#endif // !CORECLR
- public unsafe void ThreadTransferReceiveHandledObj(object id, int kind, string info) {
- ThreadTransferReceive((long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info);
+ public unsafe void ThreadTransferReceiveHandledObj(object id, int kind, string info)
+ {
+ ThreadTransferReceive((long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref id)), kind, info);
}
// return a stable ID for a an object. We use the hash code which is not truely unique but is
// close enough for now at least. we add to it 0x7FFFFFFF00000000 to make it distinguishable
// from the style of ID that simply casts the object reference to a long (since old versions of the
// runtime will emit IDs of that form).
- private static long IdForObject(object obj) {
+ private static long IdForObject(object obj)
+ {
return obj.GetHashCode() + 0x7FFFFFFF00000000;
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs b/src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs
deleted file mode 100644
index e090c4f106..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/StubEnvironment.cs
+++ /dev/null
@@ -1,373 +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.Collections.Generic;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing.Internal
-#else
-namespace System.Diagnostics.Tracing.Internal
-#endif
-{
-#if ES_BUILD_AGAINST_DOTNET_V35
- using Microsoft.Internal;
-#endif
- using Microsoft.Reflection;
- using System.Reflection;
-
- internal static class Environment
- {
- public static readonly string NewLine = System.Environment.NewLine;
-
- public static int TickCount
- { get { return System.Environment.TickCount; } }
-
- public static string GetResourceString(string key, params object[] args)
- {
- string fmt = rm.GetString(key);
- if (fmt != null)
- return string.Format(fmt, args);
-
- string sargs = String.Empty;
- foreach(var arg in args)
- {
- if (sargs != String.Empty)
- sargs += ", ";
- sargs += arg.ToString();
- }
-
- return key + " (" + sargs + ")";
- }
-
- public static string GetRuntimeResourceString(string key, params object[] args)
- {
- return GetResourceString(key, args);
- }
-
- private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly());
- }
-}
-
-#if ES_BUILD_AGAINST_DOTNET_V35
-
-namespace Microsoft.Diagnostics.Contracts.Internal
-{
- internal class Contract
- {
- public static void Assert(bool invariant)
- {
- Assert(invariant, string.Empty);
- }
- public static void Assert(bool invariant, string message)
- {
- if (!invariant)
- {
- if (System.Diagnostics.Debugger.IsAttached)
- System.Diagnostics.Debugger.Break();
- throw new Exception("Assertion failed: " + message);
- }
- }
- public static void EndContractBlock()
- { }
- }
-}
-
-
-namespace Microsoft.Internal
-{
- using System.Text;
-
- internal static class Tuple
- {
- public static Tuple<T1> Create<T1>(T1 item1)
- {
- return new Tuple<T1>(item1);
- }
-
- public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2)
- {
- return new Tuple<T1, T2>(item1, item2);
- }
- }
-
- [Serializable]
- internal class Tuple<T1>
- {
- private readonly T1 m_Item1;
-
- public T1 Item1 { get { return m_Item1; } }
-
- public Tuple(T1 item1)
- {
- m_Item1 = item1;
- }
-
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("(");
- sb.Append(m_Item1);
- sb.Append(")");
- return sb.ToString();
- }
-
- int Size
- {
- get
- {
- return 1;
- }
- }
- }
-
- [Serializable]
- public class Tuple<T1, T2>
- {
- private readonly T1 m_Item1;
- private readonly T2 m_Item2;
-
- public T1 Item1 { get { return m_Item1; } }
- public T2 Item2 { get { return m_Item2; } }
-
- public Tuple(T1 item1, T2 item2)
- {
- m_Item1 = item1;
- m_Item2 = item2;
- }
-
- public override string ToString()
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("(");
- sb.Append(m_Item1);
- sb.Append(", ");
- sb.Append(m_Item2);
- sb.Append(")");
- return sb.ToString();
- }
-
- int Size
- {
- get
- {
- return 2;
- }
- }
- }
-}
-
-#endif
-
-namespace Microsoft.Reflection
-{
- using System.Reflection;
-
-#if (ES_BUILD_PCL || PROJECTN)
- [Flags]
- public enum BindingFlags
- {
- DeclaredOnly = 0x02, // Only look at the members declared on the Type
- Instance = 0x04, // Include Instance members in search
- Static = 0x08, // Include Static members in search
- Public = 0x10, // Include Public members in search
- NonPublic = 0x20, // Include Non-Public members in search
- }
-
- public enum TypeCode {
- Empty = 0, // Null reference
- Object = 1, // Instance that isn't a value
- DBNull = 2, // Database null value
- Boolean = 3, // Boolean
- Char = 4, // Unicode character
- SByte = 5, // Signed 8-bit integer
- Byte = 6, // Unsigned 8-bit integer
- Int16 = 7, // Signed 16-bit integer
- UInt16 = 8, // Unsigned 16-bit integer
- Int32 = 9, // Signed 32-bit integer
- UInt32 = 10, // Unsigned 32-bit integer
- Int64 = 11, // Signed 64-bit integer
- UInt64 = 12, // Unsigned 64-bit integer
- Single = 13, // IEEE 32-bit float
- Double = 14, // IEEE 64-bit double
- Decimal = 15, // Decimal
- DateTime = 16, // DateTime
- String = 18, // Unicode character string
- }
-#endif
- static class ReflectionExtensions
- {
-#if (!ES_BUILD_PCL && !PROJECTN)
-
- //
- // Type extension methods
- //
- public static bool IsEnum(this Type type) { return type.IsEnum; }
- public static bool IsAbstract(this Type type) { return type.IsAbstract; }
- public static bool IsSealed(this Type type) { return type.IsSealed; }
- public static bool IsValueType(this Type type) { return type.IsValueType; }
- public static bool IsGenericType(this Type type) { return type.IsGenericType; }
- public static Type BaseType(this Type type) { return type.BaseType; }
- public static Assembly Assembly(this Type type) { return type.Assembly; }
- public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); }
-
- public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; }
-
-#else // ES_BUILD_PCL
-
- //
- // Type extension methods
- //
- public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; }
- public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; }
- public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; }
- public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; }
- public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; }
- public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; }
- public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; }
- public static IEnumerable<PropertyInfo> GetProperties(this Type type) { return type.GetRuntimeProperties(); }
- public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; }
- public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; }
-
- public static MethodInfo[] GetMethods(this Type type, BindingFlags flags)
- {
- // Minimal implementation to cover only the cases we need
- System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
- System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0);
- Func<MethodInfo, bool> visFilter;
- Func<MethodInfo, bool> instFilter;
- switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
- {
- case 0: visFilter = mi => false; break;
- case BindingFlags.Public: visFilter = mi => mi.IsPublic; break;
- case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break;
- default: visFilter = mi => true; break;
- }
- switch (flags & (BindingFlags.Instance | BindingFlags.Static))
- {
- case 0: instFilter = mi => false; break;
- case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break;
- case BindingFlags.Static: instFilter = mi => mi.IsStatic; break;
- default: instFilter = mi => true; break;
- }
- List<MethodInfo> methodInfos = new List<MethodInfo>();
- foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods)
- {
- if (visFilter(declaredMethod) && instFilter(declaredMethod))
- methodInfos.Add(declaredMethod);
- }
- return methodInfos.ToArray();
- }
- public static FieldInfo[] GetFields(this Type type, BindingFlags flags)
- {
- // Minimal implementation to cover only the cases we need
- System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0);
- System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0);
- Func<FieldInfo, bool> visFilter;
- Func<FieldInfo, bool> instFilter;
- switch (flags & (BindingFlags.Public | BindingFlags.NonPublic))
- {
- case 0: visFilter = fi => false; break;
- case BindingFlags.Public: visFilter = fi => fi.IsPublic; break;
- case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break;
- default: visFilter = fi => true; break;
- }
- switch (flags & (BindingFlags.Instance | BindingFlags.Static))
- {
- case 0: instFilter = fi => false; break;
- case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break;
- case BindingFlags.Static: instFilter = fi => fi.IsStatic; break;
- default: instFilter = fi => true; break;
- }
- List<FieldInfo> fieldInfos = new List<FieldInfo>();
- foreach (var declaredField in type.GetTypeInfo().DeclaredFields)
- {
- if (visFilter(declaredField) && instFilter(declaredField))
- fieldInfos.Add(declaredField);
- }
- return fieldInfos.ToArray();
- }
- public static Type GetNestedType(this Type type, string nestedTypeName)
- {
- TypeInfo ti = null;
- foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes)
- {
- if (nt.Name == nestedTypeName)
- {
- ti = nt;
- break;
- }
- }
- return ti == null ? null : ti.AsType();
- }
- public static TypeCode GetTypeCode(this Type type)
- {
- if (type == typeof(bool)) return TypeCode.Boolean;
- else if (type == typeof(byte)) return TypeCode.Byte;
- else if (type == typeof(char)) return TypeCode.Char;
- else if (type == typeof(ushort)) return TypeCode.UInt16;
- else if (type == typeof(uint)) return TypeCode.UInt32;
- else if (type == typeof(ulong)) return TypeCode.UInt64;
- else if (type == typeof(sbyte)) return TypeCode.SByte;
- else if (type == typeof(short)) return TypeCode.Int16;
- else if (type == typeof(int)) return TypeCode.Int32;
- else if (type == typeof(long)) return TypeCode.Int64;
- else if (type == typeof(string)) return TypeCode.String;
- else if (type == typeof(float)) return TypeCode.Single;
- else if (type == typeof(double)) return TypeCode.Double;
- else if (type == typeof(DateTime)) return TypeCode.DateTime;
- else if (type == (typeof(Decimal))) return TypeCode.Decimal;
- else return TypeCode.Object;
- }
-
- //
- // FieldInfo extension methods
- //
- public static object GetRawConstantValue(this FieldInfo fi)
- { return fi.GetValue(null); }
-
- //
- // Assembly extension methods
- //
- public static bool ReflectionOnly(this Assembly assm)
- {
- // In PCL we can't load in reflection-only context
- return false;
- }
-
-#endif
- }
-}
-
-// Defining some no-ops in PCL builds
-#if ES_BUILD_PCL || PROJECTN
-namespace System.Security
-{
- class SuppressUnmanagedCodeSecurityAttribute : Attribute { }
-
- enum SecurityAction { Demand }
-}
-namespace System.Security.Permissions
-{
- class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } }
- class PermissionSetAttribute : Attribute
- {
- public PermissionSetAttribute(System.Security.SecurityAction action) { }
- public bool Unrestricted { get; set; }
- }
-}
-#endif
-
-#if PROJECTN
-namespace System
-{
- public static class AppDomain
- {
- public static int GetCurrentThreadId()
- {
- return (int)Interop.mincore.GetCurrentThreadId();
- }
- }
-}
-#endif
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs
deleted file mode 100644
index 5771354f67..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ArrayTypeInfo.cs
+++ /dev/null
@@ -1,63 +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.Collections.Generic;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- internal sealed class ArrayTypeInfo : TraceLoggingTypeInfo
- {
- private readonly TraceLoggingTypeInfo elementInfo;
-
- public ArrayTypeInfo(Type type, TraceLoggingTypeInfo elementInfo)
- : base(type)
- {
- this.elementInfo = elementInfo;
- }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.BeginBufferedArray();
- this.elementInfo.WriteMetadata(collector, name, format);
- collector.EndBufferedArray();
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- var bookmark = collector.BeginBufferedArray();
-
- var count = 0;
- Array array = (Array)value.ReferenceValue;
- if (array != null)
- {
- count = array.Length;
- for (int i = 0; i < array.Length; i++)
- {
- this.elementInfo.WriteData(collector, elementInfo.PropertyValueFactory(array.GetValue(i)));
- }
- }
-
- collector.EndBufferedArray(bookmark, count);
- }
-
- public override object GetData(object value)
- {
- var array = (Array)value;
- var serializedArray = new object[array.Length];
- for (int i = 0; i < array.Length; i++)
- {
- serializedArray[i] = this.elementInfo.GetData(array.GetValue(i));
- }
- return serializedArray;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs
deleted file mode 100644
index 76c01c6c06..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSet.cs
+++ /dev/null
@@ -1,127 +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 Interlocked = System.Threading.Interlocked;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: A very simple lock-free add-only dictionary.
- /// Warning: this is a copy-by-value type. Copying performs a snapshot.
- /// Accessing a readonly field always makes a copy of the field, so the
- /// GetOrAdd method will not work as expected if called on a readonly field.
- /// </summary>
- /// <typeparam name="KeyType">
- /// The type of the key, used for TryGet.
- /// </typeparam>
- /// <typeparam name="ItemType">
- /// The type of the item, used for GetOrAdd.
- /// </typeparam>
- internal struct ConcurrentSet<KeyType, ItemType>
- where ItemType : ConcurrentSetItem<KeyType, ItemType>
- {
- private ItemType[] items;
-
- public ItemType TryGet(KeyType key)
- {
- ItemType item;
- var oldItems = this.items;
-
- if (oldItems != null)
- {
- var lo = 0;
- var hi = oldItems.Length;
- do
- {
- int i = (lo + hi) / 2;
- item = oldItems[i];
-
- int cmp = item.Compare(key);
- if (cmp == 0)
- {
- goto Done;
- }
- else if (cmp < 0)
- {
- lo = i + 1;
- }
- else
- {
- hi = i;
- }
- }
- while (lo != hi);
- }
-
- item = null;
-
- Done:
-
- return item;
- }
-
- public ItemType GetOrAdd(ItemType newItem)
- {
- ItemType item;
- var oldItems = this.items;
- ItemType[] newItems;
-
- Retry:
-
- if (oldItems == null)
- {
- newItems = new ItemType[] { newItem };
- }
- else
- {
- var lo = 0;
- var hi = oldItems.Length;
- do
- {
- int i = (lo + hi) / 2;
- item = oldItems[i];
-
- int cmp = item.Compare(newItem);
- if (cmp == 0)
- {
- goto Done;
- }
- else if (cmp < 0)
- {
- lo = i + 1;
- }
- else
- {
- hi = i;
- }
- }
- while (lo != hi);
-
- int oldLength = oldItems.Length;
- newItems = new ItemType[oldLength + 1];
- Array.Copy(oldItems, 0, newItems, 0, lo);
- newItems[lo] = newItem;
- Array.Copy(oldItems, lo, newItems, lo + 1, oldLength - lo);
- }
-
- newItems = Interlocked.CompareExchange(ref this.items, newItems, oldItems);
- if (oldItems != newItems)
- {
- oldItems = newItems;
- goto Retry;
- }
-
- item = newItem;
-
- Done:
-
- return item;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSetItem.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSetItem.cs
deleted file mode 100644
index 558dbf670b..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/ConcurrentSetItem.cs
+++ /dev/null
@@ -1,25 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Abstract base class that must be inherited by items in a
- /// ConcurrentSet.
- /// </summary>
- /// <typeparam name="KeyType">Type of the set's key.</typeparam>
- /// <typeparam name="ItemType">Type of the derived class.</typeparam>
- internal abstract class ConcurrentSetItem<KeyType, ItemType>
- where ItemType : ConcurrentSetItem<KeyType, ItemType>
- {
- public abstract int Compare(ItemType other);
- public abstract int Compare(KeyType key);
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
deleted file mode 100644
index 079d7f480b..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/DataCollector.cs
+++ /dev/null
@@ -1,318 +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.Runtime.InteropServices;
-using System.Security;
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: This is the implementation of the DataCollector
- /// functionality. To enable safe access to the DataCollector from
- /// untrusted code, there is one thread-local instance of this structure
- /// per thread. The instance must be Enabled before any data is written to
- /// it. The instance must be Finished before the data is passed to
- /// EventWrite. The instance must be Disabled before the arrays referenced
- /// by the pointers are freed or unpinned.
- /// </summary>
- internal unsafe struct DataCollector
- {
- [ThreadStatic]
- internal static DataCollector ThreadInstance;
-
- private byte* scratchEnd;
- private EventSource.EventData* datasEnd;
- private GCHandle* pinsEnd;
- private EventSource.EventData* datasStart;
- private byte* scratch;
- private EventSource.EventData* datas;
- private GCHandle* pins;
- private byte[] buffer;
- private int bufferPos;
- private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this.
- private bool writingScalars;
-
- internal void Enable(
- byte* scratch,
- int scratchSize,
- EventSource.EventData* datas,
- int dataCount,
- GCHandle* pins,
- int pinCount)
- {
- this.datasStart = datas;
- this.scratchEnd = scratch + scratchSize;
- this.datasEnd = datas + dataCount;
- this.pinsEnd = pins + pinCount;
- this.scratch = scratch;
- this.datas = datas;
- this.pins = pins;
- this.writingScalars = false;
- }
-
- internal void Disable()
- {
- this = new DataCollector();
- }
-
- /// <summary>
- /// Completes the list of scalars. Finish must be called before the data
- /// descriptor array is passed to EventWrite.
- /// </summary>
- /// <returns>
- /// A pointer to the next unused data descriptor, or datasEnd if they were
- /// all used. (Descriptors may be unused if a string or array was null.)
- /// </returns>
- internal EventSource.EventData* Finish()
- {
- this.ScalarsEnd();
- return this.datas;
- }
-
- internal void AddScalar(void* value, int size)
- {
- var pb = (byte*)value;
- if (this.bufferNesting == 0)
- {
- var scratchOld = this.scratch;
- var scratchNew = scratchOld + size;
- if (this.scratchEnd < scratchNew)
- {
- throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_AddScalarOutOfRange"));
- }
-
- this.ScalarsBegin();
- this.scratch = scratchNew;
-
- for (int i = 0; i != size; i++)
- {
- scratchOld[i] = pb[i];
- }
- }
- else
- {
- var oldPos = this.bufferPos;
- this.bufferPos = checked(this.bufferPos + size);
- this.EnsureBuffer();
- for (int i = 0; i != size; i++, oldPos++)
- {
- this.buffer[oldPos] = pb[i];
- }
- }
- }
-
- internal void AddBinary(string value, int size)
- {
- if (size > ushort.MaxValue)
- {
- size = ushort.MaxValue - 1;
- }
-
- if (this.bufferNesting != 0)
- {
- this.EnsureBuffer(size + 2);
- }
-
- this.AddScalar(&size, 2);
-
- if (size != 0)
- {
- if (this.bufferNesting == 0)
- {
- this.ScalarsEnd();
- this.PinArray(value, size);
- }
- else
- {
- var oldPos = this.bufferPos;
- this.bufferPos = checked(this.bufferPos + size);
- this.EnsureBuffer();
- fixed (void* p = value)
- {
- Marshal.Copy((IntPtr)p, this.buffer, oldPos, size);
- }
- }
- }
- }
-
- internal void AddBinary(Array value, int size)
- {
- this.AddArray(value, size, 1);
- }
-
- internal void AddArray(Array value, int length, int itemSize)
- {
- if (length > ushort.MaxValue)
- {
- length = ushort.MaxValue;
- }
-
- var size = length * itemSize;
- if (this.bufferNesting != 0)
- {
- this.EnsureBuffer(size + 2);
- }
-
- this.AddScalar(&length, 2);
-
- if (length != 0)
- {
- if (this.bufferNesting == 0)
- {
- this.ScalarsEnd();
- this.PinArray(value, size);
- }
- else
- {
- var oldPos = this.bufferPos;
- this.bufferPos = checked(this.bufferPos + size);
- this.EnsureBuffer();
- Buffer.BlockCopy(value, 0, this.buffer, oldPos, size);
- }
- }
- }
-
- /// <summary>
- /// Marks the start of a non-blittable array or enumerable.
- /// </summary>
- /// <returns>Bookmark to be passed to EndBufferedArray.</returns>
- internal int BeginBufferedArray()
- {
- this.BeginBuffered();
- this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable)
- return this.bufferPos;
- }
-
- /// <summary>
- /// Marks the end of a non-blittable array or enumerable.
- /// </summary>
- /// <param name="bookmark">The value returned by BeginBufferedArray.</param>
- /// <param name="count">The number of items in the array.</param>
- internal void EndBufferedArray(int bookmark, int count)
- {
- this.EnsureBuffer();
- this.buffer[bookmark - 2] = unchecked((byte)count);
- this.buffer[bookmark - 1] = unchecked((byte)(count >> 8));
- this.EndBuffered();
- }
-
- /// <summary>
- /// Marks the start of dynamically-buffered data.
- /// </summary>
- internal void BeginBuffered()
- {
- this.ScalarsEnd();
- this.bufferNesting += 1;
- }
-
- /// <summary>
- /// Marks the end of dynamically-buffered data.
- /// </summary>
- internal void EndBuffered()
- {
- this.bufferNesting -= 1;
-
- if (this.bufferNesting == 0)
- {
- /*
- TODO (perf): consider coalescing adjacent buffered regions into a
- single buffer, similar to what we're already doing for adjacent
- scalars. In addition, if a type contains a buffered region adjacent
- to a blittable array, and the blittable array is small, it would be
- more efficient to buffer the array instead of pinning it.
- */
-
- this.EnsureBuffer();
- this.PinArray(this.buffer, this.bufferPos);
- this.buffer = null;
- this.bufferPos = 0;
- }
- }
-
- private void EnsureBuffer()
- {
- var required = this.bufferPos;
- if (this.buffer == null || this.buffer.Length < required)
- {
- this.GrowBuffer(required);
- }
- }
-
- private void EnsureBuffer(int additionalSize)
- {
- var required = this.bufferPos + additionalSize;
- if (this.buffer == null || this.buffer.Length < required)
- {
- this.GrowBuffer(required);
- }
- }
-
- private void GrowBuffer(int required)
- {
- var newSize = this.buffer == null ? 64 : this.buffer.Length;
-
- do
- {
- newSize *= 2;
- }
- while (newSize < required);
-
- Array.Resize(ref this.buffer, newSize);
- }
-
- private void PinArray(object value, int size)
- {
- var pinsTemp = this.pins;
- if (this.pinsEnd <= pinsTemp)
- {
- throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_PinArrayOutOfRange"));
- }
-
- var datasTemp = this.datas;
- if (this.datasEnd <= datasTemp)
- {
- throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
- }
-
- this.pins = pinsTemp + 1;
- this.datas = datasTemp + 1;
-
- *pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned);
- datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject();
- datasTemp->m_Size = size;
- }
-
- private void ScalarsBegin()
- {
- if (!this.writingScalars)
- {
- var datasTemp = this.datas;
- if (this.datasEnd <= datasTemp)
- {
- throw new IndexOutOfRangeException(Resources.GetResourceString("EventSource_DataDescriptorsOutOfRange"));
- }
-
- datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch;
- this.writingScalars = true;
- }
- }
-
- private void ScalarsEnd()
- {
- if (this.writingScalars)
- {
- var datasTemp = this.datas;
- datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr));
- this.datas = datasTemp + 1;
- this.writingScalars = false;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EmptyStruct.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EmptyStruct.cs
deleted file mode 100644
index bc7fb8c346..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EmptyStruct.cs
+++ /dev/null
@@ -1,17 +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.
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Empty struct indicating no payload data.
- /// </summary>
- internal struct EmptyStruct
- {
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumHelper.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumHelper.cs
deleted file mode 100644
index 7a23378bb1..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumHelper.cs
+++ /dev/null
@@ -1,30 +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.
-#if EVENTSOURCE_GENERICS
-?using System;
-using System.Reflection;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Provides support for casting enums to their underlying type
- /// from within generic context.
- /// </summary>
- /// <typeparam name="UnderlyingType">
- /// The underlying type of the enum.
- /// </typeparam>
- internal static class EnumHelper<UnderlyingType>
- {
- public static UnderlyingType Cast<ValueType>(ValueType value)
- {
- return (UnderlyingType)(object)value;
- }
- }
-
-}
-#endif
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.cs
deleted file mode 100644
index 74a3fa27b2..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EnumerableTypeInfo.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.Collections;
-using System.Collections.Generic;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- internal sealed class EnumerableTypeInfo : TraceLoggingTypeInfo
- {
- private readonly TraceLoggingTypeInfo elementInfo;
-
- public EnumerableTypeInfo(Type type, TraceLoggingTypeInfo elementInfo)
- : base(type)
- {
- this.elementInfo = elementInfo;
- }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.BeginBufferedArray();
- this.elementInfo.WriteMetadata(collector, name, format);
- collector.EndBufferedArray();
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- var bookmark = collector.BeginBufferedArray();
-
- var count = 0;
- IEnumerable enumerable = (IEnumerable)value.ReferenceValue;
- if (enumerable != null)
- {
- foreach (var element in enumerable)
- {
- this.elementInfo.WriteData(collector, elementInfo.PropertyValueFactory(element));
- count++;
- }
- }
-
- collector.EndBufferedArray(bookmark, count);
- }
-
- public override object GetData(object value)
- {
- var iterType = (IEnumerable)value;
- List<object> serializedEnumerable = new List<object>();
- foreach (var element in iterType)
- {
- serializedEnumerable.Add(elementInfo.GetData(element));
- }
- return serializedEnumerable.ToArray();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs
deleted file mode 100644
index cdedf13c64..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventDataAttribute.cs
+++ /dev/null
@@ -1,146 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Used when authoring types that will be passed to EventSource.Write.
- /// EventSource.Write&lt;T> only works when T is either an anonymous type
- /// or a type with an [EventData] attribute. In addition, the properties
- /// of T must be supported property types. Supported property types include
- /// simple built-in types (int, string, Guid, DateTime, DateTimeOffset,
- /// KeyValuePair, etc.), anonymous types that only contain supported types,
- /// types with an [EventData] attribute, arrays of the above, and IEnumerable
- /// of the above.
- /// </summary>
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
- public class EventDataAttribute
- : Attribute
- {
- private EventLevel level = (EventLevel)(-1);
- private EventOpcode opcode = (EventOpcode)(-1);
-
- /// <summary>
- /// Gets or sets the name to use if this type is used for an
- /// implicitly-named event or an implicitly-named property.
- ///
- /// Example 1:
- ///
- /// EventSource.Write(null, new T()); // implicitly-named event
- ///
- /// The name of the event will be determined as follows:
- ///
- /// if (T has an EventData attribute and attribute.Name != null)
- /// eventName = attribute.Name;
- /// else
- /// eventName = typeof(T).Name;
- ///
- /// Example 2:
- ///
- /// EventSource.Write(name, new { _1 = new T() }); // implicitly-named field
- ///
- /// The name of the field will be determined as follows:
- ///
- /// if (T has an EventData attribute and attribute.Name != null)
- /// fieldName = attribute.Name;
- /// else
- /// fieldName = typeof(T).Name;
- /// </summary>
- public string Name
- {
- get;
- set;
- }
-
- /// <summary>
- /// Gets or sets the level to use for the event.
- /// Invalid levels (outside the range 0..255) are treated as unset.
- /// Note that the Level attribute can bubble-up, i.e. if a type contains
- /// a sub-object (a field or property), and the sub-object's type has a
- /// TraceLoggingEvent attribute, the Level from the sub-object's attribute
- /// can affect the event's level.
- ///
- /// Example: for EventSource.Write(name, options, data), the level of the
- /// event will be determined as follows:
- ///
- /// if (options.Level has been set)
- /// eventLevel = options.Level;
- /// else if (data.GetType() has a TraceLoggingEvent attribute and attribute.Level has been set)
- /// eventLevel = attribute.Level;
- /// else if (a field/property contained in data has a TraceLoggingEvent attribute and attribute.Level has been set)
- /// eventLevel = attribute.Level;
- /// else
- /// eventLevel = EventLevel.LogAlways;
- /// </summary>
- internal EventLevel Level
- {
- get { return this.level; }
- set { this.level = value; }
- }
-
- /// <summary>
- /// Gets or sets the opcode to use for the event.
- /// Invalid opcodes (outside the range 0..255) are treated as unset.
- /// Note that the Opcode attribute can bubble-up, i.e. if a type contains
- /// a sub-object (a field or property), and the sub-object's type has a
- /// TraceLoggingEvent attribute, the Opcode from the sub-object's attribute
- /// can affect the event's opcode.
- ///
- /// Example: for EventSource.Write(name, options, data), the opcode of the
- /// event will be determined as follows:
- ///
- /// if (options.Opcode has been set)
- /// eventOpcode = options.Opcode;
- /// else if (data.GetType() has a TraceLoggingEvent attribute and attribute.Opcode has been set)
- /// eventOpcode = attribute.Opcode;
- /// else if (a field/property contained in data has a TraceLoggingEvent attribute and attribute.Opcode has been set)
- /// eventOpcode = attribute.Opcode;
- /// else
- /// eventOpcode = EventOpcode.Info;
- /// </summary>
- internal EventOpcode Opcode
- {
- get { return this.opcode; }
- set { this.opcode = value; }
- }
-
- /// <summary>
- /// Gets or sets the keywords to use for the event.
- /// Note that the Keywords attribute can bubble-up, i.e. if a type contains
- /// a sub-object (a field or property), and the sub-object's type has a
- /// TraceLoggingEvent attribute, the Keywords from the sub-object's attribute
- /// can affect the event's keywords.
- ///
- /// Example: for EventSource.Write(name, options, data), the keywords of the
- /// event will be determined as follows:
- ///
- /// eventKeywords = options.Keywords;
- /// if (data.GetType() has a TraceLoggingEvent attribute)
- /// eventKeywords |= attribute.Keywords;
- /// if (a field/property contained in data has a TraceLoggingEvent attribute)
- /// eventKeywords |= attribute.Keywords;
- /// </summary>
- internal EventKeywords Keywords
- {
- get;
- set;
- }
-
- /// <summary>
- /// Gets or sets the flags for an event. These flags are ignored by ETW,
- /// but can have meaning to the event consumer.
- /// </summary>
- internal EventTags Tags
- {
- get;
- set;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldAttribute.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldAttribute.cs
deleted file mode 100644
index 1a298c2851..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldAttribute.cs
+++ /dev/null
@@ -1,76 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Tags are flags that are not interpreted by EventSource but are passed along
- /// to the EventListener. The EventListener determines the semantics of the flags.
- /// </summary>
- [Flags]
- public enum EventFieldTags
- {
- /// <summary>
- /// No special traits are added to the field.
- /// </summary>
- None = 0,
-
- /* Bits below 0x10000 are available for any use by the provider. */
- /* Bits at or above 0x10000 are reserved for definition by Microsoft. */
- }
-
- /// <summary>
- /// TraceLogging: used when authoring types that will be passed to EventSource.Write.
- /// Controls how a field or property is handled when it is written as a
- /// field in a TraceLogging event. Apply this attribute to a field or
- /// property if the default handling is not correct. (Apply the
- /// TraceLoggingIgnore attribute if the property should not be
- /// included as a field in the event.)
- /// The default for Name is null, which means that the name of the
- /// underlying field or property will be used as the event field's name.
- /// The default for PiiTag is 0, which means that the event field does not
- /// contain personally-identifiable information.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property)]
- public class EventFieldAttribute
- : Attribute
- {
- /// <summary>
- /// User defined options for the field. These are not interpreted by the EventSource
- /// but are available to the Listener. See EventFieldSettings for details
- /// </summary>
- public EventFieldTags Tags
- {
- get;
- set;
- }
-
- /// <summary>
- /// Gets or sets the name to use for the field. This defaults to null.
- /// If null, the name of the corresponding property will be used
- /// as the event field's name.
- /// TODO REMOVE
- /// </summary>
- internal string Name
- {
- get;
- set;
- }
-
- /// <summary>
- /// Gets or sets a field formatting hint.
- /// </summary>
- public EventFieldFormat Format
- {
- get;
- set;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldFormat.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldFormat.cs
deleted file mode 100644
index fd77b07965..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventFieldFormat.cs
+++ /dev/null
@@ -1,130 +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.
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Provides a hint that may be used by an event listener when formatting
- /// an event field for display. Note that the event listener may ignore the
- /// hint if it does not recognize a particular combination of type and format.
- /// Similar to TDH_OUTTYPE.
- /// </summary>
- public enum EventFieldFormat
- {
- /// <summary>
- /// Field receives default formatting based on the field's underlying type.
- /// </summary>
- Default = 0,
-#if false
- /// <summary>
- /// Field should not be displayed.
- /// </summary>
- NoPrint = 1,
-#endif
- /// <summary>
- /// Field should be formatted as character or string data.
- /// Typically applied to 8-bit or 16-bit integers.
- /// This is the default format for String and Char types.
- /// </summary>
- String = 2,
-
- /// <summary>
- /// Field should be formatted as boolean data. Typically applied to 8-bit
- /// or 32-bit integers. This is the default format for the Boolean type.
- /// </summary>
- Boolean = 3,
-
- /// <summary>
- /// Field should be formatted as hexadecimal data. Typically applied to
- /// integer types.
- /// </summary>
- Hexadecimal = 4,
-
-#if false
- /// <summary>
- /// Field should be formatted as a process identifier. Typically applied to
- /// 32-bit integer types.
- /// </summary>
- ProcessId = 5,
-
- /// <summary>
- /// Field should be formatted as a thread identifier. Typically applied to
- /// 32-bit integer types.
- /// </summary>
- ThreadId = 6,
-
- /// <summary>
- /// Field should be formatted as an Internet port. Typically applied to 16-bit integer
- /// types.
- /// </summary>
- Port = 7,
- /// <summary>
- /// Field should be formatted as an Internet Protocol v4 address. Typically applied to
- /// 32-bit integer types.
- /// </summary>
- Ipv4Address = 8,
-
- /// <summary>
- /// Field should be formatted as an Internet Protocol v6 address. Typically applied to
- /// byte[] types.
- /// </summary>
- Ipv6Address = 9,
- /// <summary>
- /// Field should be formatted as a SOCKADDR. Typically applied to byte[] types.
- /// </summary>
- SocketAddress = 10,
-#endif
- /// <summary>
- /// Field should be formatted as XML string data. Typically applied to
- /// strings or arrays of 8-bit or 16-bit integers.
- /// </summary>
- Xml = 11,
-
- /// <summary>
- /// Field should be formatted as JSON string data. Typically applied to
- /// strings or arrays of 8-bit or 16-bit integers.
- /// </summary>
- Json = 12,
-#if false
- /// <summary>
- /// Field should be formatted as a Win32 error code. Typically applied to
- /// 32-bit integer types.
- /// </summary>
- Win32Error = 13,
-
- /// <summary>
- /// Field should be formatted as an NTSTATUS code. Typically applied to
- /// 32-bit integer types.
- /// </summary>
- NTStatus = 14,
-#endif
- /// <summary>
- /// Field should be formatted as an HRESULT code. Typically applied to
- /// 32-bit integer types.
- /// </summary>
- HResult = 15,
-#if false
- /// <summary>
- /// Field should be formatted as a FILETIME. Typically applied to 64-bit
- /// integer types. This is the default format for DateTime types.
- /// </summary>
- FileTime = 16,
- /// <summary>
- /// When applied to a numeric type, indicates that the type should be formatted
- /// as a signed integer. This is the default format for signed integer types.
- /// </summary>
- Signed = 17,
-
- /// <summary>
- /// When applied to a numeric type, indicates that the type should be formatted
- /// as an unsigned integer. This is the default format for unsigned integer types.
- /// </summary>
- Unsigned = 18,
-#endif
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventIgnoreAttribute.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventIgnoreAttribute.cs
deleted file mode 100644
index 769345f78e..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventIgnoreAttribute.cs
+++ /dev/null
@@ -1,25 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Used when authoring types that will be passed to EventSource.Write.
- /// By default, EventSource.Write will write all of an object's public
- /// properties to the event payload. Apply [EventIgnore] to a public
- /// property to prevent EventSource.Write from including the property in
- /// the event.
- /// </summary>
- [AttributeUsage(AttributeTargets.Property)]
- public class EventIgnoreAttribute
- : Attribute
- {
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
deleted file mode 100644
index 5967ad6ab5..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventPayload.cs
+++ /dev/null
@@ -1,155 +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.Collections.Generic;
-using System.Collections;
-using System.Diagnostics;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// EventPayload class holds the list of parameters and their corresponding values for user defined types passed to
- /// EventSource APIs.
- /// Preserving the order of the elements as they were found inside user defined types is the most important characteristic of this class.
- /// </summary>
- internal class EventPayload : IDictionary<string, object>
- {
- internal EventPayload(List<string> payloadNames, List<object> payloadValues)
- {
- Debug.Assert(payloadNames.Count == payloadValues.Count);
-
- m_names = payloadNames;
- m_values = payloadValues;
- }
-
- public ICollection<string> Keys { get { return m_names; } }
- public ICollection<object> Values { get { return m_values; } }
-
- public object this[string key]
- {
- get
- {
- if (key == null)
- throw new System.ArgumentNullException(nameof(key));
-
- int position = 0;
- foreach(var name in m_names)
- {
- if (name == key)
- {
- return m_values[position];
- }
- position++;
- }
-
- throw new System.Collections.Generic.KeyNotFoundException();
- }
- set
- {
- throw new System.NotSupportedException();
- }
- }
-
- public void Add(string key, object value)
- {
- throw new System.NotSupportedException();
- }
-
- public void Add(KeyValuePair<string, object> payloadEntry)
- {
- throw new System.NotSupportedException();
- }
-
- public void Clear()
- {
- throw new System.NotSupportedException();
- }
-
- public bool Contains(KeyValuePair<string, object> entry)
- {
- return ContainsKey(entry.Key);
- }
-
- public bool ContainsKey(string key)
- {
- if (key == null)
- throw new System.ArgumentNullException(nameof(key));
-
- foreach (var item in m_names)
- {
- if (item == key)
- return true;
- }
- return false;
- }
-
- public int Count { get { return m_names.Count; } }
-
- public bool IsReadOnly { get { return true; } }
-
- public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
- {
- for (int i = 0; i < Keys.Count; i++)
- {
- yield return new KeyValuePair<string, object>(this.m_names[i], this.m_values[i]);
- }
- }
-
- IEnumerator IEnumerable.GetEnumerator()
- {
- var instance = this as IEnumerable<KeyValuePair<string, object>>;
- return instance.GetEnumerator();
- }
-
- public void CopyTo(KeyValuePair<string, object>[] payloadEntries, int count)
- {
- throw new System.NotSupportedException();
- }
-
- public bool Remove(string key)
- {
- throw new System.NotSupportedException();
- }
-
- public bool Remove(KeyValuePair<string, object> entry)
- {
- throw new System.NotSupportedException();
- }
-
- public bool TryGetValue(string key, out object value)
- {
- if (key == null)
- throw new System.ArgumentNullException(nameof(key));
-
- int position = 0;
- foreach (var name in m_names)
- {
- if (name == key)
- {
- value = m_values[position];
- return true;
- }
- position++;
- }
-
- value = default(object);
- return false;
- }
-
- #region private
- private List<string> m_names;
- private List<object> m_values;
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs
deleted file mode 100644
index 38c1767462..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceActivity.cs
+++ /dev/null
@@ -1,321 +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;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Provides support for EventSource activities by marking the start and
- /// end of a particular operation.
- /// </summary>
- internal sealed class EventSourceActivity
- : IDisposable
- {
- /// <summary>
- /// Initializes a new instance of the EventSourceActivity class that
- /// is attached to the specified event source. The new activity will
- /// not be attached to any related (parent) activity.
- /// The activity is created in the Initialized state.
- /// </summary>
- /// <param name="eventSource">
- /// The event source to which the activity information is written.
- /// </param>
- public EventSourceActivity(EventSource eventSource)
- {
- if (eventSource == null)
- throw new ArgumentNullException(nameof(eventSource));
- Contract.EndContractBlock();
-
- this.eventSource = eventSource;
- }
-
- /// <summary>
- /// You can make an activity out of just an EventSource.
- /// </summary>
- public static implicit operator EventSourceActivity(EventSource eventSource) { return new EventSourceActivity(eventSource); }
-
- /* Properties */
- /// <summary>
- /// Gets the event source to which this activity writes events.
- /// </summary>
- public EventSource EventSource
- {
- get { return this.eventSource; }
- }
-
- /// <summary>
- /// Gets this activity's unique identifier, or the default Guid if the
- /// event source was disabled when the activity was initialized.
- /// </summary>
- public Guid Id
- {
- get { return this.activityId; }
- }
-
-#if false // don't expose RelatedActivityId unless there is a need.
- /// <summary>
- /// Gets the unique identifier of this activity's related (parent)
- /// activity.
- /// </summary>
- public Guid RelatedId
- {
- get { return this.relatedActivityId; }
- }
-#endif
-
- /// <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
- ///
- /// 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)
- /// with this activityID. In addition the Start activity will log a 'relatedActivityID' that was the activity
- /// ID before the start event. This way event processors can form a linked list of all the activities that
- /// caused this one (directly or indirectly).
- /// </summary>
- /// <param name="eventName">
- /// The name to use for the event. It is strongly suggested that this name end in 'Start' (e.g. DownloadStart).
- /// If you do this, then the Stop() method will automatically replace the 'Start' suffix with a 'Stop' suffix.
- /// </param>
- /// <param name="options">Allow options (keywords, level) to be set for the write associated with this start
- /// These will also be used for the stop event.</param>
- /// <param name="data">The data to include in the event.</param>
- public EventSourceActivity Start<T>(string eventName, EventSourceOptions options, T data)
- {
- return this.Start(eventName, ref options, ref data);
- }
- /// <summary>
- /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords
- /// and level==Info) Data payload is empty.
- /// </summary>
- public EventSourceActivity Start(string eventName)
- {
- var options = new EventSourceOptions();
- var data = new EmptyStruct();
- return this.Start(eventName, ref options, ref data);
- }
- /// <summary>
- /// Shortcut version see Start(string eventName, EventSourceOptions options, T data). Data payload is empty.
- /// </summary>
- public EventSourceActivity Start(string eventName, EventSourceOptions options)
- {
- var data = new EmptyStruct();
- return this.Start(eventName, ref options, ref data);
- }
- /// <summary>
- /// Shortcut version see Start(string eventName, EventSourceOptions options, T data) Options is empty (no keywords
- /// and level==Info)
- /// </summary>
- public EventSourceActivity Start<T>(string eventName, T data)
- {
- var options = new EventSourceOptions();
- return this.Start(eventName, ref options, ref data);
- }
-
- /// <summary>
- /// Writes a Stop event with the specified data, and sets the activity
- /// to the Stopped state. The name is determined by the eventName used in Start.
- /// If that Start event name is suffixed with 'Start' that is removed, and regardless
- /// 'Stop' is appended to the result to form the Stop event name.
- /// May only be called when the activity is in the Started state.
- /// </summary>
- /// <param name="data">The data to include in the event.</param>
- public void Stop<T>(T data)
- {
- this.Stop(null, ref data);
- }
- /// <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
- /// 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)
- {
- var data = new EmptyStruct();
- this.Stop(eventName, ref data);
- }
- /// <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
- /// 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)
- {
- this.Stop(eventName, ref data);
- }
-
- /// <summary>
- /// Writes an event associated with this activity to the eventSource associted with this activity.
- /// May only be called when the activity is in the Started state.
- /// </summary>
- /// <param name="eventName">
- /// The name to use for the event. If null, the name is determined from
- /// data's type.
- /// </param>
- /// <param name="options">
- /// The options to use for the event.
- /// </param>
- /// <param name="data">The data to include in the event.</param>
- public void Write<T>(string eventName, EventSourceOptions options, T data)
- {
- this.Write(this.eventSource, eventName, ref options, ref data);
- }
- /// <summary>
- /// Writes an event associated with this activity.
- /// May only be called when the activity is in the Started state.
- /// </summary>
- /// <param name="eventName">
- /// The name to use for the event. If null, the name is determined from
- /// data's type.
- /// </param>
- /// <param name="data">The data to include in the event.</param>
- public void Write<T>(string eventName, T data)
- {
- var options = new EventSourceOptions();
- this.Write(this.eventSource, eventName, ref options, ref data);
- }
- /// <summary>
- /// Writes a trivial event associated with this activity.
- /// May only be called when the activity is in the Started state.
- /// </summary>
- /// <param name="eventName">
- /// The name to use for the event. Must not be null.
- /// </param>
- /// <param name="options">
- /// The options to use for the event.
- /// </param>
- public void Write(string eventName, EventSourceOptions options)
- {
- var data = new EmptyStruct();
- this.Write(this.eventSource, eventName, ref options, ref data);
- }
- /// <summary>
- /// Writes a trivial event associated with this activity.
- /// May only be called when the activity is in the Started state.
- /// </summary>
- /// <param name="eventName">
- /// The name to use for the event. Must not be null.
- /// </param>
- public void Write(string eventName)
- {
- var options = new EventSourceOptions();
- var data = new EmptyStruct();
- this.Write(this.eventSource, eventName, ref options, ref data);
- }
- /// <summary>
- /// Writes an event to a arbitrary eventSource stamped with the activity ID of this activity.
- /// </summary>
- public void Write<T>(EventSource source, string eventName, EventSourceOptions options, T data)
- {
- this.Write(source, eventName, ref options, ref data);
- }
-
- /// <summary>
- /// Releases any unmanaged resources associated with this object.
- /// If the activity is in the Started state, calls Stop().
- /// </summary>
- public void Dispose()
- {
- if (this.state == State.Started)
- {
- var data = new EmptyStruct();
- this.Stop(null, ref data);
- }
- }
-
- #region private
- private EventSourceActivity Start<T>(string eventName, ref EventSourceOptions options, ref T data)
- {
- if (this.state != State.Started)
- throw new InvalidOperationException();
-
- // If the source is not on at all, then we don't need to do anything and we can simply return ourselves.
- if (!this.eventSource.IsEnabled())
- return this;
-
- var newActivity = new EventSourceActivity(eventSource);
- if (!this.eventSource.IsEnabled(options.Level, options.Keywords))
- {
- // newActivity.relatedActivityId = this.Id;
- Guid relatedActivityId = this.Id;
- newActivity.activityId = Guid.NewGuid();
- newActivity.startStopOptions = options;
- newActivity.eventName = eventName;
- newActivity.startStopOptions.Opcode = EventOpcode.Start;
- this.eventSource.Write(eventName, ref newActivity.startStopOptions, ref newActivity.activityId, ref relatedActivityId, ref data);
- }
- else
- {
- // If we are not active, we don't set the eventName, which basically also turns off the Stop event as well.
- newActivity.activityId = this.Id;
- }
-
- return newActivity;
- }
-
- private void Write<T>(EventSource eventSource, string eventName, ref EventSourceOptions options, ref T data)
- {
- if (this.state != State.Started)
- throw new InvalidOperationException(); // Write after stop.
- if (eventName == null)
- throw new ArgumentNullException();
-
- eventSource.Write(eventName, ref options, ref this.activityId, ref s_empty, ref data);
- }
-
- private void Stop<T>(string eventName, ref T data)
- {
- if (this.state != State.Started)
- throw new InvalidOperationException();
-
- // If start was not fired, then stop isn't as well.
- if (!StartEventWasFired)
- return;
-
- this.state = State.Stopped;
- if (eventName == null)
- {
- eventName = this.eventName;
- if (eventName.EndsWith("Start"))
- eventName = eventName.Substring(0, eventName.Length - 5);
- eventName = eventName + "Stop";
- }
- this.startStopOptions.Opcode = EventOpcode.Stop;
- this.eventSource.Write(eventName, ref this.startStopOptions, ref this.activityId, ref s_empty, ref data);
- }
-
- private enum State
- {
- Started,
- Stopped
- }
-
- /// <summary>
- /// If eventName is non-null then we logged a start event
- /// </summary>
- private bool StartEventWasFired { get { return eventName != null; } }
-
- private readonly EventSource eventSource;
- private EventSourceOptions startStopOptions;
- internal Guid activityId;
- // internal Guid relatedActivityId;
- private State state;
- private string eventName;
-
- static internal Guid s_empty;
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceOptions.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceOptions.cs
deleted file mode 100644
index 26305a5708..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/EventSourceOptions.cs
+++ /dev/null
@@ -1,130 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Used when calling EventSource.Write.
- /// Optional overrides for event settings such as Level, Keywords, or Opcode.
- /// If overrides are not provided for a setting, default values will be used.
- /// </summary>
- public struct EventSourceOptions
- {
- internal EventKeywords keywords;
- internal EventTags tags;
- internal EventActivityOptions activityOptions;
- internal byte level;
- internal byte opcode;
- internal byte valuesSet;
-
- internal const byte keywordsSet = 0x1;
- internal const byte tagsSet = 0x2;
- internal const byte levelSet = 0x4;
- internal const byte opcodeSet = 0x8;
- internal const byte activityOptionsSet = 0x10;
-
- /// <summary>
- /// Gets or sets the level to use for the specified event. If this property
- /// is unset, the event's level will be 5 (Verbose).
- /// </summary>
- public EventLevel Level
- {
- get
- {
- return (EventLevel)this.level;
- }
-
- set
- {
- this.level = checked((byte)value);
- this.valuesSet |= levelSet;
- }
- }
-
- /// <summary>
- /// Gets or sets the opcode to use for the specified event. If this property
- /// is unset, the event's opcode will 0 (Info).
- /// </summary>
- public EventOpcode Opcode
- {
- get
- {
- return (EventOpcode)this.opcode;
- }
-
- set
- {
- this.opcode = checked((byte)value);
- this.valuesSet |= opcodeSet;
- }
- }
-
- internal bool IsOpcodeSet
- {
- get
- {
- return (this.valuesSet & opcodeSet) != 0;
- }
- }
-
- /// <summary>
- /// Gets or sets the keywords to use for the specified event. If this
- /// property is unset, the event's keywords will be 0.
- /// </summary>
- public EventKeywords Keywords
- {
- get
- {
- return this.keywords;
- }
-
- set
- {
- this.keywords = value;
- this.valuesSet |= keywordsSet;
- }
- }
-
- /// <summary>
- /// Gets or sets the tags to use for the specified event. If this property is
- /// unset, the event's tags will be 0.
- /// </summary>
- public EventTags Tags
- {
- get
- {
- return this.tags;
- }
-
- set
- {
- this.tags = value;
- this.valuesSet |= tagsSet;
- }
- }
-
- /// <summary>
- /// Gets or sets the activity options for this specified events. If this property is
- /// unset, the event's activity options will be 0.
- /// </summary>
- public EventActivityOptions ActivityOptions
- {
- get
- {
- return this.activityOptions;
- }
- set
- {
- this.activityOptions = value;
- this.valuesSet |= activityOptionsSet;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
deleted file mode 100644
index 309226b84d..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/FieldMetadata.cs
+++ /dev/null
@@ -1,231 +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 Encoding = System.Text.Encoding;
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Contains the information needed to generate tracelogging
- /// metadata for an event field.
- /// </summary>
- internal class FieldMetadata
- {
- /// <summary>
- /// Name of the field
- /// </summary>
- private readonly string name;
-
- /// <summary>
- /// The number of bytes in the UTF8 Encoding of 'name' INCLUDING a null terminator.
- /// </summary>
- private readonly int nameSize;
- private readonly EventFieldTags tags;
- private readonly byte[] custom;
-
- /// <summary>
- /// ETW supports fixed sized arrays. If inType has the InTypeFixedCountFlag then this is the
- /// statically known count for the array. It is also used to encode the number of bytes of
- /// custom meta-data if InTypeCustomCountFlag set.
- /// </summary>
- private readonly ushort fixedCount;
-
- private byte inType;
- private byte outType;
-
- /// <summary>
- /// Scalar or variable-length array.
- /// </summary>
- public FieldMetadata(
- string name,
- TraceLoggingDataType type,
- EventFieldTags tags,
- bool variableCount)
- : this(
- name,
- type,
- tags,
- variableCount ? Statics.InTypeVariableCountFlag : (byte)0,
- 0,
- null)
- {
- return;
- }
-
- /// <summary>
- /// Fixed-length array.
- /// </summary>
- public FieldMetadata(
- string name,
- TraceLoggingDataType type,
- EventFieldTags tags,
- ushort fixedCount)
- : this(
- name,
- type,
- tags,
- Statics.InTypeFixedCountFlag,
- fixedCount,
- null)
- {
- return;
- }
-
- /// <summary>
- /// Custom serializer
- /// </summary>
- public FieldMetadata(
- string name,
- TraceLoggingDataType type,
- EventFieldTags tags,
- byte[] custom)
- : this(
- name,
- type,
- tags,
- Statics.InTypeCustomCountFlag,
- checked((ushort)(custom == null ? 0 : custom.Length)),
- custom)
- {
- return;
- }
-
- private FieldMetadata(
- string name,
- TraceLoggingDataType dataType,
- EventFieldTags tags,
- byte countFlags,
- ushort fixedCount = 0,
- byte[] custom = null)
- {
- if (name == null)
- {
- throw new ArgumentNullException(
- nameof(name),
- "This usually means that the object passed to Write is of a type that"
- + " does not support being used as the top-level object in an event,"
- + " e.g. a primitive or built-in type.");
- }
-
- Statics.CheckName(name);
- var coreType = (int)dataType & Statics.InTypeMask;
- this.name = name;
- this.nameSize = Encoding.UTF8.GetByteCount(this.name) + 1;
- this.inType = (byte)(coreType | countFlags);
- this.outType = (byte)(((int)dataType >> 8) & Statics.OutTypeMask);
- this.tags = tags;
- this.fixedCount = fixedCount;
- this.custom = custom;
-
- if (countFlags != 0)
- {
- if (coreType == (int)TraceLoggingDataType.Nil)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedArrayOfNil"));
- }
- if (coreType == (int)TraceLoggingDataType.Binary)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedArrayOfBinary"));
- }
-#if !BROKEN_UNTIL_M3
- if (coreType == (int)TraceLoggingDataType.Utf16String ||
- coreType == (int)TraceLoggingDataType.MbcsString)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedArrayOfNullTerminatedString"));
- }
-#endif
- }
-
- if (((int)this.tags & 0xfffffff) != 0)
- {
- this.outType |= Statics.OutTypeChainFlag;
- }
-
- if (this.outType != 0)
- {
- this.inType |= Statics.InTypeChainFlag;
- }
- }
-
- public void IncrementStructFieldCount()
- {
- this.inType |= Statics.InTypeChainFlag;
- this.outType++;
- if ((this.outType & Statics.OutTypeMask) == 0)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_TooManyFields"));
- }
- }
-
- /// <summary>
- /// This is the main routine for FieldMetaData. Basically it will serialize the data in
- /// this structure as TraceLogging style meta-data into the array 'metaArray' starting at
- /// 'pos' (pos is updated to reflect the bytes written).
- ///
- /// Note that 'metaData' can be null, in which case it only updates 'pos'. This is useful
- /// for a 'two pass' approach where you figure out how big to make the array, and then you
- /// fill it in.
- /// </summary>
- public void Encode(ref int pos, byte[] metadata)
- {
- // Write out the null terminated UTF8 encoded name
- if (metadata != null)
- {
- Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos);
- }
- pos += this.nameSize;
-
- // Write 1 byte for inType
- if (metadata != null)
- {
- metadata[pos] = this.inType;
- }
- pos += 1;
-
- // If InTypeChainFlag set, then write out the outType
- if (0 != (this.inType & Statics.InTypeChainFlag))
- {
- if (metadata != null)
- {
- metadata[pos] = this.outType;
- }
- pos += 1;
-
- // If OutTypeChainFlag set, then write out tags
- if (0 != (this.outType & Statics.OutTypeChainFlag))
- {
- Statics.EncodeTags((int)this.tags, ref pos, metadata);
- }
- }
-
- // If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian)
- if (0 != (this.inType & Statics.InTypeFixedCountFlag))
- {
- if (metadata != null)
- {
- metadata[pos + 0] = unchecked((byte)this.fixedCount);
- metadata[pos + 1] = (byte)(this.fixedCount >> 8);
- }
- pos += 2;
-
- // If InTypeCustomCountFlag set, write out the blob of custom meta-data.
- if (Statics.InTypeCustomCountFlag == (this.inType & Statics.InTypeCountMask) &&
- this.fixedCount != 0)
- {
- if (metadata != null)
- {
- Buffer.BlockCopy(this.custom, 0, metadata, pos, this.fixedCount);
- }
- pos += this.fixedCount;
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs
deleted file mode 100644
index 3e5997bc9b..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/InvokeTypeInfo.cs
+++ /dev/null
@@ -1,96 +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.Collections.Generic;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: An implementation of TraceLoggingTypeInfo that works
- /// for arbitrary types. It writes all public instance properties of
- /// the type.
- /// </summary>
- /// <typeparam name="ContainerType">
- /// Type from which to read values.
- /// </typeparam>
- internal sealed class InvokeTypeInfo : TraceLoggingTypeInfo
- {
- private readonly PropertyAnalysis[] properties;
-
- public InvokeTypeInfo(
- Type type,
- TypeAnalysis typeAnalysis)
- : base(
- type,
- typeAnalysis.name,
- typeAnalysis.level,
- typeAnalysis.opcode,
- typeAnalysis.keywords,
- typeAnalysis.tags)
- {
- if (typeAnalysis.properties.Length != 0)
- this.properties = typeAnalysis.properties;
- }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- var groupCollector = collector.AddGroup(name);
- if (this.properties != null)
- {
- foreach (var property in this.properties)
- {
- var propertyFormat = EventFieldFormat.Default;
- var propertyAttribute = property.fieldAttribute;
- if (propertyAttribute != null)
- {
- groupCollector.Tags = propertyAttribute.Tags;
- propertyFormat = propertyAttribute.Format;
- }
-
- property.typeInfo.WriteMetadata(
- groupCollector,
- property.name,
- propertyFormat);
- }
- }
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- if (this.properties != null)
- {
- foreach (var property in this.properties)
- {
- property.typeInfo.WriteData(collector, property.getter(value));
- }
- }
- }
-
- public override object GetData(object value)
- {
- if (this.properties != null)
- {
- var membersNames = new List<string>();
- var memebersValues = new List<object>();
- for (int i = 0; i < this.properties.Length; i++)
- {
- var propertyValue = properties[i].propertyInfo.GetValue(value);
- membersNames.Add(properties[i].name);
- memebersValues.Add(properties[i].typeInfo.GetData(propertyValue));
- }
- return new EventPayload(membersNames, memebersValues);
- }
-
- return null;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs
deleted file mode 100644
index 668043ae68..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/NameInfo.cs
+++ /dev/null
@@ -1,79 +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.Collections.Generic;
-using Interlocked = System.Threading.Interlocked;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Stores the metadata and event identifier corresponding
- /// to a tracelogging event type+name+tags combination.
- /// </summary>
- internal sealed class NameInfo
- : ConcurrentSetItem<KeyValuePair<string, EventTags>, NameInfo>
- {
- /// <summary>
- /// Insure that eventIds strictly less than 'eventId' will not be
- /// used by the SelfDescribing events.
- /// </summary>
- internal static void ReserveEventIDsBelow(int eventId)
- {
- for(;;)
- {
- int snapshot = lastIdentity;
- int newIdentity = (lastIdentity & ~0xFFFFFF) + eventId;
- newIdentity = Math.Max(newIdentity, snapshot); // Should be redundant. as we only create descriptors once.
- if (Interlocked.CompareExchange(ref lastIdentity, newIdentity, snapshot) == snapshot)
- break;
- }
- }
-
- private static int lastIdentity = Statics.TraceLoggingChannel << 24;
- internal readonly string name;
- internal readonly EventTags tags;
- internal readonly int identity;
- internal readonly byte[] nameMetadata;
-
- public NameInfo(string name, EventTags tags, int typeMetadataSize)
- {
- this.name = name;
- this.tags = tags & Statics.EventTagsMask;
- this.identity = Interlocked.Increment(ref lastIdentity);
-
- int tagsPos = 0;
- Statics.EncodeTags((int)this.tags, ref tagsPos, null);
-
- this.nameMetadata = Statics.MetadataForString(name, tagsPos, 0, typeMetadataSize);
-
- tagsPos = 2;
- Statics.EncodeTags((int)this.tags, ref tagsPos, this.nameMetadata);
- }
-
- public override int Compare(NameInfo other)
- {
- return this.Compare(other.name, other.tags);
- }
-
- public override int Compare(KeyValuePair<string, EventTags> key)
- {
- return this.Compare(key.Key, key.Value & Statics.EventTagsMask);
- }
-
- private int Compare(string otherName, EventTags otherTags)
- {
- int result = StringComparer.Ordinal.Compare(this.name, otherName);
- if (result == 0 && this.tags != otherTags)
- {
- result = this.tags < otherTags ? -1 : 1;
- }
- return result;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyAnalysis.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyAnalysis.cs
deleted file mode 100644
index 1f07539b52..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyAnalysis.cs
+++ /dev/null
@@ -1,39 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: stores the per-property information obtained by
- /// reflecting over a type.
- /// </summary>
- internal sealed class PropertyAnalysis
- {
- internal readonly string name;
- internal readonly PropertyInfo propertyInfo;
- internal readonly Func<PropertyValue, PropertyValue> getter;
- internal readonly TraceLoggingTypeInfo typeInfo;
- internal readonly EventFieldAttribute fieldAttribute;
-
- public PropertyAnalysis(
- string name,
- PropertyInfo propertyInfo,
- TraceLoggingTypeInfo typeInfo,
- EventFieldAttribute fieldAttribute)
- {
- this.name = name;
- this.propertyInfo = propertyInfo;
- this.getter = PropertyValue.GetPropertyGetter(propertyInfo);
- this.typeInfo = typeInfo;
- this.fieldAttribute = fieldAttribute;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
deleted file mode 100644
index 3ea781252f..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/PropertyValue.cs
+++ /dev/null
@@ -1,252 +0,0 @@
-using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Diagnostics;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-namespace System.Diagnostics.Tracing
-{
- /// <summary>
- /// Holds property values of any type. For common value types, we have inline storage so that we don't need
- /// to box the values. For all other types, we store the value in a single object reference field.
- ///
- /// To get the value of a property quickly, use a delegate produced by <see cref="PropertyValue.GetPropertyGetter(PropertyInfo)"/>.
- /// </summary>
- internal unsafe struct PropertyValue
- {
- /// <summary>
- /// Union of well-known value types, to avoid boxing those types.
- /// </summary>
- [StructLayout(LayoutKind.Explicit)]
- public struct Scalar
- {
- [FieldOffset(0)]
- public Boolean AsBoolean;
- [FieldOffset(0)]
- public Byte AsByte;
- [FieldOffset(0)]
- public SByte AsSByte;
- [FieldOffset(0)]
- public Char AsChar;
- [FieldOffset(0)]
- public Int16 AsInt16;
- [FieldOffset(0)]
- public UInt16 AsUInt16;
- [FieldOffset(0)]
- public Int32 AsInt32;
- [FieldOffset(0)]
- public UInt32 AsUInt32;
- [FieldOffset(0)]
- public Int64 AsInt64;
- [FieldOffset(0)]
- public UInt64 AsUInt64;
- [FieldOffset(0)]
- public IntPtr AsIntPtr;
- [FieldOffset(0)]
- public UIntPtr AsUIntPtr;
- [FieldOffset(0)]
- public Single AsSingle;
- [FieldOffset(0)]
- public Double AsDouble;
- [FieldOffset(0)]
- public Guid AsGuid;
- [FieldOffset(0)]
- public DateTime AsDateTime;
- [FieldOffset(0)]
- public DateTimeOffset AsDateTimeOffset;
- [FieldOffset(0)]
- public TimeSpan AsTimeSpan;
- [FieldOffset(0)]
- public Decimal AsDecimal;
- }
-
- // Anything not covered by the Scalar union gets stored in this reference.
- readonly object _reference;
- readonly Scalar _scalar;
- readonly int _scalarLength;
-
- private PropertyValue(object value)
- {
- _reference = value;
- _scalar = default(Scalar);
- _scalarLength = 0;
- }
-
- private PropertyValue(Scalar scalar, int scalarLength)
- {
- _reference = null;
- _scalar = scalar;
- _scalarLength = scalarLength;
- }
-
- private PropertyValue(Boolean value) : this(new Scalar() { AsBoolean = value }, sizeof(Boolean)) { }
- private PropertyValue(Byte value) : this(new Scalar() { AsByte = value }, sizeof(Byte)) { }
- private PropertyValue(SByte value) : this(new Scalar() { AsSByte = value }, sizeof(SByte)) { }
- private PropertyValue(Char value) : this(new Scalar() { AsChar = value }, sizeof(Char)) { }
- private PropertyValue(Int16 value) : this(new Scalar() { AsInt16 = value }, sizeof(Int16)) { }
- private PropertyValue(UInt16 value) : this(new Scalar() { AsUInt16 = value }, sizeof(UInt16)) { }
- private PropertyValue(Int32 value) : this(new Scalar() { AsInt32 = value }, sizeof(Int32)) { }
- private PropertyValue(UInt32 value) : this(new Scalar() { AsUInt32 = value }, sizeof(UInt32)) { }
- private PropertyValue(Int64 value) : this(new Scalar() { AsInt64 = value }, sizeof(Int64)) { }
- private PropertyValue(UInt64 value) : this(new Scalar() { AsUInt64 = value }, sizeof(UInt64)) { }
- private PropertyValue(IntPtr value) : this(new Scalar() { AsIntPtr = value }, sizeof(IntPtr)) { }
- private PropertyValue(UIntPtr value) : this(new Scalar() { AsUIntPtr = value }, sizeof(UIntPtr)) { }
- private PropertyValue(Single value) : this(new Scalar() { AsSingle = value }, sizeof(Single)) { }
- private PropertyValue(Double value) : this(new Scalar() { AsDouble = value }, sizeof(Double)) { }
- private PropertyValue(Guid value) : this(new Scalar() { AsGuid = value }, sizeof(Guid)) { }
- private PropertyValue(DateTime value) : this(new Scalar() { AsDateTime = value }, sizeof(DateTime)) { }
- private PropertyValue(DateTimeOffset value) : this(new Scalar() { AsDateTimeOffset = value }, sizeof(DateTimeOffset)) { }
- private PropertyValue(TimeSpan value) : this(new Scalar() { AsTimeSpan = value }, sizeof(TimeSpan)) { }
- private PropertyValue(Decimal value) : this(new Scalar() { AsDecimal = value }, sizeof(Decimal)) { }
-
- public static Func<object, PropertyValue> GetFactory(Type type)
- {
- if (type == typeof(Boolean)) return value => new PropertyValue((Boolean)value);
- if (type == typeof(Byte)) return value => new PropertyValue((Byte)value);
- if (type == typeof(SByte)) return value => new PropertyValue((SByte)value);
- if (type == typeof(Char)) return value => new PropertyValue((Char)value);
- if (type == typeof(Int16)) return value => new PropertyValue((Int16)value);
- if (type == typeof(UInt16)) return value => new PropertyValue((UInt16)value);
- if (type == typeof(Int32)) return value => new PropertyValue((Int32)value);
- if (type == typeof(UInt32)) return value => new PropertyValue((UInt32)value);
- if (type == typeof(Int64)) return value => new PropertyValue((Int64)value);
- if (type == typeof(UInt64)) return value => new PropertyValue((UInt64)value);
- if (type == typeof(IntPtr)) return value => new PropertyValue((IntPtr)value);
- if (type == typeof(UIntPtr)) return value => new PropertyValue((UIntPtr)value);
- if (type == typeof(Single)) return value => new PropertyValue((Single)value);
- if (type == typeof(Double)) return value => new PropertyValue((Double)value);
- if (type == typeof(Guid)) return value => new PropertyValue((Guid)value);
- if (type == typeof(DateTime)) return value => new PropertyValue((DateTime)value);
- if (type == typeof(DateTimeOffset)) return value => new PropertyValue((DateTimeOffset)value);
- if (type == typeof(TimeSpan)) return value => new PropertyValue((TimeSpan)value);
- if (type == typeof(Decimal)) return value => new PropertyValue((Decimal)value);
-
- return value => new PropertyValue(value);
- }
-
-
- public object ReferenceValue
- {
- get
- {
- Debug.Assert(_scalarLength == 0, "This ReflectedValue refers to an unboxed value type, not a reference type or boxed value type.");
- return _reference;
- }
- }
-
- public Scalar ScalarValue
- {
- get
- {
- Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
- return _scalar;
- }
- }
-
- public int ScalarLength
- {
- get
- {
- Debug.Assert(_scalarLength > 0, "This ReflectedValue refers to a reference type or boxed value type, not an unboxed value type");
- return _scalarLength;
- }
- }
-
- /// <summary>
- /// Gets a delegate that gets the value of a given property.
- /// </summary>
- public static Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property)
- {
- if (property.DeclaringType.GetTypeInfo().IsValueType)
- return GetBoxedValueTypePropertyGetter(property);
- else
- return GetReferenceTypePropertyGetter(property);
- }
-
- /// <summary>
- /// Gets a delegate that gets the value of a property of a value type. We unfortunately cannot avoid boxing the value type,
- /// without making this generic over the value type. That would result in a large number of generic instantiations, and furthermore
- /// does not work correctly on .Net Native (we cannot express the needed instantiations in an rd.xml file). We expect that user-defined
- /// value types will be rare, and in any case the boxing only happens for events that are actually enabled.
- /// </summary>
- private static Func<PropertyValue, PropertyValue> GetBoxedValueTypePropertyGetter(PropertyInfo property)
- {
- var type = property.PropertyType;
-
- if (type.GetTypeInfo().IsEnum)
- type = Enum.GetUnderlyingType(type);
-
- var factory = GetFactory(type);
-
- return container => factory(property.GetValue(container.ReferenceValue));
- }
-
- /// <summary>
- /// For properties of reference types, we use a generic helper class to get the value. This enables us to use MethodInfo.CreateDelegate
- /// to build a fast getter. We can get away with this on .Net Native, because we really only need one runtime instantiation of the
- /// generic type, since it's only instantiated over reference types (and thus all instances are shared).
- /// </summary>
- /// <param name="property"></param>
- /// <returns></returns>
- private static Func<PropertyValue, PropertyValue> GetReferenceTypePropertyGetter(PropertyInfo property)
- {
- var helper = (TypeHelper)Activator.CreateInstance(typeof(ReferenceTypeHelper<>).MakeGenericType(property.DeclaringType));
- return helper.GetPropertyGetter(property);
- }
-
- private abstract class TypeHelper
- {
- public abstract Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property);
-
- protected Delegate GetGetMethod(PropertyInfo property, Type propertyType)
- {
- return property.GetMethod.CreateDelegate(typeof(Func<,>).MakeGenericType(property.DeclaringType, propertyType));
- }
- }
-
- private sealed class ReferenceTypeHelper<TContainer> : TypeHelper where TContainer : class
- {
- public override Func<PropertyValue, PropertyValue> GetPropertyGetter(PropertyInfo property)
- {
- var type = property.PropertyType;
-
- if (!Statics.IsValueType(type))
- {
- var getter = (Func<TContainer, object>)GetGetMethod(property, type);
- return container => new PropertyValue(getter((TContainer)container.ReferenceValue));
- }
- else
- {
- if (type.GetTypeInfo().IsEnum)
- type = Enum.GetUnderlyingType(type);
-
- if (type == typeof(Boolean)) { var f = (Func<TContainer, Boolean>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Byte)) { var f = (Func<TContainer, Byte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(SByte)) { var f = (Func<TContainer, SByte>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Char)) { var f = (Func<TContainer, Char>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Int16)) { var f = (Func<TContainer, Int16>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(UInt16)) { var f = (Func<TContainer, UInt16>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Int32)) { var f = (Func<TContainer, Int32>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(UInt32)) { var f = (Func<TContainer, UInt32>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Int64)) { var f = (Func<TContainer, Int64>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(UInt64)) { var f = (Func<TContainer, UInt64>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(IntPtr)) { var f = (Func<TContainer, IntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(UIntPtr)) { var f = (Func<TContainer, UIntPtr>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Single)) { var f = (Func<TContainer, Single>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Double)) { var f = (Func<TContainer, Double>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Guid)) { var f = (Func<TContainer, Guid>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(DateTime)) { var f = (Func<TContainer, DateTime>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(DateTimeOffset)) { var f = (Func<TContainer, DateTimeOffset>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(TimeSpan)) { var f = (Func<TContainer, TimeSpan>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
- if (type == typeof(Decimal)) { var f = (Func<TContainer, Decimal>)GetGetMethod(property, type); return container => new PropertyValue(f((TContainer)container.ReferenceValue)); }
-
- return container => new PropertyValue(property.GetValue(container.ReferenceValue));
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleEventTypes.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleEventTypes.cs
deleted file mode 100644
index cdced968f0..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleEventTypes.cs
+++ /dev/null
@@ -1,39 +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 Interlocked = System.Threading.Interlocked;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Contains the metadata needed to emit an event, optimized
- /// for events with one top-level compile-time-typed payload object.
- /// </summary>
- /// <typeparam name="T">
- /// Type of the top-level payload object. Should be EmptyStruct if the
- /// event has no payload.
- /// </typeparam>
- internal static class SimpleEventTypes<T>
- {
- private static TraceLoggingEventTypes instance;
-
- public static TraceLoggingEventTypes Instance
- {
- get { return instance ?? InitInstance(); }
- }
-
- private static TraceLoggingEventTypes InitInstance()
- {
- var info = TraceLoggingTypeInfo.GetInstance(typeof(T), null);
- var newInstance = new TraceLoggingEventTypes(info.Name, info.Tags, new TraceLoggingTypeInfo[] { info });
- Interlocked.CompareExchange(ref instance, newInstance, null);
- return instance;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
deleted file mode 100644
index 901a0ed1a2..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/SimpleTypeInfos.cs
+++ /dev/null
@@ -1,297 +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.Collections.Generic;
-using System.Reflection;
-using System.Diagnostics;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Type handler for empty or unsupported types.
- /// </summary>
- internal sealed class NullTypeInfo : TraceLoggingTypeInfo
- {
- public NullTypeInfo() : base(typeof(EmptyStruct)) { }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.AddGroup(name);
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- return;
- }
-
- public override object GetData(object value)
- {
- return null;
- }
- }
-
- /// <summary>
- /// Type handler for simple scalar types.
- /// </summary>
- sealed class ScalarTypeInfo : TraceLoggingTypeInfo
- {
- Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
- TraceLoggingDataType nativeFormat;
-
- private ScalarTypeInfo(
- Type type,
- Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc,
- TraceLoggingDataType nativeFormat)
- : base(type)
- {
- this.formatFunc = formatFunc;
- this.nativeFormat = nativeFormat;
- }
-
- public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
- {
- collector.AddScalar(name, formatFunc(format, nativeFormat));
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- collector.AddScalar(value);
- }
-
- public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); }
- public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); }
- public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); }
- public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); }
- public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); }
- public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); }
- public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); }
- public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); }
- public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); }
- public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); }
- public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); }
- public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); }
- public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); }
- public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); }
- public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); }
- }
-
-
- /// <summary>
- /// Type handler for arrays of scalars
- /// </summary>
- internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo
- {
- Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
- TraceLoggingDataType nativeFormat;
- int elementSize;
-
- private ScalarArrayTypeInfo(
- Type type,
- Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc,
- TraceLoggingDataType nativeFormat,
- int elementSize)
- : base(type)
- {
- this.formatFunc = formatFunc;
- this.nativeFormat = nativeFormat;
- this.elementSize = elementSize;
- }
-
- public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
- {
- collector.AddArray(name, formatFunc(format, nativeFormat));
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- collector.AddArray(value, elementSize);
- }
-
- public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); }
- public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); }
- public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); }
- public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); }
- public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); }
- public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); }
- public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); }
- public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); }
- public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); }
- public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); }
- public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); }
- public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); }
- public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); }
- public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); }
- public unsafe static TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); }
- }
-
- /// <summary>
- /// TraceLogging: Type handler for String.
- /// </summary>
- internal sealed class StringTypeInfo : TraceLoggingTypeInfo
- {
- public StringTypeInfo() : base(typeof(string)) { }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.AddBinary(name, Statics.MakeDataType(TraceLoggingDataType.CountedUtf16String, format));
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- collector.AddBinary((string)value.ReferenceValue);
- }
-
- public override object GetData(object value)
- {
- if(value == null)
- {
- return "";
- }
-
- return value;
- }
- }
-
- /// <summary>
- /// TraceLogging: Type handler for DateTime.
- /// </summary>
- internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo
- {
- public DateTimeTypeInfo() : base(typeof(DateTime)) { }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format));
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- var ticks = value.ScalarValue.AsDateTime.Ticks;
- collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000);
- }
- }
-
- /// <summary>
- /// TraceLogging: Type handler for DateTimeOffset.
- /// </summary>
- internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo
- {
- public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { }
-
- public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
- {
- var group = collector.AddGroup(name);
- group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format));
- group.AddScalar("Offset", TraceLoggingDataType.Int64);
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- var dateTimeOffset = value.ScalarValue.AsDateTimeOffset;
- var ticks = dateTimeOffset.Ticks;
- collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000);
- collector.AddScalar(dateTimeOffset.Offset.Ticks);
- }
- }
-
- /// <summary>
- /// TraceLogging: Type handler for TimeSpan.
- /// </summary>
- internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo
- {
- public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format));
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks);
- }
- }
-
- /// <summary>
- /// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.)
- /// </summary>
- internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo
- {
- public DecimalTypeInfo() : base(typeof(Decimal)) { }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format));
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- collector.AddScalar((double)value.ScalarValue.AsDecimal);
- }
- }
-
- /// <summary>
- /// TraceLogging: Type handler for Nullable.
- /// </summary>
- internal sealed class NullableTypeInfo : TraceLoggingTypeInfo
- {
- private readonly TraceLoggingTypeInfo valueInfo;
- private readonly Func<PropertyValue, PropertyValue> hasValueGetter;
- private readonly Func<PropertyValue, PropertyValue> valueGetter;
-
- public NullableTypeInfo(Type type, List<Type> recursionCheck)
- : base(type)
- {
- var typeArgs = type.GenericTypeArguments;
- Debug.Assert(typeArgs.Length == 1);
- this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck);
- this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue"));
- this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value"));
- }
-
- public override void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format)
- {
- var group = collector.AddGroup(name);
- group.AddScalar("HasValue", TraceLoggingDataType.Boolean8);
- this.valueInfo.WriteMetadata(group, "Value", format);
- }
-
- public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
- {
- var hasValue = hasValueGetter(value);
- collector.AddScalar(hasValue);
- var val = hasValue.ScalarValue.AsBoolean ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType));
- this.valueInfo.WriteData(collector, val);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs
deleted file mode 100644
index 516c8ba19a..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/Statics.cs
+++ /dev/null
@@ -1,727 +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.Collections.Generic;
-using System.Reflection;
-using System.Runtime.CompilerServices;
-using Encoding = System.Text.Encoding;
-
-using Microsoft.Reflection;
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Constants and utility functions.
- /// </summary>
- internal static class Statics
- {
- #region Constants
-
- public const byte DefaultLevel = 5;
- public const byte TraceLoggingChannel = 0xb;
- public const byte InTypeMask = 31;
- public const byte InTypeFixedCountFlag = 32;
- public const byte InTypeVariableCountFlag = 64;
- public const byte InTypeCustomCountFlag = 96;
- public const byte InTypeCountMask = 96;
- public const byte InTypeChainFlag = 128;
- public const byte OutTypeMask = 127;
- public const byte OutTypeChainFlag = 128;
- public const EventTags EventTagsMask = (EventTags)0xfffffff;
-
- public static readonly TraceLoggingDataType IntPtrType = IntPtr.Size == 8
- ? TraceLoggingDataType.Int64
- : TraceLoggingDataType.Int32;
- public static readonly TraceLoggingDataType UIntPtrType = IntPtr.Size == 8
- ? TraceLoggingDataType.UInt64
- : TraceLoggingDataType.UInt32;
- public static readonly TraceLoggingDataType HexIntPtrType = IntPtr.Size == 8
- ? TraceLoggingDataType.HexInt64
- : TraceLoggingDataType.HexInt32;
-
- #endregion
-
- #region Metadata helpers
-
- /// <summary>
- /// A complete metadata chunk can be expressed as:
- /// length16 + prefix + null-terminated-utf8-name + suffix + additionalData.
- /// We assume that excludedData will be provided by some other means,
- /// but that its size is known. This function returns a blob containing
- /// length16 + prefix + name + suffix, with prefix and suffix initialized
- /// to 0's. The length16 value is initialized to the length of the returned
- /// blob plus additionalSize, so that the concatenation of the returned blob
- /// plus a blob of size additionalSize constitutes a valid metadata blob.
- /// </summary>
- /// <param name="name">
- /// The name to include in the blob.
- /// </param>
- /// <param name="prefixSize">
- /// Amount of space to reserve before name. For provider or field blobs, this
- /// should be 0. For event blobs, this is used for the tags field and will vary
- /// from 1 to 4, depending on how large the tags field needs to be.
- /// </param>
- /// <param name="suffixSize">
- /// Amount of space to reserve after name. For example, a provider blob with no
- /// traits would reserve 0 extra bytes, but a provider blob with a single GroupId
- /// field would reserve 19 extra bytes.
- /// </param>
- /// <param name="additionalSize">
- /// Amount of additional data in another blob. This value will be counted in the
- /// blob's length field, but will not be included in the returned byte[] object.
- /// The complete blob would then be the concatenation of the returned byte[] object
- /// with another byte[] object of length additionalSize.
- /// </param>
- /// <returns>
- /// A byte[] object with the length and name fields set, with room reserved for
- /// prefix and suffix. If additionalSize was 0, the byte[] object is a complete
- /// blob. Otherwise, another byte[] of size additionalSize must be concatenated
- /// with this one to form a complete blob.
- /// </returns>
- public static byte[] MetadataForString(
- string name,
- int prefixSize,
- int suffixSize,
- int additionalSize)
- {
- Statics.CheckName(name);
- int metadataSize = Encoding.UTF8.GetByteCount(name) + 3 + prefixSize + suffixSize;
- var metadata = new byte[metadataSize];
- ushort totalSize = checked((ushort)(metadataSize + additionalSize));
- metadata[0] = unchecked((byte)totalSize);
- metadata[1] = unchecked((byte)(totalSize >> 8));
- Encoding.UTF8.GetBytes(name, 0, name.Length, metadata, 2 + prefixSize);
- return metadata;
- }
-
- /// <summary>
- /// Serialize the low 28 bits of the tags value into the metadata stream,
- /// starting at the index given by pos. Updates pos. Writes 1 to 4 bytes,
- /// depending on the value of the tags variable. Usable for event tags and
- /// field tags.
- ///
- /// Note that 'metadata' can be null, in which case it only updates 'pos'.
- /// This is useful for a two pass approach where you figure out how big to
- /// make the array, and then you fill it in.
- /// </summary>
- public static void EncodeTags(int tags, ref int pos, byte[] metadata)
- {
- // We transmit the low 28 bits of tags, high bits first, 7 bits at a time.
- var tagsLeft = tags & 0xfffffff;
- bool more;
- do
- {
- byte current = (byte)((tagsLeft >> 21) & 0x7f);
- more = (tagsLeft & 0x1fffff) != 0;
- current |= (byte)(more ? 0x80 : 0x00);
- tagsLeft = tagsLeft << 7;
-
- if (metadata != null)
- {
- metadata[pos] = current;
- }
- pos += 1;
- }
- while (more);
- }
-
- public static byte Combine(
- int settingValue,
- byte defaultValue)
- {
- unchecked
- {
- return (byte)settingValue == settingValue
- ? (byte)settingValue
- : defaultValue;
- }
- }
-
- public static byte Combine(
- int settingValue1,
- int settingValue2,
- byte defaultValue)
- {
- unchecked
- {
- return (byte)settingValue1 == settingValue1
- ? (byte)settingValue1
- : (byte)settingValue2 == settingValue2
- ? (byte)settingValue2
- : defaultValue;
- }
- }
-
- public static int Combine(
- int settingValue1,
- int settingValue2)
- {
- unchecked
- {
- return (byte)settingValue1 == settingValue1
- ? settingValue1
- : settingValue2;
- }
- }
-
- public static void CheckName(string name)
- {
- if (name != null && 0 <= name.IndexOf('\0'))
- {
- throw new ArgumentOutOfRangeException(nameof(name));
- }
- }
-
- public static bool ShouldOverrideFieldName(string fieldName)
- {
- return (fieldName.Length <= 2 && fieldName[0] == '_');
- }
-
- public static TraceLoggingDataType MakeDataType(
- TraceLoggingDataType baseType,
- EventFieldFormat format)
- {
- return (TraceLoggingDataType)(((int)baseType & 0x1f) | ((int)format << 8));
- }
-
- /// <summary>
- /// Adjusts the native type based on format.
- /// - If format is default, return native.
- /// - If format is recognized, return the canonical type for that format.
- /// - Otherwise remove existing format from native and apply the requested format.
- /// </summary>
- public static TraceLoggingDataType Format8(
- EventFieldFormat format,
- TraceLoggingDataType native)
- {
- switch (format)
- {
- case EventFieldFormat.Default:
- return native;
- case EventFieldFormat.String:
- return TraceLoggingDataType.Char8;
- case EventFieldFormat.Boolean:
- return TraceLoggingDataType.Boolean8;
- case EventFieldFormat.Hexadecimal:
- return TraceLoggingDataType.HexInt8;
-#if false
- case EventSourceFieldFormat.Signed:
- return TraceLoggingDataType.Int8;
- case EventSourceFieldFormat.Unsigned:
- return TraceLoggingDataType.UInt8;
-#endif
- default:
- return MakeDataType(native, format);
- }
- }
-
- /// <summary>
- /// Adjusts the native type based on format.
- /// - If format is default, return native.
- /// - If format is recognized, return the canonical type for that format.
- /// - Otherwise remove existing format from native and apply the requested format.
- /// </summary>
- public static TraceLoggingDataType Format16(
- EventFieldFormat format,
- TraceLoggingDataType native)
- {
- switch (format)
- {
- case EventFieldFormat.Default:
- return native;
- case EventFieldFormat.String:
- return TraceLoggingDataType.Char16;
- case EventFieldFormat.Hexadecimal:
- return TraceLoggingDataType.HexInt16;
-#if false
- case EventSourceFieldFormat.Port:
- return TraceLoggingDataType.Port;
- case EventSourceFieldFormat.Signed:
- return TraceLoggingDataType.Int16;
- case EventSourceFieldFormat.Unsigned:
- return TraceLoggingDataType.UInt16;
-#endif
- default:
- return MakeDataType(native, format);
- }
- }
-
- /// <summary>
- /// Adjusts the native type based on format.
- /// - If format is default, return native.
- /// - If format is recognized, return the canonical type for that format.
- /// - Otherwise remove existing format from native and apply the requested format.
- /// </summary>
- public static TraceLoggingDataType Format32(
- EventFieldFormat format,
- TraceLoggingDataType native)
- {
- switch (format)
- {
- case EventFieldFormat.Default:
- return native;
- case EventFieldFormat.Boolean:
- return TraceLoggingDataType.Boolean32;
- case EventFieldFormat.Hexadecimal:
- return TraceLoggingDataType.HexInt32;
-#if false
- case EventSourceFieldFormat.Ipv4Address:
- return TraceLoggingDataType.Ipv4Address;
- case EventSourceFieldFormat.ProcessId:
- return TraceLoggingDataType.ProcessId;
- case EventSourceFieldFormat.ThreadId:
- return TraceLoggingDataType.ThreadId;
- case EventSourceFieldFormat.Win32Error:
- return TraceLoggingDataType.Win32Error;
- case EventSourceFieldFormat.NTStatus:
- return TraceLoggingDataType.NTStatus;
-#endif
- case EventFieldFormat.HResult:
- return TraceLoggingDataType.HResult;
-#if false
- case EventSourceFieldFormat.Signed:
- return TraceLoggingDataType.Int32;
- case EventSourceFieldFormat.Unsigned:
- return TraceLoggingDataType.UInt32;
-#endif
- default:
- return MakeDataType(native, format);
- }
- }
-
- /// <summary>
- /// Adjusts the native type based on format.
- /// - If format is default, return native.
- /// - If format is recognized, return the canonical type for that format.
- /// - Otherwise remove existing format from native and apply the requested format.
- /// </summary>
- public static TraceLoggingDataType Format64(
- EventFieldFormat format,
- TraceLoggingDataType native)
- {
- switch (format)
- {
- case EventFieldFormat.Default:
- return native;
- case EventFieldFormat.Hexadecimal:
- return TraceLoggingDataType.HexInt64;
-#if false
- case EventSourceFieldFormat.FileTime:
- return TraceLoggingDataType.FileTime;
- case EventSourceFieldFormat.Signed:
- return TraceLoggingDataType.Int64;
- case EventSourceFieldFormat.Unsigned:
- return TraceLoggingDataType.UInt64;
-#endif
- default:
- return MakeDataType(native, format);
- }
- }
-
- /// <summary>
- /// Adjusts the native type based on format.
- /// - If format is default, return native.
- /// - If format is recognized, return the canonical type for that format.
- /// - Otherwise remove existing format from native and apply the requested format.
- /// </summary>
- public static TraceLoggingDataType FormatPtr(
- EventFieldFormat format,
- TraceLoggingDataType native)
- {
- switch (format)
- {
- case EventFieldFormat.Default:
- return native;
- case EventFieldFormat.Hexadecimal:
- return HexIntPtrType;
-#if false
- case EventSourceFieldFormat.Signed:
- return IntPtrType;
- case EventSourceFieldFormat.Unsigned:
- return UIntPtrType;
-#endif
- default:
- return MakeDataType(native, format);
- }
- }
-
- #endregion
-
- #region Reflection helpers
-
- /*
- All TraceLogging use of reflection APIs should go through wrappers here.
- This helps with portability, and it also makes it easier to audit what
- kinds of reflection operations are being done.
- */
-
- public static object CreateInstance(Type type, params object[] parameters)
- {
- return Activator.CreateInstance(type, parameters);
- }
-
- public static bool IsValueType(Type type)
- {
- bool result = type.IsValueType();
- return result;
- }
-
- public static bool IsEnum(Type type)
- {
- bool result = type.IsEnum();
- return result;
- }
-
- public static IEnumerable<PropertyInfo> GetProperties(Type type)
- {
- IEnumerable<PropertyInfo> result = type.GetProperties();
- return result;
- }
-
- public static MethodInfo GetGetMethod(PropertyInfo propInfo)
- {
- MethodInfo result = propInfo.GetGetMethod();
- return result;
- }
-
- public static MethodInfo GetDeclaredStaticMethod(Type declaringType, string name)
- {
- MethodInfo result;
-#if (ES_BUILD_PCL || PROJECTN)
- result = declaringType.GetTypeInfo().GetDeclaredMethod(name);
-#else
- result = declaringType.GetMethod(
- name,
- BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
-#endif
- return result;
- }
-
- public static bool HasCustomAttribute(
- PropertyInfo propInfo,
- Type attributeType)
- {
- bool result;
-#if (ES_BUILD_PCL || PROJECTN)
- result = propInfo.IsDefined(attributeType);
-#else
- var attributes = propInfo.GetCustomAttributes(
- attributeType,
- false);
- result = attributes.Length != 0;
-#endif
- return result;
- }
-
- public static AttributeType GetCustomAttribute<AttributeType>(PropertyInfo propInfo)
- where AttributeType : Attribute
- {
- AttributeType result = null;
-#if (ES_BUILD_PCL || PROJECTN)
- foreach (var attrib in propInfo.GetCustomAttributes<AttributeType>(false))
- {
- result = attrib;
- break;
- }
-#else
- var attributes = propInfo.GetCustomAttributes(typeof(AttributeType), false);
- if (attributes.Length != 0)
- {
- result = (AttributeType)attributes[0];
- }
-#endif
- return result;
- }
-
- public static AttributeType GetCustomAttribute<AttributeType>(Type type)
- where AttributeType : Attribute
- {
- AttributeType result = null;
-#if (ES_BUILD_PCL || PROJECTN)
- foreach (var attrib in type.GetTypeInfo().GetCustomAttributes<AttributeType>(false))
- {
- result = attrib;
- break;
- }
-#else
- var attributes = type.GetCustomAttributes(typeof(AttributeType), false);
- if (attributes.Length != 0)
- {
- result = (AttributeType)attributes[0];
- }
-#endif
- return result;
- }
-
- public static Type[] GetGenericArguments(Type type)
- {
- return type.GetGenericArguments();
- }
-
- public static Type FindEnumerableElementType(Type type)
- {
- Type elementType = null;
-
- if (IsGenericMatch(type, typeof(IEnumerable<>)))
- {
- elementType = GetGenericArguments(type)[0];
- }
- else
- {
-#if (ES_BUILD_PCL || PROJECTN)
- var ifaceTypes = type.GetTypeInfo().ImplementedInterfaces;
-#else
- var ifaceTypes = type.FindInterfaces(IsGenericMatch, typeof(IEnumerable<>));
-#endif
-
- foreach (var ifaceType in ifaceTypes)
- {
-#if (ES_BUILD_PCL || PROJECTN)
- if (!IsGenericMatch(ifaceType, typeof(IEnumerable<>)))
- {
- continue;
- }
-#endif
-
- if (elementType != null)
- {
- // ambiguous match. report no match at all.
- elementType = null;
- break;
- }
-
- elementType = GetGenericArguments(ifaceType)[0];
- }
- }
-
- return elementType;
- }
-
- public static bool IsGenericMatch(Type type, object openType)
- {
- return type.IsGenericType() && type.GetGenericTypeDefinition() == (Type)openType;
- }
-
- public static Delegate CreateDelegate(Type delegateType, MethodInfo methodInfo)
- {
- Delegate result;
-#if (ES_BUILD_PCL || PROJECTN)
- result = methodInfo.CreateDelegate(
- delegateType);
-#else
- result = Delegate.CreateDelegate(
- delegateType,
- methodInfo);
-#endif
- return result;
- }
-
- public static TraceLoggingTypeInfo CreateDefaultTypeInfo(
- Type dataType,
- List<Type> recursionCheck)
- {
- TraceLoggingTypeInfo result;
-
- if (recursionCheck.Contains(dataType))
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_RecursiveTypeDefinition"));
- }
-
- recursionCheck.Add(dataType);
-
- var eventAttrib = Statics.GetCustomAttribute<EventDataAttribute>(dataType);
- if (eventAttrib != null ||
- Statics.GetCustomAttribute<CompilerGeneratedAttribute>(dataType) != null ||
- IsGenericMatch(dataType, typeof(KeyValuePair<,>)))
- {
- var analysis = new TypeAnalysis(dataType, eventAttrib, recursionCheck);
- result = new InvokeTypeInfo(dataType, analysis);
- }
- else if (dataType.IsArray)
- {
- var elementType = dataType.GetElementType();
- if (elementType == typeof(Boolean))
- {
- result = ScalarArrayTypeInfo.Boolean();
- }
- else if (elementType == typeof(Byte))
- {
- result = ScalarArrayTypeInfo.Byte();
- }
- else if (elementType == typeof(SByte))
- {
- result = ScalarArrayTypeInfo.SByte();
- }
- else if (elementType == typeof(Int16))
- {
- result = ScalarArrayTypeInfo.Int16();
- }
- else if (elementType == typeof(UInt16))
- {
- result = ScalarArrayTypeInfo.UInt16();
- }
- else if (elementType == typeof(Int32))
- {
- result = ScalarArrayTypeInfo.Int32();
- }
- else if (elementType == typeof(UInt32))
- {
- result = ScalarArrayTypeInfo.UInt32();
- }
- else if (elementType == typeof(Int64))
- {
- result = ScalarArrayTypeInfo.Int64();
- }
- else if (elementType == typeof(UInt64))
- {
- result = ScalarArrayTypeInfo.UInt64();
- }
- else if (elementType == typeof(Char))
- {
- result = ScalarArrayTypeInfo.Char();
- }
- else if (elementType == typeof(Double))
- {
- result = ScalarArrayTypeInfo.Double();
- }
- else if (elementType == typeof(Single))
- {
- result = ScalarArrayTypeInfo.Single();
- }
- else if (elementType == typeof(IntPtr))
- {
- result = ScalarArrayTypeInfo.IntPtr();
- }
- else if (elementType == typeof(UIntPtr))
- {
- result = ScalarArrayTypeInfo.UIntPtr();
- }
- else if (elementType == typeof(Guid))
- {
- result = ScalarArrayTypeInfo.Guid();
- }
- else
- {
- result = new ArrayTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck));
- }
- }
- else
- {
- if (Statics.IsEnum(dataType))
- dataType = Enum.GetUnderlyingType(dataType);
-
- if (dataType == typeof(String))
- {
- result = new StringTypeInfo();
- }
- else if (dataType == typeof(Boolean))
- {
- result = ScalarTypeInfo.Boolean();
- }
- else if (dataType == typeof(Byte))
- {
- result = ScalarTypeInfo.Byte();
- }
- else if (dataType == typeof(SByte))
- {
- result = ScalarTypeInfo.SByte();
- }
- else if (dataType == typeof(Int16))
- {
- result = ScalarTypeInfo.Int16();
- }
- else if (dataType == typeof(UInt16))
- {
- result = ScalarTypeInfo.UInt16();
- }
- else if (dataType == typeof(Int32))
- {
- result = ScalarTypeInfo.Int32();
- }
- else if (dataType == typeof(UInt32))
- {
- result = ScalarTypeInfo.UInt32();
- }
- else if (dataType == typeof(Int64))
- {
- result = ScalarTypeInfo.Int64();
- }
- else if (dataType == typeof(UInt64))
- {
- result = ScalarTypeInfo.UInt64();
- }
- else if (dataType == typeof(Char))
- {
- result = ScalarTypeInfo.Char();
- }
- else if (dataType == typeof(Double))
- {
- result = ScalarTypeInfo.Double();
- }
- else if (dataType == typeof(Single))
- {
- result = ScalarTypeInfo.Single();
- }
- else if (dataType == typeof(DateTime))
- {
- result = new DateTimeTypeInfo();
- }
- else if (dataType == typeof(Decimal))
- {
- result = new DecimalTypeInfo();
- }
- else if (dataType == typeof(IntPtr))
- {
- result = ScalarTypeInfo.IntPtr();
- }
- else if (dataType == typeof(UIntPtr))
- {
- result = ScalarTypeInfo.UIntPtr();
- }
- else if (dataType == typeof(Guid))
- {
- result = ScalarTypeInfo.Guid();
- }
- else if (dataType == typeof(TimeSpan))
- {
- result = new TimeSpanTypeInfo();
- }
- else if (dataType == typeof(DateTimeOffset))
- {
- result = new DateTimeOffsetTypeInfo();
- }
- else if (dataType == typeof(EmptyStruct))
- {
- result = new NullTypeInfo();
- }
- else if (IsGenericMatch(dataType, typeof(Nullable<>)))
- {
- result = new NullableTypeInfo(dataType, recursionCheck);
- }
- else
- {
- var elementType = FindEnumerableElementType(dataType);
- if (elementType != null)
- {
- result = new EnumerableTypeInfo(dataType, TraceLoggingTypeInfo.GetInstance(elementType, recursionCheck));
- }
- else
- {
- throw new ArgumentException(Resources.GetResourceString("EventSource_NonCompliantTypeError", dataType.Name));
- }
- }
- }
-
- return result;
- }
-
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs
deleted file mode 100644
index 04a047fb35..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataCollector.cs
+++ /dev/null
@@ -1,104 +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.Security;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Used when implementing a custom TraceLoggingTypeInfo.
- /// The instance of this type is provided to the TypeInfo.WriteData method.
- /// All operations are forwarded to the current thread's DataCollector.
- /// Note that this abstraction would allow us to expose the custom
- /// serialization system to partially-trusted code. If we end up not
- /// making custom serialization public, or if we only expose it to
- /// full-trust code, this abstraction is unnecessary (though it probably
- /// doesn't hurt anything).
- /// </summary>
- internal unsafe class TraceLoggingDataCollector
- {
- internal static readonly TraceLoggingDataCollector Instance = new TraceLoggingDataCollector();
-
- private TraceLoggingDataCollector()
- {
- return;
- }
-
- /// <summary>
- /// Marks the start of a non-blittable array or enumerable.
- /// </summary>
- /// <returns>Bookmark to be passed to EndBufferedArray.</returns>
- public int BeginBufferedArray()
- {
- return DataCollector.ThreadInstance.BeginBufferedArray();
- }
-
- /// <summary>
- /// Marks the end of a non-blittable array or enumerable.
- /// </summary>
- /// <param name="bookmark">The value returned by BeginBufferedArray.</param>
- /// <param name="count">The number of items in the array.</param>
- public void EndBufferedArray(int bookmark, int count)
- {
- DataCollector.ThreadInstance.EndBufferedArray(bookmark, count);
- }
-
- /// <summary>
- /// Adds the start of a group to the event.
- /// This has no effect on the event payload, but is provided to allow
- /// WriteMetadata and WriteData implementations to have similar
- /// sequences of calls, allowing for easier verification of correctness.
- /// </summary>
- public TraceLoggingDataCollector AddGroup()
- {
- return this;
- }
-
- public void AddScalar(PropertyValue value)
- {
- var scalar = value.ScalarValue;
- DataCollector.ThreadInstance.AddScalar(&scalar, value.ScalarLength);
- }
-
- /// <summary>
- /// Adds an Int64 value to the event payload.
- /// </summary>
- /// <param name="value">Value to be added.</param>
- public void AddScalar(long value)
- {
- DataCollector.ThreadInstance.AddScalar(&value, sizeof(long));
- }
-
- /// <summary>
- /// Adds a Double value to the event payload.
- /// </summary>
- /// <param name="value">Value to be added.</param>
- public void AddScalar(double value)
- {
- DataCollector.ThreadInstance.AddScalar(&value, sizeof(double));
- }
-
- /// <summary>
- /// Adds a counted String value to the event payload.
- /// </summary>
- /// <param name="value">
- /// Value to be added. A null value is treated as a zero-length string.
- /// </param>
- public void AddBinary(string value)
- {
- DataCollector.ThreadInstance.AddBinary(value, value == null ? 0 : value.Length * 2);
- }
-
- public void AddArray(PropertyValue value, int elementSize)
- {
- Array array = (Array)value.ReferenceValue;
- DataCollector.ThreadInstance.AddArray(array, array == null ? 0 : array.Length, elementSize);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataType.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataType.cs
deleted file mode 100644
index 529948daf8..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingDataType.cs
+++ /dev/null
@@ -1,349 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Used when implementing a custom TraceLoggingTypeInfo.
- /// These are passed to metadataCollector.Add to specify the low-level
- /// type of a field in the event payload. Note that a "formatted"
- /// TraceLoggingDataType consists of a core TraceLoggingDataType value
- /// (a TraceLoggingDataType with a value less than 32) plus an OutType.
- /// Any combination of TraceLoggingDataType + OutType is valid, but not
- /// all are useful. In particular, combinations not explicitly listed
- /// below are unlikely to be recognized by decoders, and will typically
- /// be decoded as the corresponding core type (i.e. the decoder will
- /// mask off any unrecognized OutType value).
- /// </summary>
- internal enum TraceLoggingDataType
- {
- /// <summary>
- /// Core type.
- /// Data type with no value (0-length payload).
- /// NOTE: arrays of Nil are illegal.
- /// NOTE: a fixed-length array of Nil is interpreted by the decoder as
- /// a struct (obsolete but retained for backwards-compatibility).
- /// </summary>
- Nil = 0,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes null-terminated Char16 string.
- /// Decoding treats as UTF-16LE string.
- /// </summary>
- Utf16String = 1,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes null-terminated Char8 string.
- /// Decoding treats as MBCS string.
- /// </summary>
- MbcsString = 2,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 8-bit value.
- /// Decoding treats as signed integer.
- /// </summary>
- Int8 = 3,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 8-bit value.
- /// Decoding treats as unsigned integer.
- /// </summary>
- UInt8 = 4,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-bit value.
- /// Decoding treats as signed integer.
- /// </summary>
- Int16 = 5,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-bit value.
- /// Decoding treats as unsigned integer.
- /// </summary>
- UInt16 = 6,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as signed integer.
- /// </summary>
- Int32 = 7,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as unsigned integer.
- /// </summary>
- UInt32 = 8,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 64-bit value.
- /// Decoding treats as signed integer.
- /// </summary>
- Int64 = 9,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 64-bit value.
- /// Decoding treats as unsigned integer.
- /// </summary>
- UInt64 = 10,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as Float.
- /// </summary>
- Float = 11,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 64-bit value.
- /// Decoding treats as Double.
- /// </summary>
- Double = 12,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as Boolean.
- /// </summary>
- Boolean32 = 13,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-bit bytecount followed by binary data.
- /// Decoding treats as binary data.
- /// </summary>
- Binary = 14,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-byte value.
- /// Decoding treats as GUID.
- /// </summary>
- Guid = 15,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 64-bit value.
- /// Decoding treats as FILETIME.
- /// </summary>
- FileTime = 17,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-byte value.
- /// Decoding treats as SYSTEMTIME.
- /// </summary>
- SystemTime = 18,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as hexadecimal unsigned integer.
- /// </summary>
- HexInt32 = 20,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 64-bit value.
- /// Decoding treats as hexadecimal unsigned integer.
- /// </summary>
- HexInt64 = 21,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-bit bytecount followed by Char16 data.
- /// Decoding treats as UTF-16LE string.
- /// </summary>
- CountedUtf16String = 22,
-
- /// <summary>
- /// Core type.
- /// Encoding assumes 16-bit bytecount followed by Char8 data.
- /// Decoding treats as MBCS string.
- /// </summary>
- CountedMbcsString = 23,
-
- /// <summary>
- /// Core type.
- /// Special case: Struct indicates that this field plus the 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
- /// itself, but logically contains the payload of the following N
- /// fields. It is legal to have an array of Struct.
- /// </summary>
- Struct = 24,
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit value.
- /// Decoding treats as UTF-16LE character.
- /// </summary>
- Char16 = UInt16 + (EventFieldFormat.String << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 8-bit value.
- /// Decoding treats as character.
- /// </summary>
- Char8 = UInt8 + (EventFieldFormat.String << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 8-bit value.
- /// Decoding treats as Boolean.
- /// </summary>
- Boolean8 = UInt8 + (EventFieldFormat.Boolean << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 8-bit value.
- /// Decoding treats as hexadecimal unsigned integer.
- /// </summary>
- HexInt8 = UInt8 + (EventFieldFormat.Hexadecimal << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit value.
- /// Decoding treats as hexadecimal unsigned integer.
- /// </summary>
- HexInt16 = UInt16 + (EventFieldFormat.Hexadecimal << 8),
-
-#if false
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as process identifier.
- /// </summary>
- ProcessId = UInt32 + (EventSourceFieldFormat.ProcessId << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as thread identifier.
- /// </summary>
- ThreadId = UInt32 + (EventSourceFieldFormat.ThreadId << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit value.
- /// Decoding treats as IP port.
- /// </summary>
- Port = UInt16 + (EventSourceFieldFormat.Port << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as IPv4 address.
- /// </summary>
- Ipv4Address = UInt32 + (EventSourceFieldFormat.Ipv4Address << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit bytecount followed by binary data.
- /// Decoding treats as IPv6 address.
- /// </summary>
- Ipv6Address = Binary + (EventSourceFieldFormat.Ipv6Address << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit bytecount followed by binary data.
- /// Decoding treats as SOCKADDR.
- /// </summary>
- SocketAddress = Binary + (EventSourceFieldFormat.SocketAddress << 8),
-#endif
- /// <summary>
- /// Formatted type.
- /// Encoding assumes null-terminated Char16 string.
- /// Decoding treats as UTF-16LE XML string.
- /// </summary>
- Utf16Xml = Utf16String + (EventFieldFormat.Xml << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes null-terminated Char8 string.
- /// Decoding treats as MBCS XML string.
- /// </summary>
- MbcsXml = MbcsString + (EventFieldFormat.Xml << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit bytecount followed by Char16 data.
- /// Decoding treats as UTF-16LE XML.
- /// </summary>
- CountedUtf16Xml = CountedUtf16String + (EventFieldFormat.Xml << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit bytecount followed by Char8 data.
- /// Decoding treats as MBCS XML.
- /// </summary>
- CountedMbcsXml = CountedMbcsString + (EventFieldFormat.Xml << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes null-terminated Char16 string.
- /// Decoding treats as UTF-16LE JSON string.
- /// </summary>
- Utf16Json = Utf16String + (EventFieldFormat.Json << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes null-terminated Char8 string.
- /// Decoding treats as MBCS JSON string.
- /// </summary>
- MbcsJson = MbcsString + (EventFieldFormat.Json << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit bytecount followed by Char16 data.
- /// Decoding treats as UTF-16LE JSON.
- /// </summary>
- CountedUtf16Json = CountedUtf16String + (EventFieldFormat.Json << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 16-bit bytecount followed by Char8 data.
- /// Decoding treats as MBCS JSON.
- /// </summary>
- CountedMbcsJson = CountedMbcsString + (EventFieldFormat.Json << 8),
-#if false
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as Win32 error.
- /// </summary>
- Win32Error = UInt32 + (EventSourceFieldFormat.Win32Error << 8),
-
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as NTSTATUS.
- /// </summary>
- NTStatus = UInt32 + (EventSourceFieldFormat.NTStatus << 8),
-#endif
- /// <summary>
- /// Formatted type.
- /// Encoding assumes 32-bit value.
- /// Decoding treats as HRESULT.
- /// </summary>
- HResult = Int32 + (EventFieldFormat.HResult << 8)
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
deleted file mode 100644
index 07a56751ea..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventSource.cs
+++ /dev/null
@@ -1,890 +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.
-
-// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
-// It is available from http://www.codeplex.com/hyperAddin
-
-#if !PLATFORM_UNIX
-#define FEATURE_MANAGED_ETW
-
-#if !ES_BUILD_STANDALONE
-#define FEATURE_ACTIVITYSAMPLING
-#endif
-#endif // PLATFORM_UNIX
-
-#if ES_BUILD_STANDALONE
-#define FEATURE_MANAGED_ETW_CHANNELS
-// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
-#endif
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
-#endif
-
-using System;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Collections.ObjectModel;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-using System.Collections.Generic;
-using System.Text;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-using System.Collections.Generic;
-using System.Text;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- public partial class EventSource
- {
-#if FEATURE_MANAGED_ETW
- private byte[] providerMetadata;
-#endif
-
- /// <summary>
- /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
- /// </summary>
- /// <param name="eventSourceName">
- /// The name of the event source. Must not be null.
- /// </param>
- public EventSource(
- string eventSourceName)
- : this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
- { }
-
- /// <summary>
- /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
- /// </summary>
- /// <param name="eventSourceName">
- /// The name of the event source. Must not be null.
- /// </param>
- /// <param name="config">
- /// Configuration options for the EventSource as a whole.
- /// </param>
- public EventSource(
- string eventSourceName,
- EventSourceSettings config)
- : this(eventSourceName, config, null) { }
-
- /// <summary>
- /// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
- ///
- /// 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).
- /// </summary>
- /// <param name="eventSourceName">
- /// The name of the event source. Must not be null.
- /// </param>
- /// <param name="config">
- /// Configuration options for the EventSource as a whole.
- /// </param>
- /// <param name="traits">A collection of key-value strings (must be an even number).</param>
- public EventSource(
- string eventSourceName,
- EventSourceSettings config,
- params string[] traits)
- : this(
- eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
- eventSourceName,
- config, traits)
- {
- if (eventSourceName == null)
- {
- throw new ArgumentNullException(nameof(eventSourceName));
- }
- Contract.EndContractBlock();
- }
-
- /// <summary>
- /// Writes an event with no fields and default options.
- /// (Native API: EventWriteTransfer)
- /// </summary>
- /// <param name="eventName">The name of the event. Must not be null.</param>
- public unsafe void Write(string eventName)
- {
- if (eventName == null)
- {
- throw new ArgumentNullException(nameof(eventName));
- }
-
- Contract.EndContractBlock();
-
- if (!this.IsEnabled())
- {
- return;
- }
-
- var options = new EventSourceOptions();
- this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
- }
-
- /// <summary>
- /// Writes an event with no fields.
- /// (Native API: EventWriteTransfer)
- /// </summary>
- /// <param name="eventName">The name of the event. Must not be null.</param>
- /// <param name="options">
- /// Options for the event, such as the level, keywords, and opcode. Unset
- /// options will be set to default values.
- /// </param>
- public unsafe void Write(string eventName, EventSourceOptions options)
- {
- if (eventName == null)
- {
- throw new ArgumentNullException(nameof(eventName));
- }
-
- Contract.EndContractBlock();
-
- if (!this.IsEnabled())
- {
- return;
- }
-
- this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
- }
-
- /// <summary>
- /// Writes an event.
- /// (Native API: EventWriteTransfer)
- /// </summary>
- /// <typeparam name="T">
- /// The type that defines the event and its payload. This must be an
- /// anonymous type or a type with an [EventData] attribute.
- /// </typeparam>
- /// <param name="eventName">
- /// The name for the event. If null, the event name is automatically
- /// determined based on T, either from the Name property of T's EventData
- /// attribute or from typeof(T).Name.
- /// </param>
- /// <param name="data">
- /// The object containing the event payload data. The type T must be
- /// an anonymous type or a type with an [EventData] attribute. The
- /// public instance properties of data will be written recursively to
- /// create the fields of the event.
- /// </param>
- public unsafe void Write<T>(
- string eventName,
- T data)
- {
- if (!this.IsEnabled())
- {
- return;
- }
-
- var options = new EventSourceOptions();
- this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
- }
-
- /// <summary>
- /// Writes an event.
- /// (Native API: EventWriteTransfer)
- /// </summary>
- /// <typeparam name="T">
- /// The type that defines the event and its payload. This must be an
- /// anonymous type or a type with an [EventData] attribute.
- /// </typeparam>
- /// <param name="eventName">
- /// The name for the event. If null, the event name is automatically
- /// determined based on T, either from the Name property of T's EventData
- /// attribute or from typeof(T).Name.
- /// </param>
- /// <param name="options">
- /// Options for the event, such as the level, keywords, and opcode. Unset
- /// options will be set to default values.
- /// </param>
- /// <param name="data">
- /// The object containing the event payload data. The type T must be
- /// an anonymous type or a type with an [EventData] attribute. The
- /// public instance properties of data will be written recursively to
- /// create the fields of the event.
- /// </param>
- public unsafe void Write<T>(
- string eventName,
- EventSourceOptions options,
- T data)
- {
- if (!this.IsEnabled())
- {
- return;
- }
-
- this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
- }
-
- /// <summary>
- /// Writes an event.
- /// This overload is for use with extension methods that wish to efficiently
- /// forward the options or data parameter without performing an extra copy.
- /// (Native API: EventWriteTransfer)
- /// </summary>
- /// <typeparam name="T">
- /// The type that defines the event and its payload. This must be an
- /// anonymous type or a type with an [EventData] attribute.
- /// </typeparam>
- /// <param name="eventName">
- /// The name for the event. If null, the event name is automatically
- /// determined based on T, either from the Name property of T's EventData
- /// attribute or from typeof(T).Name.
- /// </param>
- /// <param name="options">
- /// Options for the event, such as the level, keywords, and opcode. Unset
- /// options will be set to default values.
- /// </param>
- /// <param name="data">
- /// The object containing the event payload data. The type T must be
- /// an anonymous type or a type with an [EventData] attribute. The
- /// public instance properties of data will be written recursively to
- /// create the fields of the event.
- /// </param>
- public unsafe void Write<T>(
- string eventName,
- ref EventSourceOptions options,
- ref T data)
- {
- if (!this.IsEnabled())
- {
- return;
- }
-
- this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
- }
-
- /// <summary>
- /// Writes an event.
- /// This overload is meant for clients that need to manipuate the activityId
- /// and related ActivityId for the event.
- /// </summary>
- /// <typeparam name="T">
- /// The type that defines the event and its payload. This must be an
- /// anonymous type or a type with an [EventData] attribute.
- /// </typeparam>
- /// <param name="eventName">
- /// The name for the event. If null, the event name is automatically
- /// determined based on T, either from the Name property of T's EventData
- /// attribute or from typeof(T).Name.
- /// </param>
- /// <param name="options">
- /// Options for the event, such as the level, keywords, and opcode. Unset
- /// options will be set to default values.
- /// </param>
- /// <param name="activityId">
- /// The GUID of the activity associated with this event.
- /// </param>
- /// <param name="relatedActivityId">
- /// The GUID of another activity that is related to this activity, or Guid.Empty
- /// if there is no related activity. Most commonly, the Start operation of a
- /// new activity specifies a parent activity as its related activity.
- /// </param>
- /// <param name="data">
- /// The object containing the event payload data. The type T must be
- /// an anonymous type or a type with an [EventData] attribute. The
- /// public instance properties of data will be written recursively to
- /// create the fields of the event.
- /// </param>
- public unsafe void Write<T>(
- string eventName,
- ref EventSourceOptions options,
- ref Guid activityId,
- ref Guid relatedActivityId,
- ref T data)
- {
- if (!this.IsEnabled())
- {
- return;
- }
-
- fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
- {
- this.WriteImpl(
- eventName,
- ref options,
- data,
- pActivity,
- relatedActivityId == Guid.Empty ? null : pRelated,
- SimpleEventTypes<T>.Instance);
- }
- }
-
- /// <summary>
- /// Writes an extended event, where the values of the event are the
- /// combined properties of any number of values. This method is
- /// intended for use in advanced logging scenarios that support a
- /// dynamic set of event context providers.
- /// This method does a quick check on whether this event is enabled.
- /// </summary>
- /// <param name="eventName">
- /// The name for the event. If null, the name from eventTypes is used.
- /// (Note that providing the event name via the name parameter is slightly
- /// less efficient than using the name from eventTypes.)
- /// </param>
- /// <param name="options">
- /// Optional overrides for the event, such as the level, keyword, opcode,
- /// activityId, and relatedActivityId. Any settings not specified by options
- /// are obtained from eventTypes.
- /// </param>
- /// <param name="eventTypes">
- /// Information about the event and the types of the values in the event.
- /// Must not be null. Note that the eventTypes object should be created once and
- /// saved. It should not be recreated for each event.
- /// </param>
- /// <param name="activityID">
- /// A pointer to the activity ID GUID to log
- /// </param>
- /// <param name="childActivityID">
- /// A pointer to the child activity ID to log (can be null) </param>
- /// <param name="values">
- /// The values to include in the event. Must not be null. The number and types of
- /// the values must match the number and types of the fields described by the
- /// eventTypes parameter.
- /// </param>
- private unsafe void WriteMultiMerge(
- string eventName,
- ref EventSourceOptions options,
- TraceLoggingEventTypes eventTypes,
- Guid* activityID,
- Guid* childActivityID,
- params object[] values)
- {
- if (!this.IsEnabled())
- {
- return;
- }
- byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
- ? options.level
- : eventTypes.level;
- EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
- ? options.keywords
- : eventTypes.keywords;
-
- if (this.IsEnabled((EventLevel)level, keywords))
- {
- WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
- }
- }
-
- /// <summary>
- /// Writes an extended event, where the values of the event are the
- /// combined properties of any number of values. This method is
- /// intended for use in advanced logging scenarios that support a
- /// dynamic set of event context providers.
- /// Attention: This API does not check whether the event is enabled or not.
- /// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
- /// not enabled.
- /// </summary>
- /// <param name="eventName">
- /// The name for the event. If null, the name from eventTypes is used.
- /// (Note that providing the event name via the name parameter is slightly
- /// less efficient than using the name from eventTypes.)
- /// </param>
- /// <param name="options">
- /// Optional overrides for the event, such as the level, keyword, opcode,
- /// activityId, and relatedActivityId. Any settings not specified by options
- /// are obtained from eventTypes.
- /// </param>
- /// <param name="eventTypes">
- /// Information about the event and the types of the values in the event.
- /// Must not be null. Note that the eventTypes object should be created once and
- /// saved. It should not be recreated for each event.
- /// </param>
- /// <param name="activityID">
- /// A pointer to the activity ID GUID to log
- /// </param>
- /// <param name="childActivityID">
- /// A pointer to the child activity ID to log (can be null)
- /// </param>
- /// <param name="values">
- /// The values to include in the event. Must not be null. The number and types of
- /// the values must match the number and types of the fields described by the
- /// eventTypes parameter.
- /// </param>
- private unsafe void WriteMultiMergeInner(
- string eventName,
- ref EventSourceOptions options,
- TraceLoggingEventTypes eventTypes,
- Guid* activityID,
- Guid* childActivityID,
- params object[] values)
- {
-#if FEATURE_MANAGED_ETW
- int identity = 0;
- byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
- ? options.level
- : eventTypes.level;
- byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
- ? options.opcode
- : eventTypes.opcode;
- EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
- ? options.tags
- : eventTypes.Tags;
- EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
- ? options.keywords
- : eventTypes.keywords;
-
- var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
- if (nameInfo == null)
- {
- return;
- }
- identity = nameInfo.identity;
- EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
-
- var pinCount = eventTypes.pinCount;
- var scratch = stackalloc byte[eventTypes.scratchSize];
- var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
- var pins = stackalloc GCHandle[pinCount];
-
- fixed (byte*
- pMetadata0 = this.providerMetadata,
- pMetadata1 = nameInfo.nameMetadata,
- pMetadata2 = eventTypes.typeMetadata)
- {
- descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
- descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
- descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
-
-#if (!ES_BUILD_PCL && !PROJECTN)
- System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
-#endif
- try
- {
- DataCollector.ThreadInstance.Enable(
- scratch,
- eventTypes.scratchSize,
- descriptors + 3,
- eventTypes.dataCount,
- pins,
- pinCount);
-
- for (int i = 0; i < eventTypes.typeInfos.Length; i++)
- {
- var info = eventTypes.typeInfos[i];
- info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i]));
- }
-
- this.WriteEventRaw(
- eventName,
- ref descriptor,
- activityID,
- childActivityID,
- (int)(DataCollector.ThreadInstance.Finish() - descriptors),
- (IntPtr)descriptors);
- }
- finally
- {
- this.WriteCleanup(pins, pinCount);
- }
- }
-#endif // FEATURE_MANAGED_ETW
- }
-
- /// <summary>
- /// Writes an extended event, where the values of the event have already
- /// been serialized in "data".
- /// </summary>
- /// <param name="eventName">
- /// The name for the event. If null, the name from eventTypes is used.
- /// (Note that providing the event name via the name parameter is slightly
- /// less efficient than using the name from eventTypes.)
- /// </param>
- /// <param name="options">
- /// Optional overrides for the event, such as the level, keyword, opcode,
- /// activityId, and relatedActivityId. Any settings not specified by options
- /// are obtained from eventTypes.
- /// </param>
- /// <param name="eventTypes">
- /// Information about the event and the types of the values in the event.
- /// Must not be null. Note that the eventTypes object should be created once and
- /// saved. It should not be recreated for each event.
- /// </param>
- /// <param name="activityID">
- /// A pointer to the activity ID GUID to log
- /// </param>
- /// <param name="childActivityID">
- /// A pointer to the child activity ID to log (can be null)
- /// </param>
- /// <param name="data">
- /// The previously serialized values to include in the event. Must not be null.
- /// The number and types of the values must match the number and types of the
- /// fields described by the eventTypes parameter.
- /// </param>
- internal unsafe void WriteMultiMerge(
- string eventName,
- ref EventSourceOptions options,
- TraceLoggingEventTypes eventTypes,
- Guid* activityID,
- Guid* childActivityID,
- EventData* data)
- {
-#if FEATURE_MANAGED_ETW
- if (!this.IsEnabled())
- {
- return;
- }
-
- fixed (EventSourceOptions* pOptions = &options)
- {
- EventDescriptor descriptor;
- var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
- if (nameInfo == null)
- {
- return;
- }
-
- // We make a descriptor for each EventData, and because we morph strings to counted strings
- // we may have 2 for each arg, so we allocate enough for this.
- var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
-
- fixed (byte*
- pMetadata0 = this.providerMetadata,
- pMetadata1 = nameInfo.nameMetadata,
- pMetadata2 = eventTypes.typeMetadata)
- {
- descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
- descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
- descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
- int numDescrs = 3;
-
- for (int i = 0; i < eventTypes.typeInfos.Length; i++)
- {
- // Until M3, we need to morph strings to a counted representation
- // When TDH supports null terminated strings, we can remove this.
- if (eventTypes.typeInfos[i].DataType == typeof(string))
- {
- // Write out the size of the string
- descriptors[numDescrs].m_Ptr = (long)&descriptors[numDescrs + 1].m_Size;
- descriptors[numDescrs].m_Size = 2;
- numDescrs++;
-
- descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
- descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
- numDescrs++;
- }
- else
- {
- descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
- descriptors[numDescrs].m_Size = data[i].m_Size;
-
- // old conventions for bool is 4 bytes, but meta-data assumes 1.
- if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
- descriptors[numDescrs].m_Size = 1;
-
- numDescrs++;
- }
- }
-
- this.WriteEventRaw(
- eventName,
- ref descriptor,
- activityID,
- childActivityID,
- numDescrs,
- (IntPtr)descriptors);
- }
- }
-#endif // FEATURE_MANAGED_ETW
- }
-
- private unsafe void WriteImpl(
- string eventName,
- ref EventSourceOptions options,
- object data,
- Guid* pActivityId,
- Guid* pRelatedActivityId,
- TraceLoggingEventTypes eventTypes)
- {
- try
- {
- fixed (EventSourceOptions* pOptions = &options)
- {
- EventDescriptor descriptor;
- options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
- var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
- if (nameInfo == null)
- {
- return;
- }
-
-#if FEATURE_MANAGED_ETW
- var pinCount = eventTypes.pinCount;
- var scratch = stackalloc byte[eventTypes.scratchSize];
- var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
- var pins = stackalloc GCHandle[pinCount];
-
- fixed (byte*
- pMetadata0 = this.providerMetadata,
- pMetadata1 = nameInfo.nameMetadata,
- pMetadata2 = eventTypes.typeMetadata)
- {
- descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
- descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
- descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
-#endif // FEATURE_MANAGED_ETW
-
-#if (!ES_BUILD_PCL && !PROJECTN)
- System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
-#endif
- EventOpcode opcode = (EventOpcode)descriptor.Opcode;
-
- Guid activityId = Guid.Empty;
- Guid relatedActivityId = Guid.Empty;
- if (pActivityId == null && pRelatedActivityId == null &&
- ((options.ActivityOptions & EventActivityOptions.Disable) == 0))
- {
- if (opcode == EventOpcode.Start)
- {
- m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
- }
- else if (opcode == EventOpcode.Stop)
- {
- m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
- }
- if (activityId != Guid.Empty)
- pActivityId = &activityId;
- if (relatedActivityId != Guid.Empty)
- pRelatedActivityId = &relatedActivityId;
- }
-
- try
- {
-#if FEATURE_MANAGED_ETW
- DataCollector.ThreadInstance.Enable(
- scratch,
- eventTypes.scratchSize,
- descriptors + 3,
- eventTypes.dataCount,
- pins,
- pinCount);
-
- var info = eventTypes.typeInfos[0];
- info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data));
-
- this.WriteEventRaw(
- eventName,
- ref descriptor,
- pActivityId,
- pRelatedActivityId,
- (int)(DataCollector.ThreadInstance.Finish() - descriptors),
- (IntPtr)descriptors);
-#endif // FEATURE_MANAGED_ETW
-
- // TODO enable filtering for listeners.
- if (m_Dispatchers != null)
- {
- var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data));
- WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
- }
-
- }
- catch (Exception ex)
- {
- if (ex is EventSourceException)
- throw;
- else
- ThrowEventSourceException(eventName, ex);
- }
-#if FEATURE_MANAGED_ETW
- finally
- {
- this.WriteCleanup(pins, pinCount);
- }
- }
-#endif // FEATURE_MANAGED_ETW
- }
- }
- catch (Exception ex)
- {
- if (ex is EventSourceException)
- throw;
- else
- ThrowEventSourceException(eventName, ex);
- }
- }
-
- private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
- {
- EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
- eventCallbackArgs.EventName = eventName;
- eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level;
- eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords;
- eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode;
- eventCallbackArgs.m_tags = tags;
-
- // Self described events do not have an id attached. We mark it internally with -1.
- eventCallbackArgs.EventId = -1;
- if (pActivityId != null)
- eventCallbackArgs.RelatedActivityId = *pActivityId;
-
- if (payload != null)
- {
- eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
- eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
- }
-
- DispatchToAllListeners(-1, pActivityId, eventCallbackArgs);
- }
-
-#if (!ES_BUILD_PCL && !PROJECTN)
- [System.Runtime.ConstrainedExecution.ReliabilityContract(
- System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
- System.Runtime.ConstrainedExecution.Cer.Success)]
-#endif
- [NonEvent]
- private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
- {
- DataCollector.ThreadInstance.Disable();
-
- for (int i = 0; i != cPins; i++)
- {
- if (IntPtr.Zero != (IntPtr)pPins[i])
- {
- pPins[i].Free();
- }
- }
- }
-
- private void InitializeProviderMetadata()
- {
-#if FEATURE_MANAGED_ETW
- if (m_traits != null)
- {
- List<byte> traitMetaData = new List<byte>(100);
- for (int i = 0; i < m_traits.Length - 1; i += 2)
- {
- if (m_traits[i].StartsWith("ETW_", StringComparison.Ordinal))
- {
- string etwTrait = m_traits[i].Substring(4);
- byte traitNum;
- if (!byte.TryParse(etwTrait, out traitNum))
- {
- if (etwTrait == "GROUP")
- {
- traitNum = 1;
- }
- else
- {
- throw new ArgumentException(Resources.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
- }
- }
- string value = m_traits[i + 1];
- int lenPos = traitMetaData.Count;
- traitMetaData.Add(0); // Emit size (to be filled in later)
- traitMetaData.Add(0);
- traitMetaData.Add(traitNum); // Emit Trait number
- var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
- traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
- traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
- }
- }
- providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
- int startPos = providerMetadata.Length - traitMetaData.Count;
- foreach (var b in traitMetaData)
- providerMetadata[startPos++] = b;
- }
- else
- providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
-#endif //FEATURE_MANAGED_ETW
- }
-
- private static int AddValueToMetaData(List<byte> metaData, string value)
- {
- if (value.Length == 0)
- return 0;
-
- int startPos = metaData.Count;
- char firstChar = value[0];
-
- if (firstChar == '@')
- metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
- else if (firstChar == '{')
- metaData.AddRange(new Guid(value).ToByteArray());
- else if (firstChar == '#')
- {
- for (int i = 1; i < value.Length; i++)
- {
- if (value[i] != ' ') // Skip spaces between bytes.
- {
- if (!(i + 1 < value.Length))
- {
- throw new ArgumentException(Resources.GetResourceString("EvenHexDigits"), "traits");
- }
- metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
- i++;
- }
- }
- }
- else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation).
- {
- metaData.AddRange(Encoding.UTF8.GetBytes(value));
- }
- else
- {
- throw new ArgumentException(Resources.GetResourceString("IllegalValue", value), "traits");
- }
-
- return metaData.Count - startPos;
- }
-
- /// <summary>
- /// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
- /// </summary>
- private static int HexDigit(char c)
- {
- if ('0' <= c && c <= '9')
- {
- return (c - '0');
- }
- if ('a' <= c)
- {
- c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case
- }
- if ('A' <= c && c <= 'F')
- {
- return (c - 'A' + 10);
- }
-
- throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits");
- }
-
- private NameInfo UpdateDescriptor(
- string name,
- TraceLoggingEventTypes eventInfo,
- ref EventSourceOptions options,
- out EventDescriptor descriptor)
- {
- NameInfo nameInfo = null;
- int identity = 0;
- byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
- ? options.level
- : eventInfo.level;
- byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
- ? options.opcode
- : eventInfo.opcode;
- EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
- ? options.tags
- : eventInfo.Tags;
- EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
- ? options.keywords
- : eventInfo.keywords;
-
- if (this.IsEnabled((EventLevel)level, keywords))
- {
- nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
- identity = nameInfo.identity;
- }
-
- descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
- return nameInfo;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTraits.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTraits.cs
deleted file mode 100644
index e808a8823c..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTraits.cs
+++ /dev/null
@@ -1,28 +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;
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// Tags are flags that are not interpreted by EventSource but are passed along
- /// to the EventListener. The EventListener determines the semantics of the flags.
- /// </summary>
- [Flags]
- public enum EventTags
- {
- /// <summary>
- /// No special traits are added to the event.
- /// </summary>
- None = 0,
-
- /* Bits below 0x10000 are available for any use by the provider. */
- /* Bits at or above 0x10000 are reserved for definition by Microsoft. */
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
deleted file mode 100644
index c2239671bb..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingEventTypes.cs
+++ /dev/null
@@ -1,262 +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.Collections.Generic;
-using Interlocked = System.Threading.Interlocked;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: Used when calling EventSource.WriteMultiMerge.
- /// Stores the type information to use when writing the event fields.
- /// </summary>
- public class TraceLoggingEventTypes
- {
- internal readonly TraceLoggingTypeInfo[] typeInfos;
- internal readonly string name;
- internal readonly EventTags tags;
- internal readonly byte level;
- internal readonly byte opcode;
- internal readonly EventKeywords keywords;
- internal readonly byte[] typeMetadata;
- internal readonly int scratchSize;
- internal readonly int dataCount;
- internal readonly int pinCount;
- private ConcurrentSet<KeyValuePair<string, EventTags>, NameInfo> nameInfos;
-
- /// <summary>
- /// Initializes a new instance of TraceLoggingEventTypes corresponding
- /// to the name, flags, and types provided. Always uses the default
- /// TypeInfo for each Type.
- /// </summary>
- /// <param name="name">
- /// The name to use when the name parameter passed to
- /// EventSource.Write is null. This value must not be null.
- /// </param>
- /// <param name="tags">
- /// Tags to add to the event if the tags are not set via options.
- /// </param>
- /// <param name="types">
- /// The types of the fields in the event. This value must not be null.
- /// </param>
- internal TraceLoggingEventTypes(
- string name,
- EventTags tags,
- params Type[] types)
- : this(tags, name, MakeArray(types))
- {
- return;
- }
-
- /// <summary>
- /// Returns a new instance of TraceLoggingEventInfo corresponding to the name,
- /// flags, and typeInfos provided.
- /// </summary>
- /// <param name="name">
- /// The name to use when the name parameter passed to
- /// EventSource.Write is null. This value must not be null.
- /// </param>
- /// <param name="tags">
- /// Tags to add to the event if the tags are not set via options.
- /// </param>
- /// <param name="typeInfos">
- /// The types of the fields in the event. This value must not be null.
- /// </param>
- /// <returns>
- /// An instance of TraceLoggingEventInfo with DefaultName set to the specified name
- /// and with the specified typeInfos.
- /// </returns>
- internal TraceLoggingEventTypes(
- string name,
- EventTags tags,
- params TraceLoggingTypeInfo[] typeInfos)
- : this(tags, name, MakeArray(typeInfos))
- {
- return;
- }
-
- internal TraceLoggingEventTypes(
- string name,
- EventTags tags,
- System.Reflection.ParameterInfo[] paramInfos)
- {
- if (name == null)
- {
- throw new ArgumentNullException(nameof(name));
- }
-
- Contract.EndContractBlock();
-
- this.typeInfos = MakeArray(paramInfos);
- this.name = name;
- this.tags = tags;
- this.level = Statics.DefaultLevel;
-
- var collector = new TraceLoggingMetadataCollector();
- for (int i = 0; i < typeInfos.Length; ++i)
- {
- var typeInfo = typeInfos[i];
- this.level = Statics.Combine((int)typeInfo.Level, this.level);
- this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode);
- this.keywords |= typeInfo.Keywords;
- var paramName = paramInfos[i].Name;
- if (Statics.ShouldOverrideFieldName(paramName))
- {
- paramName = typeInfo.Name;
- }
- typeInfo.WriteMetadata(collector, paramName, EventFieldFormat.Default);
- }
-
- this.typeMetadata = collector.GetMetadata();
- this.scratchSize = collector.ScratchSize;
- this.dataCount = collector.DataCount;
- this.pinCount = collector.PinCount;
- }
-
- private TraceLoggingEventTypes(
- EventTags tags,
- string defaultName,
- TraceLoggingTypeInfo[] typeInfos)
- {
- if (defaultName == null)
- {
- throw new ArgumentNullException(nameof(defaultName));
- }
-
- Contract.EndContractBlock();
-
- this.typeInfos = typeInfos;
- this.name = defaultName;
- this.tags = tags;
- this.level = Statics.DefaultLevel;
-
- var collector = new TraceLoggingMetadataCollector();
- foreach (var typeInfo in typeInfos)
- {
- this.level = Statics.Combine((int)typeInfo.Level, this.level);
- this.opcode = Statics.Combine((int)typeInfo.Opcode, this.opcode);
- this.keywords |= typeInfo.Keywords;
- typeInfo.WriteMetadata(collector, null, EventFieldFormat.Default);
- }
-
- this.typeMetadata = collector.GetMetadata();
- this.scratchSize = collector.ScratchSize;
- this.dataCount = collector.DataCount;
- this.pinCount = collector.PinCount;
- }
-
- /// <summary>
- /// Gets the default name that will be used for events with this descriptor.
- /// </summary>
- internal string Name
- {
- get { return this.name; }
- }
-
- /// <summary>
- /// Gets the default level that will be used for events with this descriptor.
- /// </summary>
- internal EventLevel Level
- {
- get { return (EventLevel)this.level; }
- }
-
- /// <summary>
- /// Gets the default opcode that will be used for events with this descriptor.
- /// </summary>
- internal EventOpcode Opcode
- {
- get { return (EventOpcode)this.opcode; }
- }
-
- /// <summary>
- /// Gets the default set of keywords that will added to events with this descriptor.
- /// </summary>
- internal EventKeywords Keywords
- {
- get { return (EventKeywords)this.keywords; }
- }
-
- /// <summary>
- /// Gets the default tags that will be added events with this descriptor.
- /// </summary>
- internal EventTags Tags
- {
- get { return this.tags; }
- }
-
- internal NameInfo GetNameInfo(string name, EventTags tags)
- {
- var ret = this.nameInfos.TryGet(new KeyValuePair<string, EventTags>(name, tags));
- if (ret == null)
- {
- ret = this.nameInfos.GetOrAdd(new NameInfo(name, tags, this.typeMetadata.Length));
- }
-
- return ret;
- }
-
- private TraceLoggingTypeInfo[] MakeArray(System.Reflection.ParameterInfo[] paramInfos)
- {
- if (paramInfos == null)
- {
- throw new ArgumentNullException(nameof(paramInfos));
- }
-
- Contract.EndContractBlock();
-
- var recursionCheck = new List<Type>(paramInfos.Length);
- var result = new TraceLoggingTypeInfo[paramInfos.Length];
- for (int i = 0; i < paramInfos.Length; ++i)
- {
- result[i] = TraceLoggingTypeInfo.GetInstance(paramInfos[i].ParameterType, recursionCheck);
- }
-
- return result;
- }
-
- private static TraceLoggingTypeInfo[] MakeArray(Type[] types)
- {
- if (types == null)
- {
- throw new ArgumentNullException(nameof(types));
- }
-
- Contract.EndContractBlock();
-
- var recursionCheck = new List<Type>(types.Length);
- var result = new TraceLoggingTypeInfo[types.Length];
- for (int i = 0; i < types.Length; i++)
- {
- result[i] = TraceLoggingTypeInfo.GetInstance(types[i], recursionCheck);
- }
-
- return result;
- }
-
- private static TraceLoggingTypeInfo[] MakeArray(
- TraceLoggingTypeInfo[] typeInfos)
- {
- if (typeInfos == null)
- {
- throw new ArgumentNullException(nameof(typeInfos));
- }
-
- Contract.EndContractBlock();
-
- return (TraceLoggingTypeInfo[])typeInfos.Clone(); ;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
deleted file mode 100644
index 41225c8626..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingMetadataCollector.cs
+++ /dev/null
@@ -1,370 +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.Collections.Generic;
-
-#if ES_BUILD_STANDALONE
-using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: used when implementing a custom TraceLoggingTypeInfo.
- /// An instance of this type is provided to the TypeInfo.WriteMetadata method.
- /// </summary>
- internal class TraceLoggingMetadataCollector
- {
- private readonly Impl impl;
- private readonly FieldMetadata currentGroup;
- private int bufferedArrayFieldCount = int.MinValue;
-
- /// <summary>
- /// Creates a root-level collector.
- /// </summary>
- internal TraceLoggingMetadataCollector()
- {
- this.impl = new Impl();
- }
-
- /// <summary>
- /// Creates a collector for a group.
- /// </summary>
- /// <param name="other">Parent collector</param>
- /// <param name="group">The field that starts the group</param>
- private TraceLoggingMetadataCollector(
- TraceLoggingMetadataCollector other,
- FieldMetadata group)
- {
- this.impl = other.impl;
- this.currentGroup = group;
- }
-
- /// <summary>
- /// The field tags to be used for the next field.
- /// This will be reset to None each time a field is written.
- /// </summary>
- internal EventFieldTags Tags
- {
- get;
- set;
- }
-
- internal int ScratchSize
- {
- get { return this.impl.scratchSize; }
- }
-
- internal int DataCount
- {
- get { return this.impl.dataCount; }
- }
-
- internal int PinCount
- {
- get { return this.impl.pinCount; }
- }
-
- private bool BeginningBufferedArray
- {
- get { return this.bufferedArrayFieldCount == 0; }
- }
-
- /// <summary>
- /// Call this method to add a group to the event and to return
- /// a new metadata collector that can be used to add fields to the
- /// group. After all of the fields in the group have been written,
- /// switch back to the original metadata collector to add fields
- /// outside of the group.
- /// Special-case: if name is null, no group is created, and AddGroup
- /// returns the original metadata collector. This is useful when
- /// adding the top-level group for an event.
- /// Note: do not use the original metadata collector while the group's
- /// metadata collector is in use, and do not use the group's metadata
- /// collector after switching back to the original.
- /// </summary>
- /// <param name="name">
- /// The name of the group. If name is null, the call to AddGroup is a
- /// no-op (collector.AddGroup(null) returns collector).
- /// </param>
- /// <returns>
- /// A new metadata collector that can be used to add fields to the group.
- /// </returns>
- public TraceLoggingMetadataCollector AddGroup(string name)
- {
- TraceLoggingMetadataCollector result = this;
-
- if (name != null || // Normal.
- this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception.
- {
- var newGroup = new FieldMetadata(
- name,
- TraceLoggingDataType.Struct,
- this.Tags,
- this.BeginningBufferedArray);
- this.AddField(newGroup);
- result = new TraceLoggingMetadataCollector(this, newGroup);
- }
-
- return result;
- }
-
- /// <summary>
- /// Adds a scalar field to an event.
- /// </summary>
- /// <param name="name">
- /// The name to use for the added field. This value must not be null.
- /// </param>
- /// <param name="type">
- /// The type code for the added field. This must be a fixed-size type
- /// (e.g. string types are not supported).
- /// </param>
- public void AddScalar(string name, TraceLoggingDataType type)
- {
- int size;
- switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
- {
- case TraceLoggingDataType.Int8:
- case TraceLoggingDataType.UInt8:
- case TraceLoggingDataType.Char8:
- size = 1;
- break;
- case TraceLoggingDataType.Int16:
- case TraceLoggingDataType.UInt16:
- case TraceLoggingDataType.Char16:
- size = 2;
- break;
- case TraceLoggingDataType.Int32:
- case TraceLoggingDataType.UInt32:
- case TraceLoggingDataType.HexInt32:
- case TraceLoggingDataType.Float:
- case TraceLoggingDataType.Boolean32:
- size = 4;
- break;
- case TraceLoggingDataType.Int64:
- case TraceLoggingDataType.UInt64:
- case TraceLoggingDataType.HexInt64:
- case TraceLoggingDataType.Double:
- case TraceLoggingDataType.FileTime:
- size = 8;
- break;
- case TraceLoggingDataType.Guid:
- case TraceLoggingDataType.SystemTime:
- size = 16;
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(type));
- }
-
- this.impl.AddScalar(size);
- this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
- }
-
- /// <summary>
- /// Adds a binary-format field to an event.
- /// Compatible with core types: Binary, CountedUtf16String, CountedMbcsString.
- /// Compatible with dataCollector methods: AddBinary(string), AddArray(Any8bitType[]).
- /// </summary>
- /// <param name="name">
- /// The name to use for the added field. This value must not be null.
- /// </param>
- /// <param name="type">
- /// The type code for the added field. This must be a Binary or CountedString type.
- /// </param>
- public void AddBinary(string name, TraceLoggingDataType type)
- {
- switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
- {
- case TraceLoggingDataType.Binary:
- case TraceLoggingDataType.CountedMbcsString:
- case TraceLoggingDataType.CountedUtf16String:
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(type));
- }
-
- this.impl.AddScalar(2);
- this.impl.AddNonscalar();
- this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray));
- }
-
- /// <summary>
- /// Adds an array field to an event.
- /// </summary>
- /// <param name="name">
- /// The name to use for the added field. This value must not be null.
- /// </param>
- /// <param name="type">
- /// The type code for the added field. This must be a fixed-size type
- /// or a string type. In the case of a string type, this adds an array
- /// of characters, not an array of strings.
- /// </param>
- public void AddArray(string name, TraceLoggingDataType type)
- {
- switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask))
- {
- case TraceLoggingDataType.Utf16String:
- case TraceLoggingDataType.MbcsString:
- case TraceLoggingDataType.Int8:
- case TraceLoggingDataType.UInt8:
- case TraceLoggingDataType.Int16:
- case TraceLoggingDataType.UInt16:
- case TraceLoggingDataType.Int32:
- case TraceLoggingDataType.UInt32:
- case TraceLoggingDataType.Int64:
- case TraceLoggingDataType.UInt64:
- case TraceLoggingDataType.Float:
- case TraceLoggingDataType.Double:
- case TraceLoggingDataType.Boolean32:
- case TraceLoggingDataType.Guid:
- case TraceLoggingDataType.FileTime:
- case TraceLoggingDataType.HexInt32:
- case TraceLoggingDataType.HexInt64:
- case TraceLoggingDataType.Char16:
- case TraceLoggingDataType.Char8:
- break;
- default:
- throw new ArgumentOutOfRangeException(nameof(type));
- }
-
- if (this.BeginningBufferedArray)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
- }
-
- this.impl.AddScalar(2);
- this.impl.AddNonscalar();
- this.AddField(new FieldMetadata(name, type, this.Tags, true));
- }
-
- public void BeginBufferedArray()
- {
- if (this.bufferedArrayFieldCount >= 0)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedNestedArraysEnums"));
- }
-
- this.bufferedArrayFieldCount = 0;
- this.impl.BeginBuffered();
- }
-
- public void EndBufferedArray()
- {
- if (this.bufferedArrayFieldCount != 1)
- {
- throw new InvalidOperationException(Resources.GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo"));
- }
-
- this.bufferedArrayFieldCount = int.MinValue;
- this.impl.EndBuffered();
- }
-
- /// <summary>
- /// Adds a custom-serialized field to an event.
- /// </summary>
- /// <param name="name">
- /// The name to use for the added field. This value must not be null.
- /// </param>
- /// <param name="type">The encoding type for the field.</param>
- /// <param name="metadata">Additional information needed to decode the field, if any.</param>
- public void AddCustom(string name, TraceLoggingDataType type, byte[] metadata)
- {
- if (this.BeginningBufferedArray)
- {
- throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedCustomSerializedData"));
- }
-
- this.impl.AddScalar(2);
- this.impl.AddNonscalar();
- this.AddField(new FieldMetadata(
- name,
- type,
- this.Tags,
- metadata));
- }
-
- internal byte[] GetMetadata()
- {
- var size = this.impl.Encode(null);
- var metadata = new byte[size];
- this.impl.Encode(metadata);
- return metadata;
- }
-
- private void AddField(FieldMetadata fieldMetadata)
- {
- this.Tags = EventFieldTags.None;
- this.bufferedArrayFieldCount++;
- this.impl.fields.Add(fieldMetadata);
-
- if (this.currentGroup != null)
- {
- this.currentGroup.IncrementStructFieldCount();
- }
- }
-
- private class Impl
- {
- internal readonly List<FieldMetadata> fields = new List<FieldMetadata>();
- internal short scratchSize;
- internal sbyte dataCount;
- internal sbyte pinCount;
- private int bufferNesting;
- private bool scalar;
-
- public void AddScalar(int size)
- {
- if (this.bufferNesting == 0)
- {
- if (!this.scalar)
- {
- this.dataCount = checked((sbyte)(this.dataCount + 1));
- }
-
- this.scalar = true;
- this.scratchSize = checked((short)(this.scratchSize + size));
- }
- }
-
- public void AddNonscalar()
- {
- if (this.bufferNesting == 0)
- {
- this.scalar = false;
- this.pinCount = checked((sbyte)(this.pinCount + 1));
- this.dataCount = checked((sbyte)(this.dataCount + 1));
- }
- }
-
- public void BeginBuffered()
- {
- if (this.bufferNesting == 0)
- {
- this.AddNonscalar();
- }
-
- this.bufferNesting++;
- }
-
- public void EndBuffered()
- {
- this.bufferNesting--;
- }
-
- public int Encode(byte[] metadata)
- {
- int size = 0;
-
- foreach (var field in this.fields)
- {
- field.Encode(ref size, metadata);
- }
-
- return size;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
deleted file mode 100644
index d68e106b0b..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TraceLoggingTypeInfo.cs
+++ /dev/null
@@ -1,209 +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.Collections.Generic;
-
-#if !ES_BUILD_AGAINST_DOTNET_V35
-using Contract = System.Diagnostics.Contracts.Contract;
-#else
-using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: used when implementing a custom TraceLoggingTypeInfo.
- /// Non-generic base class for TraceLoggingTypeInfo&lt;DataType>. Do not derive
- /// from this class. Instead, derive from TraceLoggingTypeInfo&lt;DataType>.
- /// </summary>
- internal abstract class TraceLoggingTypeInfo
- {
- private readonly string name;
- private readonly EventKeywords keywords;
- private readonly EventLevel level = (EventLevel)(-1);
- private readonly EventOpcode opcode = (EventOpcode)(-1);
- private readonly EventTags tags;
- private readonly Type dataType;
- private readonly Func<object, PropertyValue> propertyValueFactory;
-
- internal TraceLoggingTypeInfo(Type dataType)
- {
- if (dataType == null)
- {
- throw new ArgumentNullException(nameof(dataType));
- }
-
- Contract.EndContractBlock();
-
- this.name = dataType.Name;
- this.dataType = dataType;
- this.propertyValueFactory = PropertyValue.GetFactory(dataType);
- }
-
- internal TraceLoggingTypeInfo(
- Type dataType,
- string name,
- EventLevel level,
- EventOpcode opcode,
- EventKeywords keywords,
- EventTags tags)
- {
- if (dataType == null)
- {
- throw new ArgumentNullException(nameof(dataType));
- }
-
- if (name == null)
- {
- throw new ArgumentNullException(nameof(name));
- }
-
- Contract.EndContractBlock();
-
- Statics.CheckName(name);
-
- this.name = name;
- this.keywords = keywords;
- this.level = level;
- this.opcode = opcode;
- this.tags = tags;
- this.dataType = dataType;
- this.propertyValueFactory = PropertyValue.GetFactory(dataType);
- }
-
- /// <summary>
- /// Gets the name to use for the event if this type is the top-level type,
- /// or the name to use for an implicitly-named field.
- /// Never null.
- /// </summary>
- public string Name
- {
- get { return this.name; }
- }
-
- /// <summary>
- /// Gets the event level associated with this type. Any value in the range 0..255
- /// is an associated event level. Any value outside the range 0..255 is invalid and
- /// indicates that this type has no associated event level.
- /// </summary>
- public EventLevel Level
- {
- get { return this.level; }
- }
-
- /// <summary>
- /// Gets the event opcode associated with this type. Any value in the range 0..255
- /// is an associated event opcode. Any value outside the range 0..255 is invalid and
- /// indicates that this type has no associated event opcode.
- /// </summary>
- public EventOpcode Opcode
- {
- get { return this.opcode; }
- }
-
- /// <summary>
- /// Gets the keyword(s) associated with this type.
- /// </summary>
- public EventKeywords Keywords
- {
- get { return this.keywords; }
- }
-
- /// <summary>
- /// Gets the event tags associated with this type.
- /// </summary>
- public EventTags Tags
- {
- get { return this.tags; }
- }
-
- internal Type DataType
- {
- get { return this.dataType; }
- }
-
- internal Func<object, PropertyValue> PropertyValueFactory
- {
- get { return this.propertyValueFactory; }
- }
-
- /// <summary>
- /// When overridden by a derived class, writes the metadata (schema) for
- /// this type. Note that the sequence of operations in WriteMetadata should be
- /// essentially identical to the sequence of operations in
- /// WriteData/WriteObjectData. Otherwise, the metadata and data will not match,
- /// which may cause trouble when decoding the event.
- /// </summary>
- /// <param name="collector">
- /// The object that collects metadata for this object's type. Metadata is written
- /// by calling methods on the collector object. Note that if the type contains
- /// sub-objects, the implementation of this method may need to call the
- /// WriteMetadata method for the type of the sub-object, e.g. by calling
- /// TraceLoggingTypeInfo&lt;SubType&gt;.Instance.WriteMetadata(...).
- /// </param>
- /// <param name="name">
- /// The name of the property that contains an object of this type, or null if this
- /// object is being written as a top-level object of an event. Typical usage
- /// is to pass this value to collector.AddGroup.
- /// </param>
- /// <param name="format">
- /// The format attribute for the field that contains an object of this type.
- /// </param>
- public abstract void WriteMetadata(
- TraceLoggingMetadataCollector collector,
- string name,
- EventFieldFormat format);
-
- /// <summary>
- /// Refer to TraceLoggingTypeInfo.WriteObjectData for information about this
- /// method.
- /// </summary>
- /// <param name="collector">
- /// Refer to TraceLoggingTypeInfo.WriteObjectData for information about this
- /// method.
- /// </param>
- /// <param name="value">
- /// Refer to TraceLoggingTypeInfo.WriteObjectData for information about this
- /// method.
- /// </param>
- public abstract void WriteData(
- TraceLoggingDataCollector collector,
- PropertyValue value);
-
- /// <summary>
- /// Fetches the event parameter data for internal serialization.
- /// </summary>
- /// <param name="value"></param>
- /// <returns></returns>
- public virtual object GetData(object value)
- {
- return value;
- }
-
- [ThreadStatic] // per-thread cache to avoid synchronization
- private static Dictionary<Type, TraceLoggingTypeInfo> threadCache;
-
- public static TraceLoggingTypeInfo GetInstance(Type type, List<Type> recursionCheck)
- {
- var cache = threadCache ?? (threadCache = new Dictionary<Type, TraceLoggingTypeInfo>());
-
- TraceLoggingTypeInfo instance;
- if (!cache.TryGetValue(type, out instance))
- {
- if (recursionCheck == null)
- recursionCheck = new List<Type>();
- var recursionCheckCount = recursionCheck.Count;
- instance = Statics.CreateDefaultTypeInfo(type, recursionCheck);
- cache[type] = instance;
- recursionCheck.RemoveRange(recursionCheckCount, recursionCheck.Count - recursionCheckCount);
- }
- return instance;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TypeAnalysis.cs b/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TypeAnalysis.cs
deleted file mode 100644
index 42cdde5f6a..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/TraceLogging/TypeAnalysis.cs
+++ /dev/null
@@ -1,103 +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.Collections.Generic;
-using System.Reflection;
-
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- /// <summary>
- /// TraceLogging: stores the per-type information obtained by reflecting over a type.
- /// </summary>
- internal sealed class TypeAnalysis
- {
- internal readonly PropertyAnalysis[] properties;
- internal readonly string name;
- internal readonly EventKeywords keywords;
- internal readonly EventLevel level = (EventLevel)(-1);
- internal readonly EventOpcode opcode = (EventOpcode)(-1);
- internal readonly EventTags tags;
-
- public TypeAnalysis(
- Type dataType,
- EventDataAttribute eventAttrib,
- List<Type> recursionCheck)
- {
- var propertyInfos = Statics.GetProperties(dataType);
- var propertyList = new List<PropertyAnalysis>();
-
- foreach (var propertyInfo in propertyInfos)
- {
- if (Statics.HasCustomAttribute(propertyInfo, typeof(EventIgnoreAttribute)))
- {
- continue;
- }
-
- if (!propertyInfo.CanRead ||
- propertyInfo.GetIndexParameters().Length != 0)
- {
- continue;
- }
-
- MethodInfo getterInfo = Statics.GetGetMethod(propertyInfo);
- if (getterInfo == null)
- {
- continue;
- }
-
- if (getterInfo.IsStatic || !getterInfo.IsPublic)
- {
- continue;
- }
-
- var propertyType = propertyInfo.PropertyType;
- var propertyTypeInfo = TraceLoggingTypeInfo.GetInstance(propertyType, recursionCheck);
- var fieldAttribute = Statics.GetCustomAttribute<EventFieldAttribute>(propertyInfo);
-
- string propertyName =
- fieldAttribute != null && fieldAttribute.Name != null
- ? fieldAttribute.Name
- : Statics.ShouldOverrideFieldName(propertyInfo.Name)
- ? propertyTypeInfo.Name
- : propertyInfo.Name;
- propertyList.Add(new PropertyAnalysis(
- propertyName,
- propertyInfo,
- propertyTypeInfo,
- fieldAttribute));
- }
-
- this.properties = propertyList.ToArray();
-
- foreach (var property in this.properties)
- {
- var typeInfo = property.typeInfo;
- this.level = (EventLevel)Statics.Combine((int)typeInfo.Level, (int)this.level);
- this.opcode = (EventOpcode)Statics.Combine((int)typeInfo.Opcode, (int)this.opcode);
- this.keywords |= typeInfo.Keywords;
- this.tags |= typeInfo.Tags;
- }
-
- if (eventAttrib != null)
- {
- this.level = (EventLevel)Statics.Combine((int)eventAttrib.Level, (int)this.level);
- this.opcode = (EventOpcode)Statics.Combine((int)eventAttrib.Opcode, (int)this.opcode);
- this.keywords |= eventAttrib.Keywords;
- this.tags |= eventAttrib.Tags;
- this.name = eventAttrib.Name;
- }
-
- if (this.name == null)
- {
- this.name = dataType.Name;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs b/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs
deleted file mode 100644
index c93e745173..0000000000
--- a/src/mscorlib/src/System/Diagnostics/Eventing/Winmeta.cs
+++ /dev/null
@@ -1,196 +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:
-** Contains eventing constants defined by the Windows
-** environment.
-**
-============================================================*/
-#if ES_BUILD_STANDALONE
-#define FEATURE_MANAGED_ETW_CHANNELS
-#endif
-
-#if ES_BUILD_STANDALONE
-namespace Microsoft.Diagnostics.Tracing
-#else
-namespace System.Diagnostics.Tracing
-#endif
-{
- using System;
-
- /// <summary>
- /// WindowsEventLevel. Custom values must be in the range from 16 through 255
- /// </summary>
- public enum EventLevel
- {
- /// <summary>
- /// Log always
- /// </summary>
- LogAlways = 0,
- /// <summary>
- /// Only critical errors
- /// </summary>
- Critical,
- /// <summary>
- /// All errors, including previous levels
- /// </summary>
- Error,
- /// <summary>
- /// All warnings, including previous levels
- /// </summary>
- Warning,
- /// <summary>
- /// All informational events, including previous levels
- /// </summary>
- Informational,
- /// <summary>
- /// All events, including previous levels
- /// </summary>
- Verbose
- }
- /// <summary>
- /// WindowsEventTask. Custom values must be in the range from 1 through 65534
- /// </summary>
-#if (!ES_BUILD_STANDALONE && !PROJECTN)
- [System.Runtime.CompilerServices.FriendAccessAllowed]
-#endif
- public enum EventTask
- {
- /// <summary>
- /// Undefined task
- /// </summary>
- None = 0
- }
- /// <summary>
- /// EventOpcode. Custom values must be in the range from 11 through 239
- /// </summary>
-#if (!ES_BUILD_STANDALONE && !PROJECTN)
- [System.Runtime.CompilerServices.FriendAccessAllowed]
-#endif
- public enum EventOpcode
- {
- /// <summary>
- /// An informational event
- /// </summary>
- Info = 0,
- /// <summary>
- /// An activity start event
- /// </summary>
- Start,
- /// <summary>
- /// An activity end event
- /// </summary>
- Stop,
- /// <summary>
- /// A trace collection start event
- /// </summary>
- DataCollectionStart,
- /// <summary>
- /// A trace collection end event
- /// </summary>
- DataCollectionStop,
- /// <summary>
- /// An extensional event
- /// </summary>
- Extension,
- /// <summary>
- /// A reply event
- /// </summary>
- Reply,
- /// <summary>
- /// An event representing the activity resuming from the suspension
- /// </summary>
- Resume,
- /// <summary>
- /// An event representing the activity is suspended, pending another activity's completion
- /// </summary>
- Suspend,
- /// <summary>
- /// An event representing the activity is transferred to another component, and can continue to work
- /// </summary>
- Send,
- /// <summary>
- /// An event representing receiving an activity transfer from another component
- /// </summary>
- Receive = 240
- }
-
- // Added for CLR V4
- /// <summary>
- /// EventChannel. Custom values must be in the range from 16 through 255. Currently only predefined values allowed.
- /// </summary>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1028:EnumStorageShouldBeInt32", Justification = "Backwards compatibility")]
-#if (!ES_BUILD_STANDALONE && !PROJECTN)
- [System.Runtime.CompilerServices.FriendAccessAllowed]
-#endif
- public enum EventChannel : byte
- {
- /// <summary>
- /// No channel
- /// </summary>
- None = 0,
- // Channels 1 - 15 are reserved...
- /// <summary>The admin channel</summary>
- Admin = 16,
- /// <summary>The operational channel</summary>
- Operational = 17,
- /// <summary>The analytic channel</summary>
- Analytic = 18,
- /// <summary>The debug channel</summary>
- Debug = 19,
-
- };
-
- /// <summary>
- /// EventOpcode
- /// </summary>
- [Flags]
- public enum EventKeywords : long
- {
- /// <summary>
- /// No events.
- /// </summary>
- None = 0x0,
- /// <summary>
- /// All Events
- /// </summary>
- All = ~0,
- /// <summary>
- /// Telemetry events
- /// </summary>
- MicrosoftTelemetry = 0x02000000000000,
- /// <summary>
- /// WDI context events
- /// </summary>
- WdiContext = 0x02000000000000,
- /// <summary>
- /// WDI diagnostic events
- /// </summary>
- WdiDiagnostic = 0x04000000000000,
- /// <summary>
- /// SQM events
- /// </summary>
- Sqm = 0x08000000000000,
- /// <summary>
- /// Failed security audits
- /// </summary>
- AuditFailure = 0x10000000000000,
- /// <summary>
- /// Successful security audits
- /// </summary>
- AuditSuccess = 0x20000000000000,
- /// <summary>
- /// Transfer events where the related Activity ID is a computed value and not a GUID
- /// N.B. The correct value for this field is 0x40000000000000.
- /// </summary>
- CorrelationHint = 0x10000000000000,
- /// <summary>
- /// Events raised using classic eventlog API
- /// </summary>
- EventLogClassic = 0x80000000000000
- }
-}
diff --git a/src/mscorlib/src/System/Diagnostics/ICustomDebuggerNotification.cs b/src/mscorlib/src/System/Diagnostics/ICustomDebuggerNotification.cs
index 29323cea2d..e7f41051f2 100644
--- a/src/mscorlib/src/System/Diagnostics/ICustomDebuggerNotification.cs
+++ b/src/mscorlib/src/System/Diagnostics/ICustomDebuggerNotification.cs
@@ -8,9 +8,11 @@
** This interface is implemented by classes that support custom debugger notifications.
**
===========================================================*/
-namespace System.Diagnostics {
-
- using System;
+
+using System;
+
+namespace System.Diagnostics
+{
// Defines an interface indicating that a custom debugger notification is requested under specific
// conditions. Users should implement this interface to be used as an argument to
// System.Diagnostics.Debugger.CustomNotification.
diff --git a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
index 14f0f26d98..29d6a1d4e6 100644
--- a/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
+++ b/src/mscorlib/src/System/Diagnostics/LogSwitch.cs
@@ -2,14 +2,15 @@
// 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.Diagnostics {
- using System;
- using System.IO;
- using System.Collections;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
- using System.Diagnostics.CodeAnalysis;
-
+using System;
+using System.IO;
+using System.Collections;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+using System.Diagnostics.CodeAnalysis;
+
+namespace System.Diagnostics
+{
[Serializable]
internal class LogSwitch
{
@@ -18,17 +19,17 @@ namespace System.Diagnostics {
// same in the EE code (debugdebugger.cpp/debugdebugger.h)
internal String strName;
internal String strDescription;
- private LogSwitch ParentSwitch;
+ private LogSwitch ParentSwitch;
internal volatile LoggingLevels iLevel;
internal volatile LoggingLevels iOldLevel;
-
+
// ! END WARNING !
-
-
- private LogSwitch ()
+
+
+ private LogSwitch()
{
}
-
+
// Constructs a LogSwitch. A LogSwitch is used to categorize log messages.
//
// All switches (except for the global LogSwitch) have a parent LogSwitch.
@@ -36,27 +37,27 @@ namespace System.Diagnostics {
public LogSwitch(String name, String description, LogSwitch parent)
{
if (name != null && name.Length == 0)
- throw new ArgumentOutOfRangeException(nameof(Name), Environment.GetResourceString("Argument_StringZeroLength"));
+ throw new ArgumentOutOfRangeException(nameof(Name), SR.Argument_StringZeroLength);
Contract.EndContractBlock();
if ((name != null) && (parent != null))
- {
+ {
strName = name;
strDescription = description;
iLevel = LoggingLevels.ErrorLevel;
iOldLevel = iLevel;
ParentSwitch = parent;
-
- Log.m_Hashtable.Add (strName, this);
-
+
+ Log.m_Hashtable.Add(strName, this);
+
// Call into the EE to let it know about the creation of
// this switch
- Log.AddLogSwitch (this);
+ Log.AddLogSwitch(this);
}
else
- throw new ArgumentNullException ((name==null ? nameof(name) : nameof(parent)));
+ throw new ArgumentNullException((name == null ? nameof(name) : nameof(parent)));
}
-
+
internal LogSwitch(String name, String description)
{
strName = name;
@@ -65,39 +66,39 @@ namespace System.Diagnostics {
iOldLevel = iLevel;
ParentSwitch = null;
- Log.m_Hashtable.Add (strName, this);
-
+ Log.m_Hashtable.Add(strName, this);
+
// Call into the EE to let it know about the creation of
// this switch
- Log.AddLogSwitch (this);
+ Log.AddLogSwitch(this);
}
-
-
+
+
// Get property returns the name of the switch
public virtual String Name
{
- get { return strName;}
+ get { return strName; }
}
-
-
+
+
// Property to Get/Set the level of log messages which are "on" for the switch.
//
- public virtual LoggingLevels MinimumLevel
+ public virtual LoggingLevels MinimumLevel
{
get { return iLevel; }
- set
- {
- iLevel = value;
+ set
+ {
+ iLevel = value;
iOldLevel = value;
- String strParentName = ParentSwitch!=null ? ParentSwitch.Name : "";
+ String strParentName = ParentSwitch != null ? ParentSwitch.Name : "";
if (Debugger.IsAttached)
- Log.ModifyLogSwitch ((int)iLevel, strName, strParentName);
-
- Log.InvokeLogSwitchLevelHandlers (this, iLevel);
+ Log.ModifyLogSwitch((int)iLevel, strName, strParentName);
+
+ Log.InvokeLogSwitchLevelHandlers(this, iLevel);
}
}
-
-
+
+
// Checks if the given level is "on" for this switch or one of its parents.
//
public virtual bool CheckLevel(LoggingLevels level)
@@ -105,22 +106,21 @@ namespace System.Diagnostics {
if (iLevel > level)
{
// recurse through the list till parent is hit.
- if (this.ParentSwitch == null)
+ if (ParentSwitch == null)
return false;
else
- return this.ParentSwitch.CheckLevel (level);
+ return ParentSwitch.CheckLevel(level);
}
else
return true;
}
-
-
+
+
// Returns a switch with the particular name, if any. Returns null if no
// such switch exists.
public static LogSwitch GetSwitch(String name)
{
return (LogSwitch)Log.m_Hashtable[name];
}
-
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs b/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs
index 0eea0507ec..6b5ea85ee1 100644
--- a/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs
+++ b/src/mscorlib/src/System/Diagnostics/LoggingLevels.cs
@@ -2,17 +2,19 @@
// 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.Diagnostics {
-
- using System;
- // Constants representing the importance level of messages to be logged.
- // This level can be used to organize messages, and also to filter which
- // messages are displayed.
- //
- // An attached debugger can enable or disable which messages will
- // actually be reported to the user through the COM+ debugger
- // services API. This info is communicated to the runtime so only
- // desired events are actually reported to the debugger.
+
+using System;
+
+namespace System.Diagnostics
+{
+ // Constants representing the importance level of messages to be logged.
+ // This level can be used to organize messages, and also to filter which
+ // messages are displayed.
+ //
+ // An attached debugger can enable or disable which messages will
+ // actually be reported to the user through the COM+ debugger
+ // services API. This info is communicated to the runtime so only
+ // desired events are actually reported to the debugger.
// NOTE: The following constants mirror the constants
// declared in the EE code (DebugDebugger.h). Any changes here will also
// need to be made there.
@@ -22,24 +24,23 @@ namespace System.Diagnostics {
[Serializable]
internal enum LoggingLevels
{
- TraceLevel0 = 0,
- TraceLevel1 = 1,
- TraceLevel2 = 2,
- TraceLevel3 = 3,
- TraceLevel4 = 4,
-
- StatusLevel0 = 20,
- StatusLevel1 = 21,
- StatusLevel2 = 22,
- StatusLevel3 = 23,
- StatusLevel4 = 24,
-
-
- WarningLevel = 40,
-
- ErrorLevel = 50,
-
- PanicLevel = 100,
- }
+ TraceLevel0 = 0,
+ TraceLevel1 = 1,
+ TraceLevel2 = 2,
+ TraceLevel3 = 3,
+ TraceLevel4 = 4,
+ StatusLevel0 = 20,
+ StatusLevel1 = 21,
+ StatusLevel2 = 22,
+ StatusLevel3 = 23,
+ StatusLevel4 = 24,
+
+
+ WarningLevel = 40,
+
+ ErrorLevel = 50,
+
+ PanicLevel = 100,
+ }
}
diff --git a/src/mscorlib/src/System/Diagnostics/Stackframe.cs b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
index 13d8f5cdcc..b555a609e7 100644
--- a/src/mscorlib/src/System/Diagnostics/Stackframe.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stackframe.cs
@@ -2,27 +2,28 @@
// 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.Diagnostics {
- using System.Text;
- using System;
- using System.IO;
- using System.Reflection;
- using System.Diagnostics.Contracts;
+using System.Text;
+using System;
+using System.IO;
+using System.Reflection;
+using System.Diagnostics.Contracts;
+namespace System.Diagnostics
+{
// There is no good reason for the methods of this class to be virtual.
[Serializable]
public class StackFrame
{
- private MethodBase method;
- private int offset;
- private int ILOffset;
- private String strFileName;
- private int iLineNumber;
- private int iColumnNumber;
-
+ private MethodBase method;
+ private int offset;
+ private int ILOffset;
+ private String strFileName;
+ private int iLineNumber;
+ private int iColumnNumber;
+
[System.Runtime.Serialization.OptionalField]
- private bool fIsLastFrameFromForeignExceptionStackTrace;
+ private bool fIsLastFrameFromForeignExceptionStackTrace;
internal void InitMembers()
{
@@ -33,21 +34,20 @@ namespace System.Diagnostics {
iLineNumber = 0;
iColumnNumber = 0;
fIsLastFrameFromForeignExceptionStackTrace = false;
-
}
// Constructs a StackFrame corresponding to the active stack frame.
public StackFrame()
{
InitMembers();
- BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, false);// iSkipFrames=0
+ BuildStackFrame(0 + StackTrace.METHODS_TO_SKIP, false);// iSkipFrames=0
}
-
+
// Constructs a StackFrame corresponding to the active stack frame.
public StackFrame(bool fNeedFileInfo)
{
InitMembers();
- BuildStackFrame (0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);// iSkipFrames=0
+ BuildStackFrame(0 + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);// iSkipFrames=0
}
// Constructs a StackFrame corresponding to a calling stack frame.
@@ -55,25 +55,25 @@ namespace System.Diagnostics {
public StackFrame(int skipFrames)
{
InitMembers();
- BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, false);
+ BuildStackFrame(skipFrames + StackTrace.METHODS_TO_SKIP, false);
}
-
+
// Constructs a StackFrame corresponding to a calling stack frame.
//
public StackFrame(int skipFrames, bool fNeedFileInfo)
{
InitMembers();
- BuildStackFrame (skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);
+ BuildStackFrame(skipFrames + StackTrace.METHODS_TO_SKIP, fNeedFileInfo);
}
-
+
// Called from the class "StackTrace"
//
internal StackFrame(bool DummyFlag1, bool DummyFlag2)
{
InitMembers();
}
-
+
// Constructs a "fake" stack frame, just containing the given file
// name and line number. Use when you don't want to use the
// debugger's line mapping logic.
@@ -81,12 +81,12 @@ namespace System.Diagnostics {
public StackFrame(String fileName, int lineNumber)
{
InitMembers();
- BuildStackFrame (StackTrace.METHODS_TO_SKIP, false);
+ BuildStackFrame(StackTrace.METHODS_TO_SKIP, false);
strFileName = fileName;
- iLineNumber = lineNumber;
+ iLineNumber = lineNumber;
iColumnNumber = 0;
}
-
+
// Constructs a "fake" stack frame, just containing the given file
// name, line number and column number. Use when you don't want to
@@ -95,48 +95,48 @@ namespace System.Diagnostics {
public StackFrame(String fileName, int lineNumber, int colNumber)
{
InitMembers();
- BuildStackFrame (StackTrace.METHODS_TO_SKIP, false);
+ BuildStackFrame(StackTrace.METHODS_TO_SKIP, false);
strFileName = fileName;
- iLineNumber = lineNumber;
+ iLineNumber = lineNumber;
iColumnNumber = colNumber;
}
// Constant returned when the native or IL offset is unknown
- public const int OFFSET_UNKNOWN = -1;
-
-
- internal virtual void SetMethodBase (MethodBase mb)
+ public const int OFFSET_UNKNOWN = -1;
+
+
+ internal virtual void SetMethodBase(MethodBase mb)
{
method = mb;
}
-
- internal virtual void SetOffset (int iOffset)
+
+ internal virtual void SetOffset(int iOffset)
{
offset = iOffset;
}
-
- internal virtual void SetILOffset (int iOffset)
+
+ internal virtual void SetILOffset(int iOffset)
{
ILOffset = iOffset;
}
- internal virtual void SetFileName (String strFName)
+ internal virtual void SetFileName(String strFName)
{
strFileName = strFName;
}
- internal virtual void SetLineNumber (int iLine)
+ internal virtual void SetLineNumber(int iLine)
{
iLineNumber = iLine;
}
- internal virtual void SetColumnNumber (int iCol)
+ internal virtual void SetColumnNumber(int iCol)
{
iColumnNumber = iCol;
}
- internal virtual void SetIsLastFrameFromForeignExceptionStackTrace (bool fIsLastFrame)
+ internal virtual void SetIsLastFrameFromForeignExceptionStackTrace(bool fIsLastFrame)
{
fIsLastFrameFromForeignExceptionStackTrace = fIsLastFrame;
}
@@ -148,22 +148,22 @@ namespace System.Diagnostics {
// Returns the method the frame is executing
//
- public virtual MethodBase GetMethod ()
+ public virtual MethodBase GetMethod()
{
Contract.Ensures(Contract.Result<MethodBase>() != null);
return method;
}
-
+
// Returns the offset from the start of the native (jitted) code for the
// method being executed
//
- public virtual int GetNativeOffset ()
+ public virtual int GetNativeOffset()
{
return offset;
}
-
-
+
+
// Returns the offset from the start of the IL code for the
// method being executed. This offset may be approximate depending
// on whether the jitter is generating debuggable code or not.
@@ -171,8 +171,8 @@ namespace System.Diagnostics {
public virtual int GetILOffset()
{
return ILOffset;
- }
-
+ }
+
// Returns the file name containing the code being executed. This
// information is normally extracted from the debugging symbols
// for the executable.
@@ -181,7 +181,7 @@ namespace System.Diagnostics {
{
return strFileName;
}
-
+
// Returns the line number in the file containing the code being executed.
// This information is normally extracted from the debugging symbols
// for the executable.
@@ -200,7 +200,7 @@ namespace System.Diagnostics {
return iColumnNumber;
}
-
+
// Builds a readable representation of the stack frame
//
public override String ToString()
@@ -258,10 +258,10 @@ namespace System.Diagnostics {
}
sb.Append(Environment.NewLine);
- return sb.ToString();
+ return sb.ToString();
}
-
-
+
+
private void BuildStackFrame(int skipFrames, bool fNeedFileInfo)
{
using (StackFrameHelper StackF = new StackFrameHelper(null))
diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
index cd88f5108f..cdedb66ed8 100644
--- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
@@ -2,21 +2,22 @@
// 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.Diagnostics {
- using System;
- using System.Collections;
- using System.Text;
- using System.Threading;
- using System.Security;
- using System.IO;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
+using System;
+using System.Collections;
+using System.Text;
+using System.Threading;
+using System.Security;
+using System.IO;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+
+namespace System.Diagnostics
+{
// READ ME:
// Modifying the order or fields of this object may require other changes
// to the unmanaged definition of the StackFrameHelper class, in
@@ -55,7 +56,7 @@ namespace System.Diagnostics {
#pragma warning restore 414
private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize,
- IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
+ IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset,
out string sourceFile, out int sourceLine, out int sourceColumn);
private static Type s_symbolsType = null;
@@ -170,16 +171,16 @@ namespace System.Diagnostics {
}
}
- public virtual MethodBase GetMethodBase(int i)
- {
+ public virtual MethodBase GetMethodBase(int i)
+ {
// There may be a better way to do this.
// we got RuntimeMethodHandles here and we need to go to MethodBase
// but we don't know whether the reflection info has been initialized
// or not. So we call GetMethods and GetConstructors on the type
// and then we fetch the proper MethodBase!!
IntPtr mh = rgMethodHandle[i];
-
- if (mh.IsNull())
+
+ if (mh.IsNull())
return null;
IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this));
@@ -187,32 +188,32 @@ namespace System.Diagnostics {
return RuntimeType.GetMethodBase(mhReal);
}
- public virtual int GetOffset(int i) { return rgiOffset[i];}
- public virtual int GetILOffset(int i) { return rgiILOffset[i];}
- public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i];}
- public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i];}
- public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i];}
+ public virtual int GetOffset(int i) { return rgiOffset[i]; }
+ public virtual int GetILOffset(int i) { return rgiILOffset[i]; }
+ public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i]; }
+ public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i]; }
+ public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i]; }
- public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
- {
- return (rgiLastFrameFromForeignExceptionStackTrace == null)?false:rgiLastFrameFromForeignExceptionStackTrace[i];
- }
+ public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i)
+ {
+ return (rgiLastFrameFromForeignExceptionStackTrace == null) ? false : rgiLastFrameFromForeignExceptionStackTrace[i];
+ }
+
+ public virtual int GetNumberOfFrames() { return iFrameCount; }
- public virtual int GetNumberOfFrames() { return iFrameCount;}
-
//
// serialization implementation
//
[OnSerializing]
- void OnSerializing(StreamingContext context)
+ private void OnSerializing(StreamingContext context)
{
// this is called in the process of serializing this object.
// For compatibility with Everett we need to assign the rgMethodBase field as that is the field
// that will be serialized
rgMethodBase = (rgMethodHandle == null) ? null : new MethodBase[rgMethodHandle.Length];
- if (rgMethodHandle != null)
+ if (rgMethodHandle != null)
{
- for (int i = 0; i < rgMethodHandle.Length; i++)
+ for (int i = 0; i < rgMethodHandle.Length; i++)
{
if (!rgMethodHandle[i].IsNull())
rgMethodBase[i] = RuntimeType.GetMethodBase(new RuntimeMethodInfoStub(rgMethodHandle[i], this));
@@ -221,20 +222,20 @@ namespace System.Diagnostics {
}
[OnSerialized]
- void OnSerialized(StreamingContext context)
+ private void OnSerialized(StreamingContext context)
{
// after we are done serializing null the rgMethodBase field
rgMethodBase = null;
}
[OnDeserialized]
- void OnDeserialized(StreamingContext context)
+ private void OnDeserialized(StreamingContext context)
{
// after we are done deserializing we need to transform the rgMethodBase in rgMethodHandle
rgMethodHandle = (rgMethodBase == null) ? null : new IntPtr[rgMethodBase.Length];
- if (rgMethodBase != null)
+ if (rgMethodBase != null)
{
- for (int i = 0; i < rgMethodBase.Length; i++)
+ for (int i = 0; i < rgMethodBase.Length; i++)
{
if (rgMethodBase[i] != null)
rgMethodHandle[i] = rgMethodBase[i].MethodHandle.Value;
@@ -243,8 +244,8 @@ namespace System.Diagnostics {
rgMethodBase = null;
}
}
-
-
+
+
// 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
@@ -274,42 +275,40 @@ namespace System.Diagnostics {
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
-
+
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace(int skipFrames)
{
-
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException(nameof(skipFrames),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
-
+
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
-
- CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, null);
+
+ CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, null);
}
-
+
// Constructs a stack trace from the current location, in a caller's
// frame
//
public StackTrace(int skipFrames, bool fNeedFileInfo)
{
-
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException(nameof(skipFrames),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
-
+
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
-
- CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, null);
+
+ CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null);
}
-
-
+
+
// Constructs a stack trace from the current location.
public StackTrace(Exception e)
{
@@ -334,7 +333,7 @@ namespace System.Diagnostics {
m_iMethodsToSkip = 0;
CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
-
+
// Constructs a stack trace from the current location, in a caller's
// frame
//
@@ -344,16 +343,16 @@ namespace System.Diagnostics {
throw new ArgumentNullException(nameof(e));
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException(nameof(skipFrames),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
-
+
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
-
- CaptureStackTrace(skipFrames+METHODS_TO_SKIP, false, null, e);
+
+ CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, e);
}
-
+
// Constructs a stack trace from the current location, in a caller's
// frame
//
@@ -363,17 +362,17 @@ namespace System.Diagnostics {
throw new ArgumentNullException(nameof(e));
if (skipFrames < 0)
- throw new ArgumentOutOfRangeException(nameof(skipFrames),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(skipFrames),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
-
+
m_iNumOfFrames = 0;
m_iMethodsToSkip = 0;
-
- CaptureStackTrace(skipFrames+METHODS_TO_SKIP, fNeedFileInfo, null, e);
+
+ CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e);
}
-
-
+
+
// Constructs a "fake" stack trace, just containing a single frame.
// Does not have the overhead of a full stack trace.
//
@@ -386,26 +385,14 @@ namespace System.Diagnostics {
}
- // Constructs a stack trace for the given thread
- //
- [Obsolete("This constructor has been deprecated. Please use a constructor that does not require a Thread parameter. http://go.microsoft.com/fwlink/?linkid=14202")]
- public StackTrace(Thread targetThread, bool needFileInfo)
- {
- m_iNumOfFrames = 0;
- m_iMethodsToSkip = 0;
-
- CaptureStackTrace(METHODS_TO_SKIP, needFileInfo, targetThread, null);
-
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e);
-
+
internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames)
{
int iRetVal = 0;
String PackageName = "System.Diagnostics";
-
+
// Check if this method is part of the System.Diagnostics
// package. If so, increment counter keeping track of
// System.Diagnostics functions
@@ -413,22 +400,22 @@ namespace System.Diagnostics {
{
MethodBase mb = StackF.GetMethodBase(i);
if (mb != null)
- {
+ {
Type t = mb.DeclaringType;
- if (t == null)
+ if (t == null)
break;
String ns = t.Namespace;
- if (ns == null)
+ if (ns == null)
break;
if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0)
break;
}
iRetVal++;
}
-
+
return iRetVal;
}
-
+
// Retrieves an object with stack trace information encoded.
// It leaves out the first "iSkip" lines of the stacktrace.
//
@@ -459,7 +446,7 @@ namespace System.Diagnostics {
sfTemp.SetOffset(StackF.GetOffset(i));
sfTemp.SetILOffset(StackF.GetILOffset(i));
- sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
+ sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i));
if (fNeedFileInfo)
{
@@ -488,23 +475,23 @@ namespace System.Diagnostics {
frames = null;
}
}
-
+
// Property to get the number of frames in the stack trace
//
public virtual int FrameCount
{
- get { return m_iNumOfFrames;}
+ get { return m_iNumOfFrames; }
}
-
-
+
+
// Returns a given stack frame. Stack frames are numbered starting at
// zero, which is the last stack frame pushed.
//
public virtual StackFrame GetFrame(int index)
{
if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0))
- return frames[index+m_iMethodsToSkip];
-
+ return frames[index + m_iMethodsToSkip];
+
return null;
}
@@ -513,18 +500,18 @@ namespace System.Diagnostics {
// The nth element of this array is the same as GetFrame(n).
// The length of the array is the same as FrameCount.
//
- public virtual StackFrame [] GetFrames()
+ public virtual StackFrame[] GetFrames()
{
if (frames == null || m_iNumOfFrames <= 0)
return null;
-
+
// We have to return a subset of the array. Unfortunately this
// means we have to allocate a new array and copy over.
- StackFrame [] array = new StackFrame[m_iNumOfFrames];
+ StackFrame[] array = new StackFrame[m_iNumOfFrames];
Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames);
return array;
}
-
+
// Builds a readable representation of the stack trace
//
public override String ToString()
@@ -535,13 +522,13 @@ namespace System.Diagnostics {
// TraceFormat is Used to specify options for how the
// string-representation of a StackTrace should be generated.
- internal enum TraceFormat
+ internal enum TraceFormat
{
Normal,
TrailingNewLine, // include a trailing new line character
NoResourceLookup // to prevent infinite resource recusion
}
-
+
// Builds a readable representation of the stack trace, specifying
// the format for backwards compatibility.
internal String ToString(TraceFormat traceFormat)
@@ -550,12 +537,12 @@ namespace System.Diagnostics {
String word_At = "at";
String inFileLineNum = "in {0}:line {1}";
- if(traceFormat != TraceFormat.NoResourceLookup)
+ if (traceFormat != TraceFormat.NoResourceLookup)
{
- word_At = Environment.GetResourceString("Word_At");
- inFileLineNum = Environment.GetResourceString("StackTrace_InFileLineNumber");
+ word_At = SR.Word_At;
+ inFileLineNum = SR.StackTrace_InFileLineNumber;
}
-
+
bool fFirstFrame = true;
StringBuilder sb = new StringBuilder(255);
for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++)
@@ -569,11 +556,11 @@ namespace System.Diagnostics {
fFirstFrame = false;
else
sb.Append(Environment.NewLine);
-
+
sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At);
Type t = mb.DeclaringType;
- // if there is a type (non global method) print it
+ // if there is a type (non global method) print it
if (t != null)
{
// Append t.FullName, replacing '+' with '.'
@@ -592,7 +579,7 @@ namespace System.Diagnostics {
{
Type[] typars = ((MethodInfo)mb).GetGenericArguments();
sb.Append('[');
- int k=0;
+ int k = 0;
bool fFirstTyParam = true;
while (k < typars.Length)
{
@@ -603,8 +590,8 @@ namespace System.Diagnostics {
sb.Append(typars[k].Name);
k++;
- }
- sb.Append(']');
+ }
+ sb.Append(']');
}
ParameterInfo[] pi = null;
@@ -635,7 +622,7 @@ namespace System.Diagnostics {
sb.Append(typeName);
sb.Append(' ');
sb.Append(pi[j].Name);
- }
+ }
sb.Append(')');
}
@@ -645,7 +632,7 @@ namespace System.Diagnostics {
// If we don't have a PDB or PDB-reading is disabled for the module,
// then the file name will be null.
String fileName = null;
-
+
// Getting the filename from a StackFrame is a privileged operation - we won't want
// to disclose full path names to arbitrarily untrusted code. Rather than just omit
// this we could probably trim to just the filename so it's still mostly usefull.
@@ -660,7 +647,7 @@ namespace System.Diagnostics {
displayFilenames = false;
}
- if (fileName != null)
+ if (fileName != null)
{
// tack on " in c:\tmp\MyFile.cs:line 5"
sb.Append(' ');
@@ -671,15 +658,15 @@ namespace System.Diagnostics {
if (sf.GetIsLastFrameFromForeignExceptionStackTrace())
{
sb.Append(Environment.NewLine);
- sb.Append(Environment.GetResourceString("Exception_EndStackTraceFromPreviousThrow"));
+ sb.Append(SR.Exception_EndStackTraceFromPreviousThrow);
}
}
}
- if(traceFormat == TraceFormat.TrailingNewLine)
+ if (traceFormat == TraceFormat.TrailingNewLine)
sb.Append(Environment.NewLine);
-
- return sb.ToString();
+
+ return sb.ToString();
}
// This helper is called from within the EE to construct a string representation
@@ -693,5 +680,4 @@ namespace System.Diagnostics {
return st.ToString();
}
}
-
}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs
index a1a2366c0a..09a7a3b0b0 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymDocumentWriter.cs
@@ -12,10 +12,11 @@
**
**
===========================================================*/
-namespace System.Diagnostics.SymbolStore {
-
- using System;
-
+
+using System;
+
+namespace System.Diagnostics.SymbolStore
+{
// Interface does not need to be marked with the serializable attribute
public interface ISymbolDocumentWriter
{
@@ -23,7 +24,7 @@ namespace System.Diagnostics.SymbolStore {
// symbol store. An array of unsigned bytes is used instead of
// character data to accommodate a wider variety of "source".
void SetSource(byte[] source);
-
+
// Check sum support.
void SetCheckSum(Guid algorithmId, byte[] checkSum);
}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
index bfe9133aee..fa2a59797a 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/ISymWriter.cs
@@ -11,18 +11,18 @@
**
**
===========================================================*/
-namespace System.Diagnostics.SymbolStore {
-
- using System;
- using System.Text;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
+using System;
+using System.Text;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+
+namespace System.Diagnostics.SymbolStore
+{
// Interface does not need to be marked with the serializable attribute
internal interface ISymbolWriter
{
-
// Define a source document. Guid's will be provided for the
// languages, vendors, and document types that we currently know
// about.
@@ -30,7 +30,7 @@ namespace System.Diagnostics.SymbolStore {
Guid language,
Guid languageVendor,
Guid documentType);
-
+
// Open a method to emit symbol information into. The given method
// becomes the current method for calls do define sequence points,
// parameters and lexical scopes. There is an implicit lexical
@@ -40,11 +40,11 @@ namespace System.Diagnostics.SymbolStore {
//
// There can be only one open method at a time.
void OpenMethod(SymbolToken method);
-
+
// Close the current method. Once a method is closed, no more
// symbols can be defined within it.
void CloseMethod();
-
+
// Define a group of sequence points within the current method.
// Each line/column defines the start of a statement within a
// method. The arrays should be sorted by offset. The offset is
@@ -55,7 +55,7 @@ namespace System.Diagnostics.SymbolStore {
int[] columns,
int[] endLines,
int[] endColumns);
-
+
// Open a new lexical scope in the current method. The scope
// becomes the new current scope and is effectivley pushed onto a
// stack of scopes. startOffset is the offset, in bytes from the
@@ -72,12 +72,12 @@ namespace System.Diagnostics.SymbolStore {
//
int OpenScope(int startOffset);
-
+
// Close the current lexical scope. Once a scope is closed no more
// variables can be defined within it. endOffset points past the
// last instruction in the scope.
void CloseScope(int endOffset);
-
+
// Define a single variable in the current lexical
// scope. startOffset and endOffset are optional. If 0, then they
// are ignored and the variable is defined over the entire
@@ -95,12 +95,12 @@ namespace System.Diagnostics.SymbolStore {
int addr3,
int startOffset,
int endOffset);
-
+
// Defines a custom attribute based upon its name. Not to be
// confused with Metadata custom attributes, these attributes are
// held in the symbol store.
void SetSymAttribute(SymbolToken parent, String name, byte[] data);
-
+
// Specifies that the given, fully qualified namespace name is
// being used within the currently open lexical scope. Closing the
// current scope will also stop using the namespace, and the
@@ -108,5 +108,4 @@ namespace System.Diagnostics.SymbolStore {
// currently open scope.
void UsingNamespace(String fullName);
}
-
}
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
index bb50d9841b..c4c1ede525 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/SymAddressKind.cs
@@ -11,37 +11,39 @@
**
**
===========================================================*/
-namespace System.Diagnostics.SymbolStore {
- // Only statics, does not need to be marked with the serializable attribute
- using System;
+// Only statics, does not need to be marked with the serializable attribute
+using System;
+
+namespace System.Diagnostics.SymbolStore
+{
[Serializable]
internal enum SymAddressKind
{
// ILOffset: addr1 = IL local var or param index.
ILOffset = 1,
-
+
// NativeRVA: addr1 = RVA into module.
NativeRVA = 2,
-
+
// NativeRegister: addr1 = register the var is stored in.
NativeRegister = 3,
-
+
// NativeRegisterRelative: addr1 = register, addr2 = offset.
NativeRegisterRelative = 4,
-
+
// NativeOffset: addr1 = offset from start of parent.
NativeOffset = 5,
-
+
// NativeRegisterRegister: addr1 = reg low, addr2 = reg high.
NativeRegisterRegister = 6,
-
+
// NativeRegisterStack: addr1 = reg low, addr2 = reg stk, addr3 = offset.
NativeRegisterStack = 7,
-
+
// NativeStackRegister: addr1 = reg stk, addr2 = offset, addr3 = reg high.
NativeStackRegister = 8,
-
+
// BitField: addr1 = field start, addr = field length.
BitField = 9,
diff --git a/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs b/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs
index cc1e4a865f..a6e6fdc0ef 100644
--- a/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs
+++ b/src/mscorlib/src/System/Diagnostics/SymbolStore/Token.cs
@@ -9,21 +9,22 @@
** around metadata tokens.
**
===========================================================*/
-namespace System.Diagnostics.SymbolStore {
-
- using System;
- using System.Runtime.InteropServices;
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Diagnostics.SymbolStore
+{
internal struct SymbolToken
{
internal int m_token;
-
- public SymbolToken(int val) {m_token=val;}
-
- public int GetToken() {return m_token;}
-
- public override int GetHashCode() {return m_token;}
-
+
+ public SymbolToken(int val) { m_token = val; }
+
+ public int GetToken() { return m_token; }
+
+ public override int GetHashCode() { return m_token; }
+
public override bool Equals(Object obj)
{
if (obj is SymbolToken)
@@ -31,7 +32,7 @@ namespace System.Diagnostics.SymbolStore {
else
return false;
}
-
+
public bool Equals(SymbolToken obj)
{
return obj.m_token == m_token;
diff --git a/src/mscorlib/src/System/Diagnostics/log.cs b/src/mscorlib/src/System/Diagnostics/log.cs
index d297b8fa08..b62ea493e7 100644
--- a/src/mscorlib/src/System/Diagnostics/log.cs
+++ b/src/mscorlib/src/System/Diagnostics/log.cs
@@ -2,7 +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.
-namespace System.Diagnostics {
+namespace System.Diagnostics
+{
using System.Runtime.Remoting;
using System;
using System.IO;
@@ -12,19 +13,19 @@ namespace System.Diagnostics {
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Diagnostics.CodeAnalysis;
-
-
- // LogSwitchLevelHandlers are triggered when the level of a LogSwitch is modified
- // NOTE: These are NOT triggered when the log switch setting is changed from the
- // attached debugger.
- //
+
+ using Console = Internal.Console;
+
+ // LogSwitchLevelHandlers are triggered when the level of a LogSwitch is modified
+ // NOTE: These are NOT triggered when the log switch setting is changed from the
+ // attached debugger.
+ //
[Serializable]
internal delegate void LogSwitchLevelHandler(LogSwitch ls, LoggingLevels newLevel);
-
-
+
+
internal static class Log
{
-
// Switches allow relatively fine level control of which messages are
// actually shown. Normally most debugging messages are not shown - the
// user will typically enable those which are relevant to what is being
@@ -36,13 +37,13 @@ namespace System.Diagnostics {
// desired events are actually reported to the debugger.
internal static Hashtable m_Hashtable;
private static volatile bool m_fConsoleDeviceEnabled;
- private static volatile LogSwitchLevelHandler _LogSwitchLevelHandler;
+ private static volatile LogSwitchLevelHandler _LogSwitchLevelHandler;
private static Object locker;
-
+
// Constant representing the global switch
public static readonly LogSwitch GlobalSwitch;
-
-
+
+
static Log()
{
m_Hashtable = new Hashtable();
@@ -51,21 +52,21 @@ namespace System.Diagnostics {
//iNumOfMsgHandlers = 0;
//iMsgHandlerArraySize = 0;
locker = new Object();
-
+
// allocate the GlobalSwitch object
- GlobalSwitch = new LogSwitch ("Global", "Global Switch for this log");
-
+ GlobalSwitch = new LogSwitch("Global", "Global Switch for this log");
+
GlobalSwitch.MinimumLevel = LoggingLevels.ErrorLevel;
}
-
- internal static void InvokeLogSwitchLevelHandlers (LogSwitch ls, LoggingLevels newLevel)
+
+ internal static void InvokeLogSwitchLevelHandlers(LogSwitch ls, LoggingLevels newLevel)
{
LogSwitchLevelHandler handler = _LogSwitchLevelHandler;
if (handler != null)
handler(ls, newLevel);
}
-
-
+
+
// Property to Enable/Disable ConsoleDevice. Enabling the console device
// adds the console device as a log output, causing any
// log messages which make it through filters to be written to the
@@ -76,7 +77,7 @@ namespace System.Diagnostics {
get { return m_fConsoleDeviceEnabled; }
set { m_fConsoleDeviceEnabled = value; }
}
-
+
// Generates a log message. If its switch (or a parent switch) allows the
// level for the message, it is "broadcast" to all of the log
// devices.
@@ -84,28 +85,28 @@ namespace System.Diagnostics {
public static void LogMessage(LoggingLevels level, LogSwitch logswitch, String message)
{
if (logswitch == null)
- throw new ArgumentNullException ("LogSwitch");
-
+ throw new ArgumentNullException("LogSwitch");
+
if (level < 0)
- throw new ArgumentOutOfRangeException(nameof(level), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(level), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
-
+
// Is logging for this level for this switch enabled?
- if (logswitch.CheckLevel (level) == true)
+ if (logswitch.CheckLevel(level) == true)
{
// Send message for logging
-
+
// first send it to the debugger
- Debugger.Log ((int) level, logswitch.strName, message);
-
+ Debugger.Log((int)level, logswitch.strName, message);
+
// Send to the console device
if (m_fConsoleDeviceEnabled)
{
- Console.Write(message);
- }
+ Console.Write(message);
+ }
}
}
-
+
/*
* Following are convenience entry points; all go through Log()
* Note that the (Switch switch, String message) variations
@@ -113,20 +114,19 @@ namespace System.Diagnostics {
*/
public static void Trace(LogSwitch logswitch, String message)
{
- LogMessage (LoggingLevels.TraceLevel0, logswitch, message);
+ LogMessage(LoggingLevels.TraceLevel0, logswitch, message);
}
-
+
public static void Trace(String message)
{
- LogMessage (LoggingLevels.TraceLevel0, GlobalSwitch, message);
+ LogMessage(LoggingLevels.TraceLevel0, GlobalSwitch, message);
}
-
-
+
+
// Native method to inform the EE about the creation of a new LogSwitch
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void AddLogSwitch(LogSwitch logSwitch);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern void ModifyLogSwitch (int iNewLevel, String strSwitchName, String strParentName);
+ internal static extern void ModifyLogSwitch(int iNewLevel, String strSwitchName, String strParentName);
}
-
}
diff --git a/src/mscorlib/src/System/DivideByZeroException.cs b/src/mscorlib/src/System/DivideByZeroException.cs
deleted file mode 100644
index 4abd43adaf..0000000000
--- a/src/mscorlib/src/System/DivideByZeroException.cs
+++ /dev/null
@@ -1,41 +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 class for bad arithmetic conditions!
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class DivideByZeroException : ArithmeticException
- {
- public DivideByZeroException()
- : base(SR.Arg_DivideByZero)
- {
- HResult = __HResults.COR_E_DIVIDEBYZERO;
- }
-
- public DivideByZeroException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_DIVIDEBYZERO;
- }
-
- public DivideByZeroException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_DIVIDEBYZERO;
- }
-
- protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/DllNotFoundException.cs b/src/mscorlib/src/System/DllNotFoundException.cs
index 43bb57fec2..a3b46c76b3 100644
--- a/src/mscorlib/src/System/DllNotFoundException.cs
+++ b/src/mscorlib/src/System/DllNotFoundException.cs
@@ -11,29 +11,35 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class DllNotFoundException : TypeLoadException {
- public DllNotFoundException()
- : base(Environment.GetResourceString("Arg_DllNotFoundException")) {
- SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
+ public class DllNotFoundException : TypeLoadException
+ {
+ public DllNotFoundException()
+ : base(SR.Arg_DllNotFoundException)
+ {
+ HResult = __HResults.COR_E_DLLNOTFOUND;
}
-
- public DllNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
+
+ public DllNotFoundException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_DLLNOTFOUND;
}
-
- public DllNotFoundException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
+
+ public DllNotFoundException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_DLLNOTFOUND;
}
- protected DllNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
+ protected DllNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ }
}
}
diff --git a/src/mscorlib/src/System/Double.cs b/src/mscorlib/src/System/Double.cs
index 1e4e477366..f2c5cec219 100644
--- a/src/mscorlib/src/System/Double.cs
+++ b/src/mscorlib/src/System/Double.cs
@@ -11,19 +11,20 @@
**
**
===========================================================*/
-namespace System {
- using System;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[StructLayout(LayoutKind.Sequential)]
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [Serializable]
+ [StructLayout(LayoutKind.Sequential)]
public struct Double : IComparable, IFormattable, IConvertible
- , IComparable<Double>, IEquatable<Double>
+ , IComparable<Double>, IEquatable<Double>
{
internal double m_value;
@@ -35,22 +36,24 @@ namespace System {
// Note Epsilon should be a double whose hex representation is 0x1
// on little endian machines.
- public const double Epsilon = 4.9406564584124654E-324;
+ public const double Epsilon = 4.9406564584124654E-324;
public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
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));
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool IsInfinity(double d) {
+ public unsafe static bool IsInfinity(double d)
+ {
return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
}
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public static bool IsPositiveInfinity(double d) {
+ public static bool IsPositiveInfinity(double d)
+ {
//Jit will generate inlineable code with this
if (d == double.PositiveInfinity)
{
@@ -64,7 +67,8 @@ namespace System {
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public static bool IsNegativeInfinity(double d) {
+ public static bool IsNegativeInfinity(double d)
+ {
//Jit will generate inlineable code with this
if (d == double.NegativeInfinity)
{
@@ -77,7 +81,8 @@ namespace System {
}
[Pure]
- internal unsafe static bool IsNegative(double d) {
+ internal unsafe static bool IsNegative(double d)
+ {
return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
}
@@ -96,11 +101,14 @@ namespace System {
//
// Returns a value less than zero if this object
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is Double) {
+ if (value is Double)
+ {
double d = (double)value;
if (m_value < d) return -1;
if (m_value > d) return 1;
@@ -112,10 +120,11 @@ namespace System {
else
return 1;
}
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDouble"));
+ throw new ArgumentException(SR.Arg_MustBeDouble);
}
- public int CompareTo(Double value) {
+ public int CompareTo(Double value)
+ {
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
@@ -129,51 +138,61 @@ namespace System {
// True if obj is another Double with the same value as the current instance. This is
// a method of object equality, that only returns true if obj is also a double.
- public override bool Equals(Object obj) {
- if (!(obj is Double)) {
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Double))
+ {
return false;
}
double temp = ((Double)obj).m_value;
// This code below is written this way for performance reasons i.e the != and == check is intentional.
- if (temp == m_value) {
+ if (temp == m_value)
+ {
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator ==(Double left, Double right) {
+ public static bool operator ==(Double left, Double right)
+ {
return left == right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator !=(Double left, Double right) {
+ public static bool operator !=(Double left, Double right)
+ {
return left != right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator <(Double left, Double right) {
+ public static bool operator <(Double left, Double right)
+ {
return left < right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator >(Double left, Double right) {
+ public static bool operator >(Double left, Double right)
+ {
return left > right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator <=(Double left, Double right) {
+ public static bool operator <=(Double left, Double right)
+ {
return left <= right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator >=(Double left, Double right) {
+ public static bool operator >=(Double left, Double right)
+ {
return left >= right;
}
public bool Equals(Double obj)
{
- if (obj == m_value) {
+ if (obj == m_value)
+ {
return true;
}
return IsNaN(obj) && IsNaN(m_value);
@@ -182,9 +201,11 @@ namespace System {
//The hashcode for a double is the absolute value of the integer representation
//of that double.
//
- public unsafe override int GetHashCode() {
+ public unsafe override int GetHashCode()
+ {
double d = m_value;
- if (d == 0) {
+ if (d == 0)
+ {
// Ensure that 0 and -0 have the same hash code
return 0;
}
@@ -192,44 +213,52 @@ namespace System {
return unchecked((int)value) ^ ((int)(value >> 32));
}
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
}
-
- public String ToString(IFormatProvider provider) {
+
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
}
-
- public String ToString(String format, IFormatProvider provider) {
+
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
}
- public static double Parse(String s) {
- return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
+ public static double Parse(String s)
+ {
+ return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
- public static double Parse(String s, NumberStyles style) {
+ public static double Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
- public static double Parse(String s, IFormatProvider provider) {
- return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
+ public static double Parse(String s, IFormatProvider provider)
+ {
+ return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
- public static double Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static double Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
-
+
// Parses a double from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
@@ -238,34 +267,46 @@ namespace System {
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
//
- private static double Parse(String s, NumberStyles style, NumberFormatInfo info) {
+ private static double Parse(String s, NumberStyles style, NumberFormatInfo info)
+ {
return Number.ParseDouble(s, style, info);
}
- public static bool TryParse(String s, out double result) {
- return TryParse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
+ public static bool TryParse(String s, out double result)
+ {
+ return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double 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) {
+
+ private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out double result)
+ {
+ if (s == null)
+ {
result = 0;
return false;
}
bool success = Number.TryParseDouble(s, style, info, out result);
- if (!success) {
+ if (!success)
+ {
String sTrim = s.Trim();
- if (sTrim.Equals(info.PositiveInfinitySymbol)) {
+ if (sTrim.Equals(info.PositiveInfinitySymbol))
+ {
result = PositiveInfinity;
- } else if (sTrim.Equals(info.NegativeInfinitySymbol)) {
+ }
+ else if (sTrim.Equals(info.NegativeInfinitySymbol))
+ {
result = NegativeInfinity;
- } else if (sTrim.Equals(info.NaNSymbol)) {
+ }
+ else if (sTrim.Equals(info.NaNSymbol))
+ {
result = NaN;
- } else
+ }
+ else
return false; // We really failed
}
return true;
@@ -275,82 +316,83 @@ namespace System {
// IConvertible implementation
//
- public TypeCode GetTypeCode() {
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Double;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "Char"));
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "Char"));
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/DuplicateWaitObjectException.cs b/src/mscorlib/src/System/DuplicateWaitObjectException.cs
deleted file mode 100644
index da29e2ad76..0000000000
--- a/src/mscorlib/src/System/DuplicateWaitObjectException.cs
+++ /dev/null
@@ -1,65 +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 class for duplicate objects in WaitAll/WaitAny.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The DuplicateWaitObjectException is thrown when an object
- // appears more than once in the list of objects to WaitAll or WaitAny.
- //
- [Serializable]
- public class DuplicateWaitObjectException : ArgumentException
- {
- private static volatile String s_duplicateWaitObjectMessage = null;
-
- private static String DuplicateWaitObjectMessage
- {
- get
- {
- if (s_duplicateWaitObjectMessage == null)
- s_duplicateWaitObjectMessage = SR.Arg_DuplicateWaitObjectException;
- return s_duplicateWaitObjectMessage;
- }
- }
-
- // Creates a new DuplicateWaitObjectException with its message
- // string set to a default message.
- public DuplicateWaitObjectException()
- : base(DuplicateWaitObjectMessage)
- {
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
- }
-
- public DuplicateWaitObjectException(String parameterName)
- : base(DuplicateWaitObjectMessage, parameterName)
- {
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
- }
-
- public DuplicateWaitObjectException(String parameterName, String message)
- : base(message, parameterName)
- {
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
- }
-
- public DuplicateWaitObjectException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
- }
-
- // This constructor is required for serialization
- protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Empty.cs b/src/mscorlib/src/System/Empty.cs
index 4790d9a383..502e8dfea7 100644
--- a/src/mscorlib/src/System/Empty.cs
+++ b/src/mscorlib/src/System/Empty.cs
@@ -5,28 +5,33 @@
// Empty
// This class represents an empty variant
////////////////////////////////////////////////////////////////////////////////
+
using System.Diagnostics.Contracts;
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
internal sealed class Empty : ISerializable
{
- private Empty() {
+ private Empty()
+ {
}
-
+
public static readonly Empty Value = new Empty();
-
+
public override String ToString()
{
return String.Empty;
}
-
- public void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/EntryPointNotFoundException.cs b/src/mscorlib/src/System/EntryPointNotFoundException.cs
deleted file mode 100644
index 835d33413d..0000000000
--- a/src/mscorlib/src/System/EntryPointNotFoundException.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 for some failed P/Invoke calls.
-**
-**
-=============================================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class EntryPointNotFoundException : TypeLoadException
- {
- public EntryPointNotFoundException()
- : base(SR.Arg_EntryPointNotFoundException)
- {
- HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
- }
-
- public EntryPointNotFoundException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
- }
-
- public EntryPointNotFoundException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
- }
-
- protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Enum.cs b/src/mscorlib/src/System/Enum.cs
index 97cfdf1b23..489f36739c 100644
--- a/src/mscorlib/src/System/Enum.cs
+++ b/src/mscorlib/src/System/Enum.cs
@@ -12,7 +12,7 @@ using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System
+namespace System
{
[Serializable]
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
@@ -69,7 +69,7 @@ namespace System
case CorElementType.U8:
return (*(ulong*)pValue).ToString("X16", null);
default:
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
+ throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
}
@@ -103,7 +103,7 @@ namespace System
return ((UInt64)(Int64)value).ToString("X16", null);
// All unsigned types will be directly cast
default:
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
+ throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
@@ -139,7 +139,7 @@ namespace System
}
}
- private static String InternalFlagsFormat(RuntimeType eT,ulong result)
+ private static String InternalFlagsFormat(RuntimeType eT, ulong result)
{
// These values are sorted by value. Don't change this
TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true);
@@ -250,7 +250,7 @@ namespace System
break;
// All unsigned types will be directly cast
default:
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
+ throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
return result;
@@ -273,11 +273,11 @@ namespace System
#region Public Static Methods
private enum ParseFailureKind
{
- None = 0,
- Argument = 1,
- ArgumentNull = 2,
+ None = 0,
+ Argument = 1,
+ ArgumentNull = 2,
ArgumentWithParameter = 3,
- UnhandledException = 4
+ UnhandledException = 4
}
// This will store the result of the parsing.
@@ -316,20 +316,20 @@ namespace System
switch (m_failure)
{
case ParseFailureKind.Argument:
- return new ArgumentException(Environment.GetResourceString(m_failureMessageID));
+ return new ArgumentException(SR.GetResourceString(m_failureMessageID));
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureParameter);
case ParseFailureKind.ArgumentWithParameter:
- return new ArgumentException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
+ return new ArgumentException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
case ParseFailureKind.UnhandledException:
return m_innerException;
default:
Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure);
- return new ArgumentException(Environment.GetResourceString("Arg_EnumValueNotFound"));
+ return new ArgumentException(SR.Arg_EnumValueNotFound);
}
}
}
@@ -362,7 +362,7 @@ namespace System
bool retValue;
if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult))
- result = (TEnum)parseResult.parsedEnum;
+ result = (TEnum)parseResult.parsedEnum;
return retValue;
}
@@ -402,12 +402,13 @@ namespace System
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
- if (value == null) {
+ if (value == null)
+ {
parseResult.SetFailure(ParseFailureKind.ArgumentNull, nameof(value));
return false;
}
@@ -421,7 +422,8 @@ namespace System
break;
}
}
- if (firstNonWhitespaceIndex == -1) {
+ if (firstNonWhitespaceIndex == -1)
+ {
parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null);
return false;
}
@@ -466,8 +468,8 @@ namespace System
String[] enumNames = entry.Names;
ulong[] enumValues = entry.Values;
- StringComparison comparison = ignoreCase ?
- StringComparison.OrdinalIgnoreCase :
+ StringComparison comparison = ignoreCase ?
+ StringComparison.OrdinalIgnoreCase :
StringComparison.Ordinal;
int valueIndex = firstNonWhitespaceIndex;
@@ -490,7 +492,7 @@ namespace System
bool success = false;
for (int i = 0; i < enumNames.Length; i++)
{
- if (enumNames[i].Length == valueSubstringLength &&
+ if (enumNames[i].Length == valueSubstringLength &&
string.Compare(enumNames[i], 0, value, valueIndex, valueSubstringLength, comparison) == 0)
{
result |= enumValues[i];
@@ -553,7 +555,7 @@ namespace System
// Get all of the values
return GetCachedValuesAndNames(enumType, false).Values;
}
-
+
public static String GetName(Type enumType, Object value)
{
if (enumType == null)
@@ -590,28 +592,28 @@ namespace System
switch (typeCode)
{
- case TypeCode.Int32 :
+ case TypeCode.Int32:
return ToObject(enumType, (int)value);
- case TypeCode.SByte :
+ case TypeCode.SByte:
return ToObject(enumType, (sbyte)value);
- case TypeCode.Int16 :
+ case TypeCode.Int16:
return ToObject(enumType, (short)value);
- case TypeCode.Int64 :
+ case TypeCode.Int64:
return ToObject(enumType, (long)value);
- case TypeCode.UInt32 :
+ case TypeCode.UInt32:
return ToObject(enumType, (uint)value);
- case TypeCode.Byte :
+ case TypeCode.Byte:
return ToObject(enumType, (byte)value);
- case TypeCode.UInt16 :
+ case TypeCode.UInt16:
return ToObject(enumType, (ushort)value);
- case TypeCode.UInt64 :
+ case TypeCode.UInt64:
return ToObject(enumType, (ulong)value);
case TypeCode.Char:
@@ -622,7 +624,7 @@ namespace System
default:
// All unsigned types will be directly cast
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), nameof(value));
+ throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
}
}
@@ -635,14 +637,14 @@ namespace System
return enumType.IsEnumDefined(value);
}
-
+
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
throw new ArgumentNullException(nameof(value));
@@ -653,7 +655,7 @@ namespace System
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
// Check if both of them are of the same type
Type valueType = value.GetType();
@@ -661,31 +663,32 @@ namespace System
Type underlyingType = GetUnderlyingType(enumType);
// If the value is an Enum then we need to extract the underlying value from it
- if (valueType.IsEnum) {
-
+ if (valueType.IsEnum)
+ {
if (!valueType.IsEquivalentTo(enumType))
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), enumType.ToString()));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), enumType.ToString()));
if (format.Length != 1)
{
// all acceptable format string are of length 1
- throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
return ((Enum)value).ToString(format);
}
// The value must be of the same type as the Underlying type of the Enum
- else if (valueType != underlyingType) {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString()));
+ else if (valueType != underlyingType)
+ {
+ throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString()));
}
if (format.Length != 1)
{
// all acceptable format string are of length 1
- throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'G' || formatCh == 'g')
- return GetEnumName(rtType, ToUInt64(value));
+ return GetEnumName(rtType, ToUInt64(value)) ?? value.ToString();
if (formatCh == 'D' || formatCh == 'd')
return value.ToString();
@@ -696,7 +699,7 @@ namespace System
if (formatCh == 'F' || formatCh == 'f')
return Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString();
- throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
#endregion
@@ -884,7 +887,7 @@ namespace System
#endregion
#region IFormattable
- [Obsolete("The provider argument is not used. Please use ToString(String).")]
+ [Obsolete("The provider argument is not used. Please use ToString(String).")]
public String ToString(String format, IFormatProvider provider)
{
return ToString(format);
@@ -900,10 +903,10 @@ namespace System
if (this == null)
throw new NullReferenceException();
Contract.EndContractBlock();
-
+
int ret = InternalCompareTo(this, target);
- if (ret < retIncompatibleMethodTables)
+ if (ret < retIncompatibleMethodTables)
{
// -1, 0 and 1 are the normal return codes
return ret;
@@ -913,26 +916,26 @@ namespace System
Type thisType = this.GetType();
Type targetType = target.GetType();
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType",
- targetType.ToString(), thisType.ToString()));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, targetType.ToString(), thisType.ToString()));
}
else
{
// assert valid return code (3)
Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
-
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
+
+ throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
#endregion
#region Public Methods
- public String ToString(String format) {
+ public String ToString(String format)
+ {
char formatCh;
if (format == null || format.Length == 0)
formatCh = 'G';
else if (format.Length != 1)
- throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
else
formatCh = format[0];
@@ -948,7 +951,7 @@ namespace System
if (formatCh == 'F' || formatCh == 'f')
return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString();
- throw new FormatException(Environment.GetResourceString("Format_InvalidEnumFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
@@ -957,13 +960,15 @@ namespace System
return ToString();
}
- public Boolean HasFlag(Enum flag) {
+ public Boolean HasFlag(Enum flag)
+ {
if (flag == null)
throw new ArgumentNullException(nameof(flag));
Contract.EndContractBlock();
-
- if (!this.GetType().IsEquivalentTo(flag.GetType())) {
- throw new ArgumentException(Environment.GetResourceString("Argument_EnumTypeDoesNotMatch", flag.GetType(), this.GetType()));
+
+ if (!this.GetType().IsEquivalentTo(flag.GetType()))
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType()));
}
return InternalHasFlag(flag);
@@ -997,101 +1002,86 @@ namespace System
case CorElementType.U8:
return TypeCode.UInt64;
default:
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
+ throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider)
+ bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider)
+ char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider)
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider)
+ byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider)
+ short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider)
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider)
+ int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider)
+ uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider)
+ long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider)
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider)
+ float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider)
+ double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Enum", "DateTime"));
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider)
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
#endregion
-
+
#region ToObject
[CLSCompliant(false)]
public static Object ToObject(Type enumType, sbyte value)
@@ -1099,11 +1089,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1112,11 +1102,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1125,11 +1115,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1138,11 +1128,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1152,11 +1142,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1166,11 +1156,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1179,11 +1169,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1193,11 +1183,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, unchecked((long)value));
}
@@ -1206,11 +1196,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
@@ -1219,11 +1209,11 @@ namespace System
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
Contract.EndContractBlock();
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(enumType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value ? 1 : 0);
}
#endregion
diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs
index 8fa4ce4ff5..b9070ae713 100644
--- a/src/mscorlib/src/System/Environment.cs
+++ b/src/mscorlib/src/System/Environment.cs
@@ -11,7 +11,9 @@
**
**
============================================================*/
-namespace System {
+
+namespace System
+{
using System.IO;
using System.Security;
using System.Resources;
@@ -37,145 +39,37 @@ namespace System {
Machine = 2,
}
- public static partial class Environment
+ internal static partial class Environment
{
// Assume the following constants include the terminating '\0' - use <, not <=
- const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value
+ private const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value
// System environment variables are stored in the registry, and have
// a size restriction that is separate from both normal environment
// variables and registry value name lengths, according to MSDN.
// MSDN doesn't detail whether the name is limited to 1024, or whether
// that includes the contents of the environment variable.
- const int MaxSystemEnvVariableLength = 1024;
- const int MaxUserEnvVariableLength = 255;
+ private const int MaxSystemEnvVariableLength = 1024;
+ private const int MaxUserEnvVariableLength = 255;
+ private const int MaxMachineNameLength = 256;
- internal sealed class ResourceHelper
+ // Looks up the resource string value for key.
+ //
+ // if you change this method's signature then you must change the code that calls it
+ // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
+ // as well as metasig.h to create the new signature type
+ internal static String GetResourceStringLocal(String key)
{
- internal ResourceHelper(String name) {
- m_name = name;
- }
-
- private String m_name;
- private ResourceManager SystemResMgr;
-
- // To avoid infinite loops when calling GetResourceString. See comments
- // in GetResourceString for this field.
- private List<string> currentlyLoading;
-
- // process-wide state (since this is only used in one domain),
- // used to avoid the TypeInitialization infinite recusion
- // in GetResourceStringCode
- internal bool resourceManagerInited = false;
-
- // Is this thread currently doing infinite resource lookups?
- private int infinitelyRecursingCount;
-
- internal String GetResourceString(String key) {
- if (key == null || key.Length == 0) {
- Debug.Assert(false, "Environment::GetResourceString with null or empty key. Bug in caller, or weird recursive loading problem?");
- return "[Resource lookup failed - null or empty resource name]";
- }
-
- // We have a somewhat common potential for infinite
- // loops with mscorlib's ResourceManager. If "potentially dangerous"
- // code throws an exception, we will get into an infinite loop
- // inside the ResourceManager and this "potentially dangerous" code.
- // Potentially dangerous code includes the IO package, CultureInfo,
- // parts of the loader, some parts of Reflection, Security (including
- // custom user-written permissions that may parse an XML file at
- // class load time), assembly load event handlers, etc. Essentially,
- // this is not a bounded set of code, and we need to fix the problem.
- // Fortunately, this is limited to mscorlib's error lookups and is NOT
- // a general problem for all user code using the ResourceManager.
-
- // The solution is to make sure only one thread at a time can call
- // GetResourceString. Also, since resource lookups can be
- // reentrant, if the same thread comes into GetResourceString
- // twice looking for the exact same resource name before
- // returning, we're going into an infinite loop and we should
- // return a bogus string.
-
- bool lockTaken = false;
- try
- {
- Monitor.Enter(this, ref lockTaken);
-
- // Are we recursively looking up the same resource? Note - our backout code will set
- // the ResourceHelper's currentlyLoading stack to null if an exception occurs.
- if (currentlyLoading != null && currentlyLoading.Count > 0 && currentlyLoading.LastIndexOf(key) != -1)
- {
- // We can start infinitely recursing for one resource lookup,
- // then during our failure reporting, start infinitely recursing again.
- // avoid that.
- if (infinitelyRecursingCount > 0)
- {
- return "[Resource lookup failed - infinite recursion or critical failure detected.]";
- }
- infinitelyRecursingCount++;
-
- // Note: our infrastructure for reporting this exception will again cause resource lookup.
- // This is the most direct way of dealing with that problem.
- string message = $"Infinite recursion during resource lookup within {System.CoreLib.Name}. This may be a bug in {System.CoreLib.Name}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: {key}";
- Assert.Fail("[Recursive resource lookup bug]", message, Assert.COR_E_FAILFAST, System.Diagnostics.StackTrace.TraceFormat.NoResourceLookup);
- Environment.FailFast(message);
- }
- if (currentlyLoading == null)
- currentlyLoading = new List<string>();
-
- // Call class constructors preemptively, so that we cannot get into an infinite
- // loop constructing a TypeInitializationException. If this were omitted,
- // we could get the Infinite recursion assert above by failing type initialization
- // between the Push and Pop calls below.
- if (!resourceManagerInited)
- {
- RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle);
- RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle);
- RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle);
- RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle);
- resourceManagerInited = true;
- }
-
- currentlyLoading.Add(key); // Push
-
- if (SystemResMgr == null)
- {
- SystemResMgr = new ResourceManager(m_name, typeof(Object).Assembly);
- }
- string s = SystemResMgr.GetString(key, null);
- currentlyLoading.RemoveAt(currentlyLoading.Count - 1); // Pop
-
- Debug.Assert(s != null, "Managed resource string lookup failed. Was your resource name misspelled? Did you rebuild mscorlib after adding a resource to resources.txt? Debug this w/ cordbg and bug whoever owns the code that called Environment.GetResourceString. Resource name was: \"" + key + "\"");
- return s;
- }
- catch
- {
- if (lockTaken)
- {
- // Backout code - throw away potentially corrupt state
- SystemResMgr = null;
- currentlyLoading = null;
- }
- throw;
- }
- finally
- {
- if (lockTaken)
- {
- Monitor.Exit(this);
- }
- }
- }
+ return SR.GetResourceString(key);
}
- private static volatile ResourceHelper m_resHelper; // Doesn't need to be initialized as they're zero-init.
-
- private const int MaxMachineNameLength = 256;
-
// 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) {
+ private static Object InternalSyncObject
+ {
+ get
+ {
+ if (s_InternalSyncObject == null)
+ {
Object o = new Object();
Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
}
@@ -192,25 +86,28 @@ namespace System {
**Arguments: None
**Exceptions: None
==============================================================================*/
- public static extern int TickCount {
+ public static extern int TickCount
+ {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
-
+
// Terminates this process with the given exit code.
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void _Exit(int exitCode);
- public static void Exit(int exitCode) {
+ public static void Exit(int exitCode)
+ {
_Exit(exitCode);
}
- public static extern int ExitCode {
+ public static extern int ExitCode
+ {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
@@ -246,22 +143,26 @@ namespace System {
==============================================================================*/
internal static String CurrentDirectory
{
- get{
+ get
+ {
return Directory.GetCurrentDirectory();
}
- set {
+ set
+ {
Directory.SetCurrentDirectory(value);
}
}
// Returns the system directory (ie, C:\WinNT\System32).
- internal static String SystemDirectory {
- get {
+ internal static String SystemDirectory
+ {
+ get
+ {
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) __Error.WinIOError();
String path = sb.ToString();
return path;
@@ -274,16 +175,11 @@ namespace System {
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
- if (name.Length == 0) {
+ if (name.Length == 0)
+ {
return name;
}
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode()) {
- // Environment variable accessors are not approved modern API.
- // Behave as if no variables are defined in this case.
- return name;
- }
-
int currentSize = 100;
StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size
@@ -314,8 +210,9 @@ namespace System {
size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize);
if (size == 0)
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
-
- while (size > currentSize) {
+
+ while (size > currentSize)
+ {
currentSize = size;
blob.Capacity = currentSize;
blob.Length = 0;
@@ -329,32 +226,14 @@ namespace System {
return blob.ToString();
}
- public static String MachineName {
- get {
-
- // UWP Debug scenarios
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Getting Computer Name is not a supported scenario on Store apps.
- throw new PlatformNotSupportedException();
- }
-
- // In future release of operating systems, you might be able to rename a machine without
- // rebooting. Therefore, don't cache this machine name.
- StringBuilder buf = new StringBuilder(MaxMachineNameLength);
- int len = MaxMachineNameLength;
- if (Win32Native.GetComputerName(buf, ref len) == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ComputerName"));
- return buf.ToString();
- }
- }
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern Int32 GetProcessorCount();
- public static int ProcessorCount {
- get {
+ public static int ProcessorCount
+ {
+ get
+ {
return GetProcessorCount();
}
}
@@ -381,7 +260,7 @@ namespace System {
* So our best bet is to simply use the commandLine that was used to invoke the process.
* in case it is present.
*/
- if(s_CommandLineArgs != null)
+ if (s_CommandLineArgs != null)
return (string[])s_CommandLineArgs.Clone();
return GetCommandLineArgsNative();
@@ -450,91 +329,70 @@ namespace System {
**Arguments: None.
**Exceptions: None.
==============================================================================*/
- public static String NewLine {
- get {
+ public static String NewLine
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
-#if !PLATFORM_UNIX
+#if PLATFORM_WINDOWS
return "\r\n";
#else
return "\n";
-#endif // !PLATFORM_UNIX
+#endif // PLATFORM_WINDOWS
}
}
-
+
/*===================================Version====================================
**Action: Returns the COM+ version struct, describing the build number.
**Returns:
**Arguments:
**Exceptions:
==============================================================================*/
- public static Version Version {
- get {
-
+ public static Version Version
+ {
+ get
+ {
// Previously this represented the File version of mscorlib.dll. Many other libraries in the framework and outside took dependencies on the first three parts of this version
// remaining constant throughout 4.x. From 4.0 to 4.5.2 this was fine since the file version only incremented the last part.Starting with 4.6 we switched to a file versioning
// scheme that matched the product version. In order to preserve compatibility with existing libraries, this needs to be hard-coded.
-
- return new Version(4,0,30319,42000);
- }
- }
-
- /*==================================OSVersion===================================
- **Action:
- **Returns:
- **Arguments:
- **Exceptions:
- ==============================================================================*/
- internal static OperatingSystem OSVersion {
- get {
- Contract.Ensures(Contract.Result<OperatingSystem>() != null);
-
- if (m_os==null) { // We avoid the lock since we don't care if two threads will set this at the same time.
-
- Microsoft.Win32.Win32Native.OSVERSIONINFO osvi = new Microsoft.Win32.Win32Native.OSVERSIONINFO();
- if (!GetVersion(osvi)) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GetVersion"));
- }
-
- Microsoft.Win32.Win32Native.OSVERSIONINFOEX osviEx = new Microsoft.Win32.Win32Native.OSVERSIONINFOEX();
- if (!GetVersionEx(osviEx))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GetVersion"));
-#if PLATFORM_UNIX
- PlatformID id = PlatformID.Unix;
-#else
- PlatformID id = PlatformID.Win32NT;
-#endif // PLATFORM_UNIX
-
- Version v = new Version(osvi.MajorVersion, osvi.MinorVersion, osvi.BuildNumber, (osviEx.ServicePackMajor << 16) |osviEx.ServicePackMinor);
- m_os = new OperatingSystem(id, v, osvi.CSDVersion);
- }
- Debug.Assert(m_os != null, "m_os != null");
- return m_os;
+ return new Version(4, 0, 30319, 42000);
}
}
+#if !FEATURE_PAL
+ private static Lazy<bool> s_IsWindows8OrAbove = new Lazy<bool>(() =>
+ {
+ ulong conditionMask = Win32Native.VerSetConditionMask(0, Win32Native.VER_MAJORVERSION, Win32Native.VER_GREATER_EQUAL);
+ conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_MINORVERSION, Win32Native.VER_GREATER_EQUAL);
+ conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMAJOR, Win32Native.VER_GREATER_EQUAL);
+ conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMINOR, Win32Native.VER_GREATER_EQUAL);
- internal static bool IsWindows8OrAbove {
- get {
- return true;
- }
- }
-
+ // Windows 8 version is 6.2
+ var version = new Win32Native.OSVERSIONINFOEX { MajorVersion = 6, MinorVersion = 2, ServicePackMajor = 0, ServicePackMinor = 0 };
+
+ return Win32Native.VerifyVersionInfoW(version,
+ Win32Native.VER_MAJORVERSION | Win32Native.VER_MINORVERSION | Win32Native.VER_SERVICEPACKMAJOR | Win32Native.VER_SERVICEPACKMINOR,
+ conditionMask);
+ });
+ internal static bool IsWindows8OrAbove => s_IsWindows8OrAbove.Value;
+#endif
+
#if FEATURE_COMINTEROP
- internal static bool IsWinRTSupported {
- get {
- return true;
- }
- }
-#endif // FEATURE_COMINTEROP
-
+ // Does the current version of Windows have Windows Runtime suppport?
+ private static Lazy<bool> s_IsWinRTSupported = new Lazy<bool>(() =>
+ {
+ return WinRTSupported();
+ });
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool GetVersion(Microsoft.Win32.Win32Native.OSVERSIONINFO osVer);
+ internal static bool IsWinRTSupported => s_IsWinRTSupported.Value;
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool GetVersionEx(Microsoft.Win32.Win32Native.OSVERSIONINFOEX osVer);
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool WinRTSupported();
+#endif // FEATURE_COMINTEROP
/*==================================StackTrace==================================
@@ -543,11 +401,13 @@ namespace System {
**Arguments:
**Exceptions:
==============================================================================*/
- public static String StackTrace {
- get {
+ public static String StackTrace
+ {
+ [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
-
- return GetStackTrace(null, true);
+ return Internal.Runtime.Augments.EnvironmentAugments.StackTrace;
}
}
@@ -564,104 +424,19 @@ namespace System {
st = new StackTrace(e, needFileInfo);
// Do no include a trailing newline for backwards compatibility
- return st.ToString( System.Diagnostics.StackTrace.TraceFormat.Normal );
- }
-
- private static void InitResourceHelper() {
- // Only the default AppDomain should have a ResourceHelper. All calls to
- // GetResourceString from any AppDomain delegate to GetResourceStringLocal
- // in the default AppDomain via the fcall GetResourceFromDefault.
-
- bool tookLock = false;
- RuntimeHelpers.PrepareConstrainedRegions();
- try {
-
- Monitor.Enter(Environment.InternalSyncObject, ref tookLock);
-
- if (m_resHelper == null) {
- ResourceHelper rh = new ResourceHelper(System.CoreLib.Name);
-
- System.Threading.Thread.MemoryBarrier();
- m_resHelper =rh;
- }
- }
- finally {
- if (tookLock)
- Monitor.Exit(Environment.InternalSyncObject);
- }
- }
-
- // Looks up the resource string value for key.
- //
- // if you change this method's signature then you must change the code that calls it
- // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature
- // as well as metasig.h to create the new signature type
- // NoInlining causes the caller and callee to not be inlined in mscorlib as it is an assumption of StackCrawlMark use
- [MethodImpl(MethodImplOptions.NoInlining)]
- internal static String GetResourceStringLocal(String key) {
- if (m_resHelper == null)
- InitResourceHelper();
-
- return m_resHelper.GetResourceString(key);
- }
-
- internal static String GetResourceString(String key) {
- return GetResourceStringLocal(key);
- }
-
- // The reason the following overloads exist are to reduce code bloat.
- // Since GetResourceString is basically only called when exceptions are
- // thrown, we want the code size to be as small as possible.
- // Using the params object[] overload works against this since the
- // initialization of the array is done inline in the caller at the IL
- // level. So we have overloads that simply wrap the params one, and
- // the methods they call through to are tagged as NoInlining.
- // In mscorlib NoInlining causes the caller and callee to not be inlined
- // as it is an assumption of StackCrawlMark use so it is not added
- // directly to these methods, but to the ones they call.
- // That way they do not bloat either the IL or the generated asm.
-
- internal static string GetResourceString(string key, object val0)
- {
- return GetResourceStringFormatted(key, new object[] { val0 });
- }
-
- internal static string GetResourceString(string key, object val0, object val1)
- {
- return GetResourceStringFormatted(key, new object[] { val0, val1 });
- }
-
- internal static string GetResourceString(string key, object val0, object val1, object val2)
- {
- return GetResourceStringFormatted(key, new object[] { val0, val1, val2 });
- }
-
- internal static string GetResourceString(string key, object val0, object val1, object val2, object val3)
- {
- return GetResourceStringFormatted(key, new object[] { val0, val1, val2, val3 });
- }
-
- internal static String GetResourceString(string key, params object[] values)
- {
- return GetResourceStringFormatted(key, values);
+ return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal);
}
- // NoInlining causes the caller and callee to not be inlined in mscorlib as it is an assumption of StackCrawlMark use
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static String GetResourceStringFormatted(string key, params object[] values)
+ public static extern bool HasShutdownStarted
{
- string rs = GetResourceString(key);
- return String.Format(CultureInfo.CurrentCulture, rs, values);
- }
-
- public static extern bool HasShutdownStarted {
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
internal static bool UserInteractive
{
- get {
+ get
+ {
return true;
}
}
@@ -684,11 +459,11 @@ namespace System {
// TODO: Consider flushing the executionIdCache on Wait operations or similar
// actions that are likely to result in changing the executing core
[ThreadStatic]
- static int t_executionIdCache;
+ private static int t_executionIdCache;
- const int ExecutionIdCacheShift = 16;
- const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1;
- const int ExecutionIdRefreshRate = 5000;
+ private const int ExecutionIdCacheShift = 16;
+ private const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1;
+ private const int ExecutionIdRefreshRate = 5000;
private static int RefreshExecutionId()
{
@@ -784,19 +559,19 @@ namespace System {
}
if (variable.Length == 0)
{
- throw new ArgumentException(GetResourceString("Argument_StringZeroLength"), nameof(variable));
+ throw new ArgumentException(SR.Argument_StringZeroLength, nameof(variable));
}
if (variable[0] == '\0')
{
- throw new ArgumentException(GetResourceString("Argument_StringFirstCharIsZero"), nameof(variable));
+ throw new ArgumentException(SR.Argument_StringFirstCharIsZero, nameof(variable));
}
if (variable.Length >= MaxEnvVariableValueLength)
{
- throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
+ throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
if (variable.IndexOf('=') != -1)
{
- throw new ArgumentException(GetResourceString("Argument_IllegalEnvVarName"), nameof(variable));
+ throw new ArgumentException(SR.Argument_IllegalEnvVarName, nameof(variable));
}
if (string.IsNullOrEmpty(value) || value[0] == '\0')
@@ -806,7 +581,7 @@ namespace System {
}
else if (value.Length >= MaxEnvVariableValueLength)
{
- throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(value));
+ throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(value));
}
}
@@ -816,7 +591,7 @@ namespace System {
target != EnvironmentVariableTarget.Machine &&
target != EnvironmentVariableTarget.User)
{
- throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(GetResourceString("Arg_EnumIllegalVal"), target));
+ throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target));
}
}
@@ -867,13 +642,6 @@ namespace System {
private static string GetEnvironmentVariableCore(string variable)
{
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Environment variable accessors are not approved modern API.
- // Behave as if the variable was not found in this case.
- return null;
- }
-
StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size
int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity);
@@ -917,7 +685,7 @@ namespace System {
}
else
{
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
@@ -929,13 +697,6 @@ namespace System {
private static IDictionary GetEnvironmentVariablesCore()
{
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Environment variable accessors are not approved modern API.
- // Behave as if no environment variables are defined in this case.
- return new Dictionary<string, string>(0);
- }
-
return GetRawEnvironmentVariables();
}
@@ -963,7 +724,7 @@ namespace System {
}
else
{
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false))
@@ -987,13 +748,6 @@ namespace System {
if (string.IsNullOrEmpty(value) || value[0] == '\0')
value = null;
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXDesignMode())
- {
- // Environment variable accessors are not approved modern API.
- // so we throw PlatformNotSupportedException.
- throw new PlatformNotSupportedException();
- }
-
if (!Win32Native.SetEnvironmentVariable(variable, value))
{
int errorCode = Marshal.GetLastWin32Error();
@@ -1006,7 +760,7 @@ namespace System {
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
// The error message from Win32 is "The filename or extension is too long",
// which is not accurate.
- throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"));
+ throw new ArgumentException(SR.Format(SR.Argument_LongEnvVarValue));
default:
throw new ArgumentException(Win32Native.GetMessage(errorCode));
}
@@ -1045,7 +799,7 @@ namespace System {
const int MaxUserEnvVariableLength = 255;
if (variable.Length >= MaxUserEnvVariableLength)
{
- throw new ArgumentException(GetResourceString("Argument_LongEnvVarValue"), nameof(variable));
+ throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable));
}
baseKey = Registry.CurrentUser;
@@ -1053,7 +807,7 @@ namespace System {
}
else
{
- throw new ArgumentException(GetResourceString("Arg_EnumIllegalVal", (int)target));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target));
}
using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true))
@@ -1066,7 +820,7 @@ namespace System {
}
else
{
- environmentKey.SetValue(variable, value);
+ environmentKey.SetStringValue(variable, value);
}
}
}
diff --git a/src/mscorlib/src/System/EventHandler.cs b/src/mscorlib/src/System/EventHandler.cs
deleted file mode 100644
index e6923cf637..0000000000
--- a/src/mscorlib/src/System/EventHandler.cs
+++ /dev/null
@@ -1,14 +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;
-
-namespace System
-{
- [Serializable]
- public delegate void EventHandler(Object sender, EventArgs e);
-
- [Serializable]
- public delegate void EventHandler<TEventArgs>(Object sender, TEventArgs e); // Removed TEventArgs constraint post-.NET 4
-}
diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs
index a166c1ab0a..263b6b3c65 100644
--- a/src/mscorlib/src/System/Exception.cs
+++ b/src/mscorlib/src/System/Exception.cs
@@ -11,7 +11,8 @@
**
=============================================================================*/
-namespace System {
+namespace System
+{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -36,55 +37,57 @@ namespace System {
_dynamicMethods = null;
HResult = __HResults.COR_E_EXCEPTION;
_xcode = _COMPlusExceptionCode;
- _xptrs = (IntPtr) 0;
+ _xptrs = (IntPtr)0;
// Initialize the WatsonBuckets to be null
_watsonBuckets = null;
// Initialize the watson bucketing IP
_ipForWatsonBuckets = UIntPtr.Zero;
-
}
- public Exception() {
+ public Exception()
+ {
Init();
}
-
- public Exception(String message) {
+
+ public Exception(String message)
+ {
Init();
_message = message;
}
-
+
// Creates a new Exception. All derived classes should
// provide this constructor.
// Note: the stack trace is not started until the exception
// is thrown
//
- public Exception (String message, Exception innerException) {
+ public Exception(String message, Exception innerException)
+ {
Init();
_message = message;
_innerException = innerException;
}
- protected Exception(SerializationInfo info, StreamingContext context)
+ protected Exception(SerializationInfo info, StreamingContext context)
{
- if (info==null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
-
+
_className = info.GetString("ClassName");
_message = info.GetString("Message");
- _data = (IDictionary)(info.GetValueNoThrow("Data",typeof(IDictionary)));
- _innerException = (Exception)(info.GetValue("InnerException",typeof(Exception)));
+ _data = (IDictionary)(info.GetValueNoThrow("Data", typeof(IDictionary)));
+ _innerException = (Exception)(info.GetValue("InnerException", typeof(Exception)));
_helpURL = info.GetString("HelpURL");
_stackTraceString = info.GetString("StackTraceString");
_remoteStackTraceString = info.GetString("RemoteStackTraceString");
_remoteStackIndex = info.GetInt32("RemoteStackIndex");
- _exceptionMethodString = (String)(info.GetValue("ExceptionMethod",typeof(String)));
+ _exceptionMethodString = (String)(info.GetValue("ExceptionMethod", typeof(String)));
HResult = info.GetInt32("HResult");
_source = info.GetString("Source");
-
+
// Get the WatsonBuckets that were serialized - this is particularly
// done to support exceptions going across AD transitions.
//
@@ -94,9 +97,9 @@ namespace System {
_watsonBuckets = (Object)info.GetValueNoThrow("WatsonBuckets", typeof(byte[]));
- if (_className == null || HResult==0)
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
-
+ if (_className == null || HResult == 0)
+ throw new SerializationException(SR.Serialization_InsufficientState);
+
// If we are constructing a new exception after a cross-appdomain call...
if (context.State == StreamingContextStates.CrossAppDomain)
{
@@ -115,30 +118,37 @@ namespace System {
_stackTraceString = null;
}
}
-
-
- public virtual String Message {
- get {
- if (_message == null) {
- if (_className==null) {
+
+
+ public virtual String Message
+ {
+ get
+ {
+ if (_message == null)
+ {
+ if (_className == null)
+ {
_className = GetClassName();
}
- return Environment.GetResourceString("Exception_WasThrown", _className);
-
- } else {
+ return SR.Format(SR.Exception_WasThrown, _className);
+ }
+ else
+ {
return _message;
}
}
}
- public virtual IDictionary Data {
- get {
+ public virtual IDictionary Data
+ {
+ get
+ {
if (_data == null)
if (IsImmutableAgileException(this))
_data = new EmptyReadOnlyDictionaryInternal();
else
_data = new ListDictionaryInternal();
-
+
return _data;
}
}
@@ -163,22 +173,22 @@ namespace System {
internal __RestrictedErrorObject(object errorObject)
{
- _realErrorObject = errorObject;
+ _realErrorObject = errorObject;
}
public object RealErrorObject
{
- get
- {
- return _realErrorObject;
- }
+ get
+ {
+ return _realErrorObject;
+ }
}
}
[FriendAccessAllowed]
internal void AddExceptionDataForRestrictedErrorInfo(
- string restrictedError,
- string restrictedErrorReference,
+ string restrictedError,
+ string restrictedErrorReference,
string restrictedCapabilitySid,
object restrictedErrorObject,
bool hasrestrictedLanguageErrorObject = false)
@@ -223,26 +233,28 @@ namespace System {
return _className;
}
-
+
// Retrieves the lowest exception (inner most) for the given Exception.
// This will traverse exceptions using the innerException property.
//
- public virtual Exception GetBaseException()
+ public virtual Exception GetBaseException()
{
Exception inner = InnerException;
Exception back = this;
-
- while (inner != null) {
+
+ while (inner != null)
+ {
back = inner;
inner = inner.InnerException;
}
-
+
return back;
}
-
+
// Returns the inner exception contained in this exception
//
- public Exception InnerException {
+ public Exception InnerException
+ {
get { return _innerException; }
}
@@ -260,36 +272,44 @@ namespace System {
return RuntimeType.GetMethodBase(method);
}
-
- public MethodBase TargetSite {
- get {
+
+ public MethodBase TargetSite
+ {
+ get
+ {
return GetTargetSiteInternal();
}
}
-
+
// this function is provided as a private helper to avoid the security demand
- private MethodBase GetTargetSiteInternal() {
- if (_exceptionMethod!=null) {
+ private MethodBase GetTargetSiteInternal()
+ {
+ if (_exceptionMethod != null)
+ {
return _exceptionMethod;
}
- if (_stackTrace==null) {
+ if (_stackTrace == null)
+ {
return null;
}
- if (_exceptionMethodString!=null) {
+ if (_exceptionMethodString != null)
+ {
_exceptionMethod = GetExceptionMethodFromString();
- } else {
+ }
+ else
+ {
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
return _exceptionMethod;
}
-
+
// Returns the stack trace as a string. If no stack trace is
// available, null is returned.
public virtual String StackTrace
{
- get
+ get
{
// By default attempt to include file and line number info
return GetStackTrace(true);
@@ -322,14 +342,14 @@ namespace System {
// don't store the stack trace string in the _stackTraceString member variable.
String tempStackTraceString = Environment.GetStackTrace(this, needFileInfo);
return remoteStackTraceString + tempStackTraceString;
- }
-
+ }
+
[FriendAccessAllowed]
internal void SetErrorCode(int hr)
{
HResult = hr;
}
-
+
// Sets the help link for this exception.
// This should be in a URL/URN form, such as:
// "file:///C:/Applications/Bazzal/help.html#ErrorNum42"
@@ -345,13 +365,15 @@ namespace System {
_helpURL = value;
}
}
-
- public virtual String Source {
- get {
+
+ public virtual String Source
+ {
+ get
+ {
if (_source == null)
{
- StackTrace st = new StackTrace(this,true);
- if (st.FrameCount>0)
+ StackTrace st = new StackTrace(this, true);
+ if (st.FrameCount > 0)
{
StackFrame sf = st.GetFrame(0);
MethodBase method = sf.GetMethod();
@@ -366,7 +388,7 @@ namespace System {
if (moduleBuilder != null)
rtModule = moduleBuilder.InternalModule;
else
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeReflectionObject"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject);
}
_source = rtModule.GetRuntimeAssembly().GetSimpleName();
@@ -383,21 +405,24 @@ namespace System {
return ToString(true, true);
}
- private String ToString(bool needFileLineInfo, bool needMessage) {
+ private String ToString(bool needFileLineInfo, bool needMessage)
+ {
String message = (needMessage ? Message : null);
String s;
- if (message == null || message.Length <= 0) {
+ if (message == null || message.Length <= 0)
+ {
s = GetClassName();
}
- else {
+ else
+ {
s = GetClassName() + ": " + message;
}
- if (_innerException!=null) {
- s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
- " " + Environment.GetResourceString("Exception_EndOfInnerExceptionStack");
-
+ if (_innerException != null)
+ {
+ s = s + " ---> " + _innerException.ToString(needFileLineInfo, needMessage) + Environment.NewLine +
+ " " + SR.Exception_EndOfInnerExceptionStack;
}
string stackTrace = GetStackTrace(needFileLineInfo);
@@ -408,10 +433,12 @@ namespace System {
return s;
}
-
- private String GetExceptionMethodString() {
+
+ private String GetExceptionMethodString()
+ {
MethodBase methBase = GetTargetSiteInternal();
- if (methBase==null) {
+ if (methBase == null)
+ {
return null;
}
if (methBase is System.Reflection.Emit.DynamicMethod.RTDynamicMethod)
@@ -425,13 +452,14 @@ namespace System {
// only for serialization of the Exception Method.
char separator = '\n';
StringBuilder result = new StringBuilder();
- if (methBase is ConstructorInfo) {
+ if (methBase is ConstructorInfo)
+ {
RuntimeConstructorInfo rci = (RuntimeConstructorInfo)methBase;
Type t = rci.ReflectedType;
result.Append((int)MemberTypes.Constructor);
result.Append(separator);
result.Append(rci.Name);
- if (t!=null)
+ if (t != null)
{
result.Append(separator);
result.Append(t.Assembly.FullName);
@@ -440,7 +468,9 @@ namespace System {
}
result.Append(separator);
result.Append(rci.ToString());
- } else {
+ }
+ else
+ {
Debug.Assert(methBase is MethodInfo, "[Exception.GetExceptionMethodString]methBase is MethodInfo");
RuntimeMethodInfo rmi = (RuntimeMethodInfo)methBase;
Type t = rmi.DeclaringType;
@@ -457,14 +487,16 @@ namespace System {
}
result.Append(rmi.ToString());
}
-
+
return result.ToString();
}
- private MethodBase GetExceptionMethodFromString() {
+ private MethodBase GetExceptionMethodFromString()
+ {
Debug.Assert(_exceptionMethodString != null, "Method string cannot be NULL!");
- String[] args = _exceptionMethodString.Split(new char[]{'\0', '\n'});
- if (args.Length!=5) {
+ String[] args = _exceptionMethodString.Split(new char[] { '\0', '\n' });
+ if (args.Length != 5)
+ {
throw new SerializationException();
}
SerializationInfo si = new SerializationInfo(typeof(MemberInfoSerializationHolder), new FormatterConverter());
@@ -475,9 +507,12 @@ namespace System {
si.AddValue("Signature", args[4]);
MethodBase result;
StreamingContext sc = new StreamingContext(StreamingContextStates.All);
- try {
+ try
+ {
result = (MethodBase)new MemberInfoSerializationHolder(si, sc).GetRealObject(sc);
- } catch (SerializationException) {
+ }
+ catch (SerializationException)
+ {
result = null;
}
return result;
@@ -485,11 +520,11 @@ namespace System {
protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
{
- add { throw new PlatformNotSupportedException();}
- remove { throw new PlatformNotSupportedException();}
+ add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
+ remove { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); }
}
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
+ public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
@@ -497,25 +532,25 @@ namespace System {
}
Contract.EndContractBlock();
- String tempStackTraceString = _stackTraceString;
-
- if (_stackTrace!=null)
+ String tempStackTraceString = _stackTraceString;
+
+ if (_stackTrace != null)
{
- if (tempStackTraceString==null)
+ if (tempStackTraceString == null)
{
tempStackTraceString = Environment.GetStackTrace(this, true);
}
- if (_exceptionMethod==null)
+ if (_exceptionMethod == null)
{
_exceptionMethod = GetExceptionMethodFromStackTrace();
}
}
- if (_source == null)
+ if (_source == null)
{
_source = Source; // Set the Source information correctly before serialization
}
-
+
info.AddValue("ClassName", GetClassName(), typeof(String));
info.AddValue("Message", _message, typeof(String));
info.AddValue("Data", _data, typeof(IDictionary));
@@ -527,10 +562,9 @@ namespace System {
info.AddValue("ExceptionMethod", GetExceptionMethodString(), typeof(String));
info.AddValue("HResult", HResult);
info.AddValue("Source", _source, typeof(String));
-
+
// Serialize the Watson bucket details as well
info.AddValue("WatsonBuckets", _watsonBuckets, typeof(byte[]));
-
}
// This method will clear the _stackTrace of the exception object upon deserialization
@@ -547,7 +581,6 @@ namespace System {
//
// Hence, we set it to zero when deserialization takes place.
_ipForWatsonBuckets = UIntPtr.Zero;
-
}
// This is used by the runtime when re-throwing a managed exception. It will
@@ -583,11 +616,11 @@ namespace System {
{
_remoteStackTraceString = tmpStackTraceString + Environment.NewLine;
}
-
+
_stackTrace = null;
_stackTraceString = null;
}
-
+
// This is the object against which a lock will be taken
// when attempt to restore the EDI. Since its static, its possible
@@ -600,14 +633,15 @@ namespace System {
internal UIntPtr IPForWatsonBuckets
{
- get {
+ get
+ {
return _ipForWatsonBuckets;
- }
+ }
}
-
+
internal object WatsonBuckets
{
- get
+ get
{
return _watsonBuckets;
}
@@ -659,7 +693,7 @@ namespace System {
return null;
}
}
-
+
internal void GetStackTracesDeepCopy(out object currentStackTrace, out object dynamicMethodArray)
{
GetStackTracesDeepCopy(this, out currentStackTrace, out dynamicMethodArray);
@@ -680,7 +714,7 @@ namespace System {
// We do this inside a finally clause to ensure ThreadAbort cannot
// be injected while we have taken the lock. This is to prevent
// unrelated exception restorations from getting blocked due to TAE.
- try{}
+ try { }
finally
{
// When restoring back the fields, we again create a copy and set reference to them
@@ -689,14 +723,14 @@ namespace System {
//
// Since deep copying can throw on OOM, try to get the copies
// outside the lock.
- object _stackTraceCopy = (exceptionDispatchInfo.BinaryStackTraceArray == null)?null:DeepCopyStackTrace(exceptionDispatchInfo.BinaryStackTraceArray);
- object _dynamicMethodsCopy = (exceptionDispatchInfo.DynamicMethodArray == null)?null:DeepCopyDynamicMethods(exceptionDispatchInfo.DynamicMethodArray);
-
+ object _stackTraceCopy = (exceptionDispatchInfo.BinaryStackTraceArray == null) ? null : DeepCopyStackTrace(exceptionDispatchInfo.BinaryStackTraceArray);
+ object _dynamicMethodsCopy = (exceptionDispatchInfo.DynamicMethodArray == null) ? null : DeepCopyDynamicMethods(exceptionDispatchInfo.DynamicMethodArray);
+
// Finally, restore the information.
//
// Since EDI can be created at various points during exception dispatch (e.g. at various frames on the stack) for the same exception instance,
// they can have different data to be restored. Thus, to ensure atomicity of restoration from each EDI, perform the restore under a lock.
- lock(Exception.s_EDILock)
+ lock (Exception.s_EDILock)
{
_watsonBuckets = exceptionDispatchInfo.WatsonBuckets;
_ipForWatsonBuckets = exceptionDispatchInfo.IPForWatsonBuckets;
@@ -730,7 +764,7 @@ namespace System {
// DynamicMethodDescs alive for the lifetime of the exception. We do this because
// the _stackTrace field holds MethodDescs, and a DynamicMethodDesc can be destroyed
// unless a System.Resolver object roots it.
- private Object _dynamicMethods;
+ private Object _dynamicMethods;
#pragma warning restore 414
// @MANAGED: HResult is used from within the EE! Rename with care - check VM directory
@@ -747,7 +781,7 @@ namespace System {
_HResult = value;
}
}
-
+
private String _source; // Mainly used by VB.
// WARNING: Don't delete/rename _xptrs and _xcode - used by functions
// on Marshal class. Native functions are in COMUtilNative.cpp & AppDomain
@@ -769,7 +803,7 @@ namespace System {
// Get the current stack trace string.
return ToString(true, true);
}
-
+
// this method is required so Object.GetType is not made virtual by the compiler
// _Exception.GetType()
public new Type GetType()
@@ -779,7 +813,8 @@ namespace System {
internal bool IsTransient
{
- get {
+ get
+ {
return nIsTransient(_HResult);
}
}
@@ -824,12 +859,12 @@ namespace System {
// The Message field is set to the ToString() output of the original exception.
//--------------------------------------------------------------------------
- internal sealed class CrossAppDomainMarshaledException : SystemException
+ internal sealed class CrossAppDomainMarshaledException : SystemException
{
- public CrossAppDomainMarshaledException(String message, int errorCode)
- : base(message)
+ public CrossAppDomainMarshaledException(String message, int errorCode)
+ : base(message)
{
- SetErrorCode(errorCode);
+ HResult = errorCode;
}
// Normally, only Telesto's UEF will see these exceptions.
diff --git a/src/mscorlib/src/System/ExecutionEngineException.cs b/src/mscorlib/src/System/ExecutionEngineException.cs
deleted file mode 100644
index bebfd493a0..0000000000
--- a/src/mscorlib/src/System/ExecutionEngineException.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.
-
-//
-//
-/*=============================================================================
-**
-**
-**
-** Purpose: The exception class for misc execution engine exceptions.
-** Currently, its only used as a placeholder type when the EE
-** does a FailFast.
-**
-**
-=============================================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Obsolete("This type previously indicated an unspecified fatal error in the runtime. The runtime no longer raises this exception so this type is obsolete.")]
- [Serializable]
- public sealed class ExecutionEngineException : SystemException
- {
- public ExecutionEngineException()
- : base(SR.Arg_ExecutionEngineException)
- {
- HResult = __HResults.COR_E_EXECUTIONENGINE;
- }
-
- public ExecutionEngineException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_EXECUTIONENGINE;
- }
-
- public ExecutionEngineException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_EXECUTIONENGINE;
- }
-
- internal ExecutionEngineException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/FieldAccessException.cs b/src/mscorlib/src/System/FieldAccessException.cs
deleted file mode 100644
index ac62c0fcac..0000000000
--- a/src/mscorlib/src/System/FieldAccessException.cs
+++ /dev/null
@@ -1,39 +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 for class loading failures.
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class FieldAccessException : MemberAccessException
- {
- public FieldAccessException()
- : base(SR.Arg_FieldAccessException)
- {
- HResult = __HResults.COR_E_FIELDACCESS;
- }
-
- public FieldAccessException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_FIELDACCESS;
- }
-
- public FieldAccessException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_FIELDACCESS;
- }
-
- protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/FlagsAttribute.cs b/src/mscorlib/src/System/FlagsAttribute.cs
deleted file mode 100644
index 5f8c108ae4..0000000000
--- a/src/mscorlib/src/System/FlagsAttribute.cs
+++ /dev/null
@@ -1,22 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-
-namespace System
-{
- // Custom attribute to indicate that the enum
- // should be treated as a bitfield (or set of flags).
- // An IDE may use this information to provide a richer
- // development experience.
- [Serializable]
- [AttributeUsage(AttributeTargets.Enum, Inherited = false)]
- public class FlagsAttribute : Attribute
- {
- public FlagsAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/FormatException.cs b/src/mscorlib/src/System/FormatException.cs
deleted file mode 100644
index c5758e11cd..0000000000
--- a/src/mscorlib/src/System/FormatException.cs
+++ /dev/null
@@ -1,41 +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 to designate an illegal argument to FormatMessage.
-**
-**
-===========================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class FormatException : SystemException
- {
- public FormatException()
- : base(SR.Arg_FormatException)
- {
- HResult = __HResults.COR_E_FORMAT;
- }
-
- public FormatException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_FORMAT;
- }
-
- public FormatException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_FORMAT;
- }
-
- protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/FormattableString.cs b/src/mscorlib/src/System/FormattableString.cs
deleted file mode 100644
index 6369363b5d..0000000000
--- a/src/mscorlib/src/System/FormattableString.cs
+++ /dev/null
@@ -1,81 +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: implementation of the FormattableString
-** class.
-**
-===========================================================*/
-
-namespace System
-{
- /// <summary>
- /// A composite format string along with the arguments to be formatted. An instance of this
- /// type may result from the use of the C# or VB language primitive "interpolated string".
- /// </summary>
- public abstract class FormattableString : IFormattable
- {
- /// <summary>
- /// The composite format string.
- /// </summary>
- public abstract string Format { get; }
-
- /// <summary>
- /// Returns an object array that contains zero or more objects to format. Clients should not
- /// mutate the contents of the array.
- /// </summary>
- public abstract object[] GetArguments();
-
- /// <summary>
- /// The number of arguments to be formatted.
- /// </summary>
- public abstract int ArgumentCount { get; }
-
- /// <summary>
- /// Returns one argument to be formatted from argument position <paramref name="index"/>.
- /// </summary>
- public abstract object GetArgument(int index);
-
- /// <summary>
- /// Format to a string using the given culture.
- /// </summary>
- public abstract string ToString(IFormatProvider formatProvider);
-
- string IFormattable.ToString(string ignored, IFormatProvider formatProvider)
- {
- return ToString(formatProvider);
- }
-
- /// <summary>
- /// Format the given object in the invariant culture. This static method may be
- /// imported in C# by
- /// <code>
- /// using static System.FormattableString;
- /// </code>.
- /// Within the scope
- /// of that import directive an interpolated string may be formatted in the
- /// invariant culture by writing, for example,
- /// <code>
- /// Invariant($"{{ lat = {latitude}; lon = {longitude} }}")
- /// </code>
- /// </summary>
- public static string Invariant(FormattableString formattable)
- {
- if (formattable == null)
- {
- throw new ArgumentNullException(nameof(formattable));
- }
-
- return formattable.ToString(Globalization.CultureInfo.InvariantCulture);
- }
-
- public override string ToString()
- {
- return ToString(Globalization.CultureInfo.CurrentCulture);
- }
- }
-}
diff --git a/src/mscorlib/src/System/GC.cs b/src/mscorlib/src/System/GC.cs
index fd09ef7984..aeb0ca5196 100644
--- a/src/mscorlib/src/System/GC.cs
+++ b/src/mscorlib/src/System/GC.cs
@@ -12,21 +12,22 @@
**
**
===========================================================*/
-namespace System {
- //This class only static members and doesn't require the serializable keyword.
-
- using System;
- using System.Reflection;
- using System.Security;
- using System.Threading;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
+//This class only static members and doesn't require the serializable keyword.
+
+using System;
+using System.Reflection;
+using System.Security;
+using System.Threading;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
[Serializable]
public enum GCCollectionMode
{
@@ -60,7 +61,7 @@ namespace System {
NotApplicable = 4
}
- public static class GC
+ public static class GC
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetGCLatencyMode();
@@ -95,9 +96,9 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetMaxGeneration();
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int _CollectionCount (int generation, int getSpecialGCCount);
+ private static extern int _CollectionCount(int generation, int getSpecialGCCount);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern bool IsServerGC();
@@ -107,35 +108,41 @@ namespace System {
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void _RemoveMemoryPressure(UInt64 bytesAllocated);
-
- public static void AddMemoryPressure (long bytesAllocated) {
- if( bytesAllocated <= 0) {
- throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+
+ public static void AddMemoryPressure(long bytesAllocated)
+ {
+ if (bytesAllocated <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
+ SR.ArgumentOutOfRange_NeedPosNum);
}
- if( (4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue) ) {
- throw new ArgumentOutOfRangeException("pressure",
- Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
+ if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue))
+ {
+ throw new ArgumentOutOfRangeException("pressure",
+ SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
Contract.EndContractBlock();
_AddMemoryPressure((ulong)bytesAllocated);
}
- public static void RemoveMemoryPressure (long bytesAllocated) {
- if( bytesAllocated <= 0) {
- throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ public static void RemoveMemoryPressure(long bytesAllocated)
+ {
+ if (bytesAllocated <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
+ SR.ArgumentOutOfRange_NeedPosNum);
}
- if( (4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue) ) {
- throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
- Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"));
+ if ((4 == IntPtr.Size) && (bytesAllocated > Int32.MaxValue))
+ {
+ throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
+ SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
Contract.EndContractBlock();
- _RemoveMemoryPressure((ulong) bytesAllocated);
+ _RemoveMemoryPressure((ulong)bytesAllocated);
}
@@ -144,40 +151,42 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetGeneration(Object obj);
-
+
// Forces a collection of all generations from 0 through Generation.
//
- public static void Collect(int generation) {
+ public static void Collect(int generation)
+ {
Collect(generation, GCCollectionMode.Default);
}
-
+
// Garbage Collect all generations.
//
- public static void Collect() {
+ public static void Collect()
+ {
//-1 says to GC all generations.
_Collect(-1, (int)InternalGCCollectionMode.Blocking);
}
- public static void Collect(int generation, GCCollectionMode mode)
+ public static void Collect(int generation, GCCollectionMode mode)
{
Collect(generation, mode, true);
}
- public static void Collect(int generation, GCCollectionMode mode, bool blocking)
+ public static void Collect(int generation, GCCollectionMode mode, bool blocking)
{
Collect(generation, mode, blocking, false);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
{
- if (generation<0)
+ if (generation < 0)
{
- throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
{
- throw new ArgumentOutOfRangeException(nameof(mode), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum);
}
Contract.EndContractBlock();
@@ -204,16 +213,16 @@ namespace System {
_Collect(generation, iInternalModes);
}
- public static int CollectionCount (int generation)
+ public static int CollectionCount(int generation)
{
- if (generation<0)
+ if (generation < 0)
{
- throw new ArgumentOutOfRangeException(nameof(generation), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
+ throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
Contract.EndContractBlock();
return _CollectionCount(generation, 0);
}
-
+
// This method DOES NOT DO ANYTHING in and of itself. It's used to
// prevent a finalizable object from losing any outstanding references
// a touch too early. The JIT is very aggressive about keeping an
@@ -256,15 +265,17 @@ namespace System {
// Returns the generation in which wo currently resides.
//
- public static int GetGeneration(WeakReference wo) {
+ public static int GetGeneration(WeakReference wo)
+ {
int result = GetGenerationWR(wo.m_handle);
KeepAlive(wo);
return result;
}
-
+
// Returns the maximum GC generation. Currently assumes only 1 heap.
//
- public static int MaxGeneration {
+ public static int MaxGeneration
+ {
get { return GetMaxGeneration(); }
}
@@ -272,17 +283,19 @@ namespace System {
[SuppressUnmanagedCodeSecurity]
private static extern void _WaitForPendingFinalizers();
- public static void WaitForPendingFinalizers() {
+ public static void WaitForPendingFinalizers()
+ {
// QCalls can not be exposed from mscorlib directly, need to wrap it.
_WaitForPendingFinalizers();
}
-
+
// Indicates that the system should not call the Finalize() method on
// an object that would normally require this call.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _SuppressFinalize(Object o);
- public static void SuppressFinalize(Object obj) {
+ public static void SuppressFinalize(Object obj)
+ {
if (obj == null)
throw new ArgumentNullException(nameof(obj));
Contract.EndContractBlock();
@@ -295,8 +308,9 @@ namespace System {
// needs to resurrect itself or an object that it references.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _ReRegisterForFinalize(Object o);
-
- public static void ReRegisterForFinalize(Object obj) {
+
+ public static void ReRegisterForFinalize(Object obj)
+ {
if (obj == null)
throw new ArgumentNullException(nameof(obj));
Contract.EndContractBlock();
@@ -307,7 +321,8 @@ namespace System {
// the GC heap. This does not return the total size of the GC heap, but
// only the live objects in the GC heap.
//
- public static long GetTotalMemory(bool forceFullCollection) {
+ public static long GetTotalMemory(bool forceFullCollection)
+ {
long size = GetTotalMemory();
if (!forceFullCollection)
return size;
@@ -319,7 +334,8 @@ namespace System {
int reps = 20; // Number of iterations
long newSize = size;
float diff;
- do {
+ do
+ {
GC.WaitForPendingFinalizers();
GC.Collect();
size = newSize;
@@ -332,7 +348,8 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern long _GetAllocatedBytesForCurrentThread();
- public static long GetAllocatedBytesForCurrentThread() {
+ public static long GetAllocatedBytesForCurrentThread()
+ {
return _GetAllocatedBytesForCurrentThread();
}
@@ -352,27 +369,27 @@ namespace System {
{
if ((maxGenerationThreshold <= 0) || (maxGenerationThreshold >= 100))
{
- throw new ArgumentOutOfRangeException(nameof(maxGenerationThreshold),
+ throw new ArgumentOutOfRangeException(nameof(maxGenerationThreshold),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
- 1,
+ SR.ArgumentOutOfRange_Bounds_Lower_Upper,
+ 1,
99));
}
-
+
if ((largeObjectHeapThreshold <= 0) || (largeObjectHeapThreshold >= 100))
{
- throw new ArgumentOutOfRangeException(nameof(largeObjectHeapThreshold),
+ throw new ArgumentOutOfRangeException(nameof(largeObjectHeapThreshold),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
- 1,
+ SR.ArgumentOutOfRange_Bounds_Lower_Upper,
+ 1,
99));
-}
+ }
if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold))
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotWithConcurrentGC"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
@@ -380,7 +397,7 @@ namespace System {
{
if (!_CancelFullGCNotification())
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotWithConcurrentGC"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
@@ -392,7 +409,7 @@ namespace System {
public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout);
}
@@ -405,11 +422,11 @@ namespace System {
public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout);
}
- enum StartNoGCRegionStatus
+ private enum StartNoGCRegionStatus
{
Succeeded = 0,
NotEnoughMemory = 1,
@@ -417,7 +434,7 @@ namespace System {
AlreadyInProgress = 3
}
- enum EndNoGCRegionStatus
+ private enum EndNoGCRegionStatus
{
Succeeded = 0,
NotInProgress = 1,
@@ -425,11 +442,11 @@ namespace System {
AllocationExceeded = 3
}
- static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
+ private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
StartNoGCRegionStatus status = (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
if (status == StartNoGCRegionStatus.AmountTooLarge)
- throw new ArgumentOutOfRangeException(nameof(totalSize),
+ throw new ArgumentOutOfRangeException(nameof(totalSize),
"totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in http://go.microsoft.com/fwlink/?LinkId=522706");
else if (status == StartNoGCRegionStatus.AlreadyInProgress)
throw new InvalidOperationException("The NoGCRegion mode was already in progress");
@@ -458,7 +475,7 @@ namespace System {
return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC);
}
- static EndNoGCRegionStatus EndNoGCRegionWorker()
+ private static EndNoGCRegionStatus EndNoGCRegionWorker()
{
EndNoGCRegionStatus status = (EndNoGCRegionStatus)_EndNoGCRegion();
if (status == EndNoGCRegionStatus.NotInProgress)
diff --git a/src/mscorlib/src/System/Globalization/BidiCategory.cs b/src/mscorlib/src/System/Globalization/BidiCategory.cs
index 1041776424..f37c44b385 100644
--- a/src/mscorlib/src/System/Globalization/BidiCategory.cs
+++ b/src/mscorlib/src/System/Globalization/BidiCategory.cs
@@ -9,9 +9,12 @@
**
**
============================================================*/
-namespace System.Globalization {
+
+namespace System.Globalization
+{
[Serializable]
- internal enum BidiCategory {
+ internal enum BidiCategory
+ {
LeftToRight = 0,
LeftToRightEmbedding = 1,
LeftToRightOverride = 2,
@@ -32,7 +35,7 @@ namespace System.Globalization {
Whitespace = 17,
OtherNeutrals = 18,
LeftToRightIsolate = 19,
- RightToLeftIsolate = 20,
+ RightToLeftIsolate = 20,
FirstStrongIsolate = 21,
PopDirectionIsolate = 22,
}
diff --git a/src/mscorlib/src/System/Globalization/Calendar.cs b/src/mscorlib/src/System/Globalization/Calendar.cs
index 1ff795ddc5..c23e1088c1 100644
--- a/src/mscorlib/src/System/Globalization/Calendar.cs
+++ b/src/mscorlib/src/System/Globalization/Calendar.cs
@@ -2,14 +2,12 @@
// 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.Globalization {
- using System;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+namespace System.Globalization
+{
// This abstract class represents a calendar. A calendar reckons time in
// divisions such as weeks, months and years. The number, length and start of
// the divisions vary in each calendar.
@@ -31,69 +29,49 @@ namespace System.Globalization {
// since most of the calendars (or all?) have the same way of calcuating hour/minute/second.
[Serializable]
- public abstract class Calendar : ICloneable
+ public abstract partial class Calendar : ICloneable
{
-
// Number of 100ns (10E-7 second) ticks per time unit
- internal const long TicksPerMillisecond = 10000;
- internal const long TicksPerSecond = TicksPerMillisecond * 1000;
- internal const long TicksPerMinute = TicksPerSecond * 60;
- internal const long TicksPerHour = TicksPerMinute * 60;
- internal const long TicksPerDay = TicksPerHour * 24;
+ internal const long TicksPerMillisecond = 10000;
+ internal const long TicksPerSecond = TicksPerMillisecond * 1000;
+ internal const long TicksPerMinute = TicksPerSecond * 60;
+ internal const long TicksPerHour = TicksPerMinute * 60;
+ internal const long TicksPerDay = TicksPerHour * 24;
// Number of milliseconds per time unit
- internal const int MillisPerSecond = 1000;
- internal const int MillisPerMinute = MillisPerSecond * 60;
- internal const int MillisPerHour = MillisPerMinute * 60;
- internal const int MillisPerDay = MillisPerHour * 24;
+ internal const int MillisPerSecond = 1000;
+ internal const int MillisPerMinute = MillisPerSecond * 60;
+ internal const int MillisPerHour = MillisPerMinute * 60;
+ internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
- internal const int DaysPerYear = 365;
+ internal const int DaysPerYear = 365;
// Number of days in 4 years
- internal const int DaysPer4Years = DaysPerYear * 4 + 1;
+ internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
- internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
+ internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
- internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
+ internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
// Number of days from 1/1/0001 to 1/1/10000
- internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
-
- internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
-
- //
- // Calendar ID Values. This is used to get data from calendar.nlp.
- // The order of calendar ID means the order of data items in the table.
- //
-
- internal const int CAL_GREGORIAN = 1 ; // Gregorian (localized) calendar
- internal const int CAL_GREGORIAN_US = 2 ; // Gregorian (U.S.) calendar
- internal const int CAL_JAPAN = 3 ; // Japanese Emperor Era calendar
- internal const int CAL_TAIWAN = 4 ; // Taiwan Era calendar
- internal const int CAL_KOREA = 5 ; // Korean Tangun Era calendar
- internal const int CAL_HIJRI = 6 ; // Hijri (Arabic Lunar) calendar
- internal const int CAL_THAI = 7 ; // Thai calendar
- internal const int CAL_HEBREW = 8 ; // Hebrew (Lunar) calendar
- internal const int CAL_GREGORIAN_ME_FRENCH = 9 ; // Gregorian Middle East French calendar
- internal const int CAL_GREGORIAN_ARABIC = 10; // Gregorian Arabic calendar
- internal const int CAL_GREGORIAN_XLIT_ENGLISH = 11; // Gregorian Transliterated English calendar
- internal const int CAL_GREGORIAN_XLIT_FRENCH = 12;
- internal const int CAL_JULIAN = 13;
- internal const int CAL_JAPANESELUNISOLAR = 14;
- internal const int CAL_CHINESELUNISOLAR = 15;
- internal const int CAL_SAKA = 16; // reserved to match Office but not implemented in our code
- internal const int CAL_LUNAR_ETO_CHN = 17; // reserved to match Office but not implemented in our code
- internal const int CAL_LUNAR_ETO_KOR = 18; // reserved to match Office but not implemented in our code
- internal const int CAL_LUNAR_ETO_ROKUYOU = 19; // reserved to match Office but not implemented in our code
- internal const int CAL_KOREANLUNISOLAR = 20;
- internal const int CAL_TAIWANLUNISOLAR = 21;
- internal const int CAL_PERSIAN = 22;
- internal const int CAL_UMALQURA = 23;
-
- internal int m_currentEraValue = -1;
-
- [System.Runtime.Serialization.OptionalField(VersionAdded = 2)]
- private bool m_isReadOnly = false;
+ internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
+
+ internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
+
+ private int _currentEraValue = -1;
+
+ [OptionalField(VersionAdded = 2)]
+ private bool _isReadOnly = false;
+
+#if CORECLR
+ internal const CalendarId CAL_HEBREW = CalendarId.HEBREW;
+ internal const CalendarId CAL_HIJRI = CalendarId.HIJRI;
+ internal const CalendarId CAL_JAPAN = CalendarId.JAPAN;
+ internal const CalendarId CAL_JULIAN = CalendarId.JULIAN;
+ internal const CalendarId CAL_TAIWAN = CalendarId.TAIWAN;
+ internal const CalendarId CAL_UMALQURA = CalendarId.UMALQURA;
+ internal const CalendarId CAL_PERSIAN = CalendarId.PERSIAN;
+#endif
// The minimum supported DateTime range for the calendar.
@@ -115,19 +93,27 @@ namespace System.Globalization {
}
}
+ public virtual CalendarAlgorithmType AlgorithmType
+ {
+ get
+ {
+ return CalendarAlgorithmType.Unknown;
+ }
+ }
-
-
- protected Calendar() {
+ protected Calendar()
+ {
//Do-nothing constructor.
}
///
// This can not be abstract, otherwise no one can create a subclass of Calendar.
//
- internal virtual int ID {
- get {
- return (-1);
+ internal virtual CalendarId ID
+ {
+ get
+ {
+ return CalendarId.UNINITIALIZED_VALUE;
}
}
@@ -135,21 +121,11 @@ namespace System.Globalization {
// Return the Base calendar ID for calendars that didn't have defined data in calendarData
//
- internal virtual int BaseCalendarID
+ internal virtual CalendarId BaseCalendarID
{
get { return ID; }
}
- // Returns the type of the calendar.
- //
- public virtual CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.Unknown;
- }
- }
-
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
@@ -159,7 +135,7 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public bool IsReadOnly
{
- get { return (m_isReadOnly); }
+ get { return (_isReadOnly); }
}
////////////////////////////////////////////////////////////////////////
@@ -169,13 +145,13 @@ namespace System.Globalization {
// Is the implementation of ICloneable.
//
////////////////////////////////////////////////////////////////////////
- public virtual Object Clone()
+ public virtual object Clone()
{
object o = MemberwiseClone();
- ((Calendar) o).SetReadOnlyState(false);
+ ((Calendar)o).SetReadOnlyState(false);
return (o);
}
-
+
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
@@ -184,29 +160,29 @@ namespace System.Globalization {
// readonly.
//
////////////////////////////////////////////////////////////////////////
- public static Calendar ReadOnly(Calendar calendar)
+ public static Calendar ReadOnly(Calendar calendar)
{
- if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
+ if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); }
Contract.EndContractBlock();
- if (calendar.IsReadOnly) { return (calendar); }
-
+ if (calendar.IsReadOnly) { return (calendar); }
+
Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone());
clonedCalendar.SetReadOnlyState(true);
-
+
return (clonedCalendar);
}
internal void VerifyWritable()
{
- if (m_isReadOnly)
+ if (_isReadOnly)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
- m_isReadOnly = readOnly;
+ _isReadOnly = readOnly;
}
@@ -219,14 +195,17 @@ namespace System.Globalization {
** The value is from calendar.nlp.
============================================================================*/
- internal virtual int CurrentEraValue {
- get {
+ internal virtual int CurrentEraValue
+ {
+ get
+ {
// The following code assumes that the current era value can not be -1.
- if (m_currentEraValue == -1) {
- Debug.Assert(BaseCalendarID > 0, "[Calendar.CurrentEraValue] Expected ID > 0");
- m_currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
+ if (_currentEraValue == -1)
+ {
+ Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID");
+ _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra;
}
- return (m_currentEraValue);
+ return (_currentEraValue);
}
}
@@ -236,16 +215,19 @@ namespace System.Globalization {
internal int twoDigitYearMax = -1;
- internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) {
- if (ticks < minValue.Ticks || ticks > maxValue.Ticks) {
+ internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue)
+ {
+ if (ticks < minValue.Ticks || ticks > maxValue.Ticks)
+ {
throw new ArgumentException(
- String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("Argument_ResultCalendarRange"),
- minValue, maxValue));
+ String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange,
+ minValue, maxValue)));
}
Contract.EndContractBlock();
}
- internal DateTime Add(DateTime time, double value, int scale) {
+ internal DateTime Add(DateTime time, double value, int scale)
+ {
// From ECMA CLI spec, Partition III, section 3.27:
//
// If overflow occurs converting a floating-point type to an integer, or if the floating-point value
@@ -256,7 +238,7 @@ namespace System.Globalization {
double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5));
if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis)))
{
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_AddValue"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
}
long millis = (long)tempMillis;
@@ -272,7 +254,8 @@ namespace System.Globalization {
// argument is permitted to be negative.
//
- public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) {
+ public virtual DateTime AddMilliseconds(DateTime time, double milliseconds)
+ {
return (Add(time, milliseconds, 1));
}
@@ -284,7 +267,8 @@ namespace System.Globalization {
// value argument is permitted to be negative.
//
- public virtual DateTime AddDays(DateTime time, int days) {
+ public virtual DateTime AddDays(DateTime time, int days)
+ {
return (Add(time, days, MillisPerDay));
}
@@ -295,7 +279,8 @@ namespace System.Globalization {
// value argument is permitted to be negative.
//
- public virtual DateTime AddHours(DateTime time, int hours) {
+ public virtual DateTime AddHours(DateTime time, int hours)
+ {
return (Add(time, hours, MillisPerHour));
}
@@ -307,7 +292,8 @@ namespace System.Globalization {
// value argument is permitted to be negative.
//
- public virtual DateTime AddMinutes(DateTime time, int minutes) {
+ public virtual DateTime AddMinutes(DateTime time, int minutes)
+ {
return (Add(time, minutes, MillisPerMinute));
}
@@ -339,7 +325,8 @@ namespace System.Globalization {
// value argument is permitted to be negative.
//
- public virtual DateTime AddSeconds(DateTime time, int seconds) {
+ public virtual DateTime AddSeconds(DateTime time, int seconds)
+ {
return Add(time, seconds, MillisPerSecond);
}
@@ -348,7 +335,8 @@ namespace System.Globalization {
// value argument is permitted to be negative.
//
- public virtual DateTime AddWeeks(DateTime time, int weeks) {
+ public virtual DateTime AddWeeks(DateTime time, int weeks)
+ {
return (AddDays(time, weeks * 7));
}
@@ -425,7 +413,8 @@ namespace System.Globalization {
============================================================================*/
- public abstract int[] Eras {
+ public abstract int[] Eras
+ {
get;
}
@@ -434,7 +423,8 @@ namespace System.Globalization {
// integer between 0 and 23.
//
- public virtual int GetHour(DateTime time) {
+ public virtual int GetHour(DateTime time)
+ {
return ((int)((time.Ticks / TicksPerHour) % 24));
}
@@ -442,7 +432,8 @@ namespace System.Globalization {
// is an integer between 0 and 999.
//
- public virtual double GetMilliseconds(DateTime time) {
+ public virtual double GetMilliseconds(DateTime time)
+ {
return (double)((time.Ticks / TicksPerMillisecond) % 1000);
}
@@ -450,7 +441,8 @@ namespace System.Globalization {
// an integer between 0 and 59.
//
- public virtual int GetMinute(DateTime time) {
+ public virtual int GetMinute(DateTime time)
+ {
return ((int)((time.Ticks / TicksPerMinute) % 60));
}
@@ -475,7 +467,8 @@ namespace System.Globalization {
// an integer between 0 and 59.
//
- public virtual int GetSecond(DateTime time) {
+ public virtual int GetSecond(DateTime time)
+ {
return ((int)((time.Ticks / TicksPerSecond) % 60));
}
@@ -516,7 +509,8 @@ namespace System.Globalization {
** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1
============================================================================*/
- internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) {
+ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek)
+ {
int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0.
// Calculate the day of week for the first day of the year.
// dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that
@@ -527,7 +521,8 @@ namespace System.Globalization {
return ((dayOfYear + offset) / 7 + 1);
}
- private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) {
+ private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays)
+ {
int dayForJan1;
int offset;
int day;
@@ -576,11 +571,12 @@ namespace System.Globalization {
// Calculate the day of year for specified time by taking offset into account.
//
day = dayOfYear - offset;
- if (day >= 0) {
+ if (day >= 0)
+ {
//
// If the day of year value is greater than zero, get the week of year.
//
- return (day/7 + 1);
+ return (day / 7 + 1);
}
//
// Otherwise, the specified time falls on the week of previous year.
@@ -643,13 +639,15 @@ namespace System.Globalization {
public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
{
- if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) {
+ if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6)
+ {
throw new ArgumentOutOfRangeException(
- nameof(firstDayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range,
DayOfWeek.Sunday, DayOfWeek.Saturday));
}
Contract.EndContractBlock();
- switch (rule) {
+ switch (rule)
+ {
case CalendarWeekRule.FirstDay:
return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek));
case CalendarWeekRule.FirstFullWeek:
@@ -658,9 +656,8 @@ namespace System.Globalization {
return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4));
}
throw new ArgumentOutOfRangeException(
- nameof(rule), Environment.GetResourceString("ArgumentOutOfRange_Range",
+ nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range,
CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
-
}
// Returns the year part of the specified DateTime. The returned value is an
@@ -688,7 +685,8 @@ namespace System.Globalization {
// month is a leap month, or false if not.
//
- public virtual bool IsLeapMonth(int year, int month) {
+ public virtual bool IsLeapMonth(int year, int month)
+ {
return (IsLeapMonth(year, month, CurrentEra));
}
@@ -717,7 +715,7 @@ namespace System.Globalization {
return 0;
int monthsCount = GetMonthsInYear(year, era);
- for (int month=1; month<=monthsCount; month++)
+ for (int month = 1; month <= monthsCount; month++)
{
if (IsLeapMonth(year, month, era))
return month;
@@ -744,7 +742,7 @@ namespace System.Globalization {
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
- public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
+ public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
{
return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra));
}
@@ -754,30 +752,35 @@ namespace System.Globalization {
public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era);
- internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) {
+ internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
+ {
result = DateTime.MinValue;
- try {
+ try
+ {
result = ToDateTime(year, month, day, hour, minute, second, millisecond, era);
return true;
}
- catch (ArgumentException) {
+ catch (ArgumentException)
+ {
return false;
}
}
-
- internal virtual bool IsValidYear(int year, int era) {
+
+ internal virtual bool IsValidYear(int year, int era)
+ {
return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime));
}
-
- internal virtual bool IsValidMonth(int year, int month, int era) {
+
+ internal virtual bool IsValidMonth(int year, int month, int era)
+ {
return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era));
}
-
+
internal virtual bool IsValidDay(int year, int month, int day, int era)
{
return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era));
}
-
+
// Returns and assigns the maximum value to represent a two digit year. This
// value is the upper boundary of a 100 year range that allows a two digit year
@@ -805,14 +808,17 @@ namespace System.Globalization {
// then a two digit value of 30 will get converted to 1930 while a two digit
// value of 29 will get converted to 2029.
- public virtual int ToFourDigitYear(int year) {
- if (year < 0) {
+ public virtual int ToFourDigitYear(int year)
+ {
+ if (year < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (year < 100) {
- return ((TwoDigitYearMax/100 - ( year > TwoDigitYearMax % 100 ? 1 : 0))*100 + year);
+ if (year < 100)
+ {
+ return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year);
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
@@ -823,30 +829,29 @@ namespace System.Globalization {
// Will check the if the parameters are valid.
internal static long TimeToTicks(int hour, int minute, int second, int millisecond)
{
- if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
+ if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
throw new ArgumentOutOfRangeException(
nameof(millisecond),
String.Format(
CultureInfo.InvariantCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), 0, MillisPerSecond - 1));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1)));
}
- return TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
+ return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond;
}
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
+ throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
- internal static int GetSystemTwoDigitYearSetting(int CalID, int defaultYearValue)
+ internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue)
{
- // Call nativeGetTwoDigitYearMax
- int twoDigitYearMax = CalendarData.nativeGetTwoDigitYearMax(CalID);
+ int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID);
if (twoDigitYearMax < 0)
{
twoDigitYearMax = defaultYearValue;
}
return (twoDigitYearMax);
}
-
}
}
diff --git a/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs b/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
deleted file mode 100644
index 33b5035a8d..0000000000
--- a/src/mscorlib/src/System/Globalization/CalendarAlgorithmType.cs
+++ /dev/null
@@ -1,19 +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.
-
-namespace System.Globalization {
- using System;
-
- public enum CalendarAlgorithmType {
- Unknown = 0, // This is the default value to return in the Calendar base class.
- SolarCalendar = 1, // Solar-base calendar, such as GregorianCalendar, jaoaneseCalendar, JulianCalendar, etc.
- // Solar calendars are based on the solar year and seasons.
- LunarCalendar = 2, // Lunar-based calendar, such as Hijri and UmAlQuraCalendar.
- // Lunar calendars are based on the path of the moon. The seasons are not accurately represented.
- LunisolarCalendar = 3 // Lunisolar-based calendar which use leap month rule, such as HebrewCalendar and Asian Lunisolar calendars.
- // Lunisolar calendars are based on the cycle of the moon, but consider the seasons as a secondary consideration,
- // so they align with the seasons as well as lunar events.
-
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs b/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs
new file mode 100644
index 0000000000..319f66ae8c
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CalendarData.Unix.cs
@@ -0,0 +1,339 @@
+// 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.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+
+namespace System.Globalization
+{
+ // needs to be kept in sync with CalendarDataType in System.Globalization.Native
+ internal enum CalendarDataType
+ {
+ Uninitialized = 0,
+ NativeName = 1,
+ MonthDay = 2,
+ ShortDates = 3,
+ LongDates = 4,
+ YearMonths = 5,
+ DayNames = 6,
+ AbbrevDayNames = 7,
+ MonthNames = 8,
+ AbbrevMonthNames = 9,
+ SuperShortDayNames = 10,
+ MonthGenitiveNames = 11,
+ AbbrevMonthGenitiveNames = 12,
+ EraNames = 13,
+ AbbrevEraNames = 14,
+ }
+
+ internal partial class CalendarData
+ {
+ private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
+ {
+ bool result = true;
+ result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out this.sNativeName);
+ result &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out this.sMonthDay);
+ this.sMonthDay = NormalizeDatePattern(this.sMonthDay);
+
+ result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out this.saShortDates);
+ result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out this.saLongDates);
+ result &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out this.saYearMonths);
+ result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out this.saDayNames);
+ result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out this.saAbbrevDayNames);
+ result &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out this.saSuperShortDayNames);
+ result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out this.saMonthNames);
+ result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out this.saAbbrevMonthNames);
+ result &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out this.saMonthGenitiveNames);
+ result &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out this.saAbbrevMonthGenitiveNames);
+ result &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out this.saEraNames);
+ result &= EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out this.saAbbrevEraNames);
+
+ return result;
+ }
+
+ internal static int GetTwoDigitYearMax(CalendarId calendarId)
+ {
+ // There is no user override for this value on Linux or in ICU.
+ // So just return -1 to use the hard-coded defaults.
+ return -1;
+ }
+
+ // Call native side to figure out which calendars are allowed
+ internal static int GetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ // NOTE: there are no 'user overrides' on Linux
+ int count = Interop.GlobalizationInterop.GetCalendars(localeName, calendars, calendars.Length);
+
+ // ensure there is at least 1 calendar returned
+ if (count == 0 && calendars.Length > 0)
+ {
+ calendars[0] = CalendarId.GREGORIAN;
+ count = 1;
+ }
+
+ return count;
+ }
+
+ private static bool SystemSupportsTaiwaneseCalendar()
+ {
+ return true;
+ }
+
+ // PAL Layer ends here
+
+ private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ return Interop.CallStringMethod(
+ (locale, calId, type, stringBuilder) =>
+ Interop.GlobalizationInterop.GetCalendarInfo(
+ locale,
+ calId,
+ type,
+ stringBuilder,
+ stringBuilder.Capacity),
+ localeName,
+ calendarId,
+ dataType,
+ out calendarString);
+ }
+
+ private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns)
+ {
+ datePatterns = null;
+
+ CallbackContext callbackContext = new CallbackContext();
+ callbackContext.DisallowDuplicates = true;
+ bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
+ if (result)
+ {
+ List<string> datePatternsList = callbackContext.Results;
+
+ datePatterns = new string[datePatternsList.Count];
+ for (int i = 0; i < datePatternsList.Count; i++)
+ {
+ datePatterns[i] = NormalizeDatePattern(datePatternsList[i]);
+ }
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// The ICU date format characters are not exactly the same as the .NET date format characters.
+ /// NormalizeDatePattern will take in an ICU date pattern and return the equivalent .NET date pattern.
+ /// </summary>
+ /// <remarks>
+ /// see Date Field Symbol Table in http://userguide.icu-project.org/formatparse/datetime
+ /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
+ /// </remarks>
+ private static string NormalizeDatePattern(string input)
+ {
+ StringBuilder destination = StringBuilderCache.Acquire(input.Length);
+
+ int index = 0;
+ while (index < input.Length)
+ {
+ switch (input[index])
+ {
+ case '\'':
+ // single quotes escape characters, like 'de' in es-SP
+ // so read verbatim until the next single quote
+ destination.Append(input[index++]);
+ while (index < input.Length)
+ {
+ char current = input[index++];
+ destination.Append(current);
+ if (current == '\'')
+ {
+ break;
+ }
+ }
+ break;
+ case 'E':
+ case 'e':
+ case 'c':
+ // 'E' in ICU is the day of the week, which maps to 3 or 4 'd's in .NET
+ // 'e' in ICU is the local day of the week, which has no representation in .NET, but
+ // maps closest to 3 or 4 'd's in .NET
+ // 'c' in ICU is the stand-alone day of the week, which has no representation in .NET, but
+ // maps closest to 3 or 4 'd's in .NET
+ NormalizeDayOfWeek(input, destination, ref index);
+ break;
+ case 'L':
+ case 'M':
+ // 'L' in ICU is the stand-alone name of the month,
+ // which maps closest to 'M' in .NET since it doesn't support stand-alone month names in patterns
+ // 'M' in both ICU and .NET is the month,
+ // but ICU supports 5 'M's, which is the super short month name
+ int occurrences = CountOccurrences(input, input[index], ref index);
+ if (occurrences > 4)
+ {
+ // 5 'L's or 'M's in ICU is the super short name, which maps closest to MMM in .NET
+ occurrences = 3;
+ }
+ destination.Append('M', occurrences);
+ break;
+ case 'G':
+ // 'G' in ICU is the era, which maps to 'g' in .NET
+ occurrences = CountOccurrences(input, 'G', ref index);
+
+ // it doesn't matter how many 'G's, since .NET only supports 'g' or 'gg', and they
+ // have the same meaning
+ destination.Append('g');
+ break;
+ case 'y':
+ // a single 'y' in ICU is the year with no padding or trimming.
+ // a single 'y' in .NET is the year with 1 or 2 digits
+ // so convert any single 'y' to 'yyyy'
+ occurrences = CountOccurrences(input, 'y', ref index);
+ if (occurrences == 1)
+ {
+ occurrences = 4;
+ }
+ destination.Append('y', occurrences);
+ break;
+ default:
+ const string unsupportedDateFieldSymbols = "YuUrQqwWDFg";
+ Debug.Assert(unsupportedDateFieldSymbols.IndexOf(input[index]) == -1,
+ string.Format(CultureInfo.InvariantCulture,
+ "Encountered an unexpected date field symbol '{0}' from ICU which has no known corresponding .NET equivalent.",
+ input[index]));
+
+ destination.Append(input[index++]);
+ break;
+ }
+ }
+
+ return StringBuilderCache.GetStringAndRelease(destination);
+ }
+
+ private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index)
+ {
+ char dayChar = input[index];
+ int occurrences = CountOccurrences(input, dayChar, ref index);
+ occurrences = Math.Max(occurrences, 3);
+ if (occurrences > 4)
+ {
+ // 5 and 6 E/e/c characters in ICU is the super short names, which maps closest to ddd in .NET
+ occurrences = 3;
+ }
+
+ destination.Append('d', occurrences);
+ }
+
+ private static int CountOccurrences(string input, char value, ref int index)
+ {
+ int startIndex = index;
+ while (index < input.Length && input[index] == value)
+ {
+ index++;
+ }
+
+ return index - startIndex;
+ }
+
+ private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames)
+ {
+ monthNames = null;
+
+ CallbackContext callbackContext = new CallbackContext();
+ bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
+ if (result)
+ {
+ // the month-name arrays are expected to have 13 elements. If ICU only returns 12, add an
+ // extra empty string to fill the array.
+ if (callbackContext.Results.Count == 12)
+ {
+ callbackContext.Results.Add(string.Empty);
+ }
+
+ monthNames = callbackContext.Results.ToArray();
+ }
+
+ return result;
+ }
+
+ private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames)
+ {
+ bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames);
+
+ // .NET expects that only the Japanese calendars have more than 1 era.
+ // So for other calendars, only return the latest era.
+ if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR && eraNames.Length > 0)
+ {
+ string[] latestEraName = new string[] { eraNames[eraNames.Length - 1] };
+ eraNames = latestEraName;
+ }
+
+ return result;
+ }
+
+ internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData)
+ {
+ calendarData = null;
+
+ CallbackContext callbackContext = new CallbackContext();
+ bool result = EnumCalendarInfo(localeName, calendarId, dataType, callbackContext);
+ if (result)
+ {
+ calendarData = callbackContext.Results.ToArray();
+ }
+
+ return result;
+ }
+
+ private static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, CallbackContext callbackContext)
+ {
+ GCHandle context = GCHandle.Alloc(callbackContext);
+ try
+ {
+ return Interop.GlobalizationInterop.EnumCalendarInfo(EnumCalendarInfoCallback, localeName, calendarId, dataType, (IntPtr)context);
+ }
+ finally
+ {
+ context.Free();
+ }
+ }
+
+ private static void EnumCalendarInfoCallback(string calendarString, IntPtr context)
+ {
+ CallbackContext callbackContext = (CallbackContext)((GCHandle)context).Target;
+
+ if (callbackContext.DisallowDuplicates)
+ {
+ foreach (string existingResult in callbackContext.Results)
+ {
+ if (string.Equals(calendarString, existingResult, StringComparison.Ordinal))
+ {
+ // the value is already in the results, so don't add it again
+ return;
+ }
+ }
+ }
+
+ callbackContext.Results.Add(calendarString);
+ }
+
+ private class CallbackContext
+ {
+ private List<string> _results = new List<string>();
+
+ public CallbackContext()
+ {
+ }
+
+ public List<string> Results { get { return _results; } }
+
+ public bool DisallowDuplicates { get; set; }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs
new file mode 100644
index 0000000000..51a2727c7d
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CalendarData.Windows.cs
@@ -0,0 +1,502 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+using System.Collections.Generic;
+
+namespace System.Globalization
+{
+#if CORECLR
+ using IntList = List<int>;
+ using StringList = List<string>;
+#else
+ using IntList = LowLevelList<int>;
+ using StringList = LowLevelList<string>;
+#endif
+
+ internal partial class CalendarData
+ {
+ private bool LoadCalendarDataFromSystem(String localeName, CalendarId calendarId)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ bool ret = true;
+
+ uint useOverrides = this.bUseUserOverrides ? 0 : CAL_NOUSEROVERRIDE;
+
+ //
+ // Windows doesn't support some calendars right now, so remap those.
+ //
+ switch (calendarId)
+ {
+ case CalendarId.JAPANESELUNISOLAR: // Data looks like Japanese
+ calendarId = CalendarId.JAPAN;
+ break;
+ case CalendarId.JULIAN: // Data looks like gregorian US
+ case CalendarId.CHINESELUNISOLAR: // Algorithmic, so actual data is irrelevent
+ case CalendarId.SAKA: // reserved to match Office but not implemented in our code, so data is irrelevent
+ case CalendarId.LUNAR_ETO_CHN: // reserved to match Office but not implemented in our code, so data is irrelevent
+ case CalendarId.LUNAR_ETO_KOR: // reserved to match Office but not implemented in our code, so data is irrelevent
+ case CalendarId.LUNAR_ETO_ROKUYOU: // reserved to match Office but not implemented in our code, so data is irrelevent
+ case CalendarId.KOREANLUNISOLAR: // Algorithmic, so actual data is irrelevent
+ case CalendarId.TAIWANLUNISOLAR: // Algorithmic, so actual data is irrelevent
+ calendarId = CalendarId.GREGORIAN_US;
+ break;
+ }
+
+ //
+ // Special handling for some special calendar due to OS limitation.
+ // This includes calendar like Taiwan calendar, UmAlQura calendar, etc.
+ //
+ CheckSpecialCalendar(ref calendarId, ref localeName);
+
+ // Numbers
+ ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_ITWODIGITYEARMAX | useOverrides, out this.iTwoDigitYearMax);
+
+ // Strings
+ ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SCALNAME, out this.sNativeName);
+ ret &= CallGetCalendarInfoEx(localeName, calendarId, CAL_SMONTHDAY | useOverrides, out this.sMonthDay);
+
+ // String Arrays
+ // Formats
+ ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SSHORTDATE, LOCALE_SSHORTDATE | useOverrides, out this.saShortDates);
+ ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SLONGDATE, LOCALE_SLONGDATE | useOverrides, out this.saLongDates);
+
+ // Get the YearMonth pattern.
+ ret &= CallEnumCalendarInfo(localeName, calendarId, CAL_SYEARMONTH, LOCALE_SYEARMONTH, out this.saYearMonths);
+
+ // Day & Month Names
+ // These are all single calType entries, 1 per day, so we have to make 7 or 13 calls to collect all the names
+
+ // Day
+ // Note that we're off-by-one since managed starts on sunday and windows starts on monday
+ ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SDAYNAME7, out this.saDayNames);
+ ret &= GetCalendarDayInfo(localeName, calendarId, CAL_SABBREVDAYNAME7, out this.saAbbrevDayNames);
+
+ // Month names
+ ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1, out this.saMonthNames);
+ ret &= GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1, out this.saAbbrevMonthNames);
+
+ //
+ // The following LCTYPE are not supported in some platforms. If the call fails,
+ // don't return a failure.
+ //
+ GetCalendarDayInfo(localeName, calendarId, CAL_SSHORTESTDAYNAME7, out this.saSuperShortDayNames);
+
+ // Gregorian may have genitive month names
+ if (calendarId == CalendarId.GREGORIAN)
+ {
+ GetCalendarMonthInfo(localeName, calendarId, CAL_SMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saMonthGenitiveNames);
+ GetCalendarMonthInfo(localeName, calendarId, CAL_SABBREVMONTHNAME1 | CAL_RETURN_GENITIVE_NAMES, out this.saAbbrevMonthGenitiveNames);
+ }
+
+ // Calendar Parts Names
+ // This doesn't get always get localized names for gregorian (not available in windows < 7)
+ // so: eg: coreclr on win < 7 won't get these
+ CallEnumCalendarInfo(localeName, calendarId, CAL_SERASTRING, 0, out this.saEraNames);
+ CallEnumCalendarInfo(localeName, calendarId, CAL_SABBREVERASTRING, 0, out this.saAbbrevEraNames);
+
+ //
+ // Calendar Era Info
+ // Note that calendar era data (offsets, etc) is hard coded for each calendar since this
+ // data is implementation specific and not dynamic (except perhaps Japanese)
+ //
+
+ // Clean up the escaping of the formats
+ this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates);
+ this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates);
+ this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths);
+ this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay);
+
+ return ret;
+ }
+
+ // Get native two digit year max
+ internal static int GetTwoDigitYearMax(CalendarId calendarId)
+ {
+ if (GlobalizationMode.Invariant)
+ {
+ return Invariant.iTwoDigitYearMax;
+ }
+
+ int twoDigitYearMax = -1;
+
+ if (!CallGetCalendarInfoEx(null, calendarId, (uint)CAL_ITWODIGITYEARMAX, out twoDigitYearMax))
+ {
+ twoDigitYearMax = -1;
+ }
+
+ return twoDigitYearMax;
+ }
+
+ // Call native side to figure out which calendars are allowed
+ internal static int GetCalendars(String localeName, bool useUserOverride, CalendarId[] calendars)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ EnumCalendarsData data = new EnumCalendarsData();
+ data.userOverride = 0;
+ data.calendars = new IntList();
+
+ // First call GetLocaleInfo if necessary
+ if (useUserOverride)
+ {
+ // They want user overrides, see if the user calendar matches the input calendar
+ int userCalendar = CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE);
+
+ // If we got a default, then use it as the first calendar
+ if (userCalendar != 0)
+ {
+ data.userOverride = userCalendar;
+ data.calendars.Add(userCalendar);
+ }
+ }
+
+ GCHandle contextHandle = GCHandle.Alloc(data);
+ try
+ {
+ // Now call the enumeration API. Work is done by our callback function
+#if CORECLR
+ Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarsCallback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle);
+#else
+ IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarsCallback);
+ Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, ENUM_ALL_CALENDARS, null, CAL_ICALINTVALUE, (IntPtr)contextHandle);
+#endif
+ }
+ finally
+ {
+ contextHandle.Free();
+ }
+
+ // Copy to the output array
+ for (int i = 0; i < Math.Min(calendars.Length, data.calendars.Count); i++)
+ calendars[i] = (CalendarId)data.calendars[i];
+
+ // Now we have a list of data, return the count
+ return data.calendars.Count;
+ }
+
+ private static bool SystemSupportsTaiwaneseCalendar()
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ string data;
+ // Taiwanese calendar get listed as one of the optional zh-TW calendars only when having zh-TW UI
+ return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, CAL_SCALNAME, out data);
+ }
+
+ // PAL Layer ends here
+
+ private const uint CAL_RETURN_NUMBER = 0x20000000;
+ private const uint CAL_RETURN_GENITIVE_NAMES = 0x10000000;
+ private const uint CAL_NOUSEROVERRIDE = 0x80000000;
+ private const uint CAL_SCALNAME = 0x00000002;
+ private const uint CAL_SMONTHDAY = 0x00000038;
+ private const uint CAL_SSHORTDATE = 0x00000005;
+ private const uint CAL_SLONGDATE = 0x00000006;
+ private const uint CAL_SYEARMONTH = 0x0000002f;
+ private const uint CAL_SDAYNAME7 = 0x0000000d;
+ private const uint CAL_SABBREVDAYNAME7 = 0x00000014;
+ private const uint CAL_SMONTHNAME1 = 0x00000015;
+ private const uint CAL_SABBREVMONTHNAME1 = 0x00000022;
+ private const uint CAL_SSHORTESTDAYNAME7 = 0x00000037;
+ private const uint CAL_SERASTRING = 0x00000004;
+ private const uint CAL_SABBREVERASTRING = 0x00000039;
+ private const uint CAL_ICALINTVALUE = 0x00000001;
+ private const uint CAL_ITWODIGITYEARMAX = 0x00000030;
+
+ private const uint ENUM_ALL_CALENDARS = 0xffffffff;
+
+ private const uint LOCALE_SSHORTDATE = 0x0000001F;
+ private const uint LOCALE_SLONGDATE = 0x00000020;
+ private const uint LOCALE_SYEARMONTH = 0x00001006;
+ private const uint LOCALE_ICALENDARTYPE = 0x00001009;
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // For calendars like Gregorain US/Taiwan/UmAlQura, they are not available
+ // in all OS or all localized versions of OS.
+ // If OS does not support these calendars, we will fallback by using the
+ // appropriate fallback calendar and locale combination to retrieve data from OS.
+ //
+ // Parameters:
+ // __deref_inout pCalendarInt:
+ // Pointer to the calendar ID. This will be updated to new fallback calendar ID if needed.
+ // __in_out pLocaleNameStackBuffer
+ // Pointer to the StackSString object which holds the locale name to be checked.
+ // This will be updated to new fallback locale name if needed.
+ //
+ ////////////////////////////////////////////////////////////////////////
+ private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName)
+ {
+ string data;
+
+ // Gregorian-US isn't always available in the OS, however it is the same for all locales
+ switch (calendar)
+ {
+ case CalendarId.GREGORIAN_US:
+ // See if this works
+ if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data))
+ {
+ // Failed, set it to a locale (fa-IR) that's alway has Gregorian US available in the OS
+ localeName = "fa-IR";
+ }
+ // See if that works
+ if (!CallGetCalendarInfoEx(localeName, calendar, CAL_SCALNAME, out data))
+ {
+ // Failed again, just use en-US with the gregorian calendar
+ localeName = "en-US";
+ calendar = CalendarId.GREGORIAN;
+ }
+ break;
+ case CalendarId.TAIWAN:
+ // Taiwan calendar data is not always in all language version of OS due to Geopolical reasons.
+ // It is only available in zh-TW localized versions of Windows.
+ // Let's check if OS supports it. If not, fallback to Greogrian localized for Taiwan calendar.
+ if (!SystemSupportsTaiwaneseCalendar())
+ {
+ calendar = CalendarId.GREGORIAN;
+ }
+ break;
+ }
+ }
+
+ private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data)
+ {
+ return (Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | CAL_RETURN_NUMBER, IntPtr.Zero, 0, out data) != 0);
+ }
+
+ private static unsafe bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data)
+ {
+ const int BUFFER_LENGTH = 80;
+
+ // The maximum size for values returned from GetCalendarInfoEx is 80 characters.
+ char* buffer = stackalloc char[BUFFER_LENGTH];
+
+ int ret = Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)buffer, BUFFER_LENGTH, IntPtr.Zero);
+ if (ret > 0)
+ {
+ if (buffer[ret - 1] == '\0')
+ {
+ ret--; // don't include the null termination in the string
+ }
+ data = new string(buffer, 0, ret);
+ return true;
+ }
+ data = "";
+ return false;
+ }
+
+ // Context for EnumCalendarInfoExEx callback.
+ private class EnumData
+ {
+ public string userOverride;
+ public StringList strings;
+ }
+
+ // EnumCalendarInfoExEx callback itself.
+#if !CORECLR
+ [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+#endif
+ private static unsafe Interop.BOOL EnumCalendarInfoCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr pReserved, IntPtr lParam)
+ {
+ EnumData context = (EnumData)((GCHandle)lParam).Target;
+ try
+ {
+ string calendarInfo = new string((char*)lpCalendarInfoString);
+
+ // If we had a user override, check to make sure this differs
+ if (context.userOverride != calendarInfo)
+ context.strings.Add(calendarInfo);
+
+ return Interop.BOOL.TRUE;
+ }
+ catch (Exception)
+ {
+ return Interop.BOOL.FALSE;
+ }
+ }
+
+ private static unsafe bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data)
+ {
+ EnumData context = new EnumData();
+ context.userOverride = null;
+ context.strings = new StringList();
+ // First call GetLocaleInfo if necessary
+ if (((lcType != 0) && ((lcType & CAL_NOUSEROVERRIDE) == 0)) &&
+ // Get user locale, see if it matches localeName.
+ // Note that they should match exactly, including letter case
+ GetUserDefaultLocaleName() == localeName)
+ {
+ // They want user overrides, see if the user calendar matches the input calendar
+ CalendarId userCalendar = (CalendarId)CultureData.GetLocaleInfoExInt(localeName, LOCALE_ICALENDARTYPE);
+
+ // If the calendars were the same, see if the locales were the same
+ if (userCalendar == calendar)
+ {
+ // They matched, get the user override since locale & calendar match
+ string res = CultureData.GetLocaleInfoEx(localeName, lcType);
+
+ // if it succeeded remember the override for the later callers
+ if (res != "")
+ {
+ // Remember this was the override (so we can look for duplicates later in the enum function)
+ context.userOverride = res;
+
+ // Add to the result strings.
+ context.strings.Add(res);
+ }
+ }
+ }
+
+ GCHandle contextHandle = GCHandle.Alloc(context);
+ try
+ {
+#if CORECLR
+ Interop.Kernel32.EnumCalendarInfoExEx(EnumCalendarInfoCallback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle);
+#else
+ // Now call the enumeration API. Work is done by our callback function
+ IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, IntPtr, Interop.BOOL>>(EnumCalendarInfoCallback);
+ Interop.Kernel32.EnumCalendarInfoExEx(callback, localeName, (uint)calendar, null, calType, (IntPtr)contextHandle);
+#endif // CORECLR
+ }
+ finally
+ {
+ contextHandle.Free();
+ }
+
+ // Now we have a list of data, fail if we didn't find anything.
+ if (context.strings.Count == 0)
+ {
+ data = null;
+ return false;
+ }
+
+ string[] output = context.strings.ToArray();
+
+ if (calType == CAL_SABBREVERASTRING || calType == CAL_SERASTRING)
+ {
+ // Eras are enumerated backwards. (oldest era name first, but
+ // Japanese calendar has newest era first in array, and is only
+ // calendar with multiple eras)
+ Array.Reverse(output, 0, output.Length);
+ }
+
+ data = output;
+
+ return true;
+ }
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // Get the native day names
+ //
+ // NOTE: There's a disparity between .Net & windows day orders, the input day should
+ // start with Sunday
+ //
+ // Parameters:
+ // OUT pOutputStrings The output string[] value.
+ //
+ ////////////////////////////////////////////////////////////////////////
+ private static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings)
+ {
+ bool result = true;
+
+ //
+ // We'll need a new array of 7 items
+ //
+ string[] results = new string[7];
+
+ // Get each one of them
+ for (int i = 0; i < 7; i++, calType++)
+ {
+ result &= CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]);
+
+ // On the first iteration we need to go from CAL_SDAYNAME7 to CAL_SDAYNAME1, so subtract 7 before the ++ happens
+ // This is because the framework starts on sunday and windows starts on monday when counting days
+ if (i == 0)
+ calType -= 7;
+ }
+
+ outputStrings = results;
+
+ return result;
+ }
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // Get the native month names
+ //
+ // Parameters:
+ // OUT pOutputStrings The output string[] value.
+ //
+ ////////////////////////////////////////////////////////////////////////
+ private static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings)
+ {
+ //
+ // We'll need a new array of 13 items
+ //
+ string[] results = new string[13];
+
+ // Get each one of them
+ for (int i = 0; i < 13; i++, calType++)
+ {
+ if (!CallGetCalendarInfoEx(localeName, calendar, calType, out results[i]))
+ results[i] = "";
+ }
+
+ outputStrings = results;
+
+ return true;
+ }
+
+ //
+ // struct to help our calendar data enumaration callback
+ //
+ private class EnumCalendarsData
+ {
+ public int userOverride; // user override value (if found)
+ public IntList calendars; // list of calendars found so far
+ }
+
+#if !CORECLR
+ [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+#endif
+ private static Interop.BOOL EnumCalendarsCallback(IntPtr lpCalendarInfoString, uint calendar, IntPtr reserved, IntPtr lParam)
+ {
+ EnumCalendarsData context = (EnumCalendarsData)((GCHandle)lParam).Target;
+ try
+ {
+ // If we had a user override, check to make sure this differs
+ if (context.userOverride != calendar)
+ context.calendars.Add((int)calendar);
+
+ return Interop.BOOL.TRUE;
+ }
+ catch (Exception)
+ {
+ return Interop.BOOL.FALSE;
+ }
+ }
+
+ private static unsafe String GetUserDefaultLocaleName()
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ const int LOCALE_NAME_MAX_LENGTH = 85;
+ const uint LOCALE_SNAME = 0x0000005c;
+ const string LOCALE_NAME_USER_DEFAULT = null;
+
+ int result;
+ char* localeName = stackalloc char[LOCALE_NAME_MAX_LENGTH];
+ result = CultureData.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME, localeName, LOCALE_NAME_MAX_LENGTH);
+
+ return result <= 0 ? "" : new String(localeName, 0, result - 1); // exclude the null termination
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CalendarData.cs b/src/mscorlib/src/System/Globalization/CalendarData.cs
index d66331b31d..0991149e07 100644
--- a/src/mscorlib/src/System/Globalization/CalendarData.cs
+++ b/src/mscorlib/src/System/Globalization/CalendarData.cs
@@ -2,159 +2,136 @@
// 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.Globalization
{
-
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- //
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
- // properties are available without locales using CalendarData.GetCalendar(int)
+ // properties are available without locales using CalendarData.GetCalendar(CalendarData)
- // StructLayout is needed here otherwise compiler can re-arrange the fields.
- // We have to keep this in-sync with the definition in calendardata.h
- //
- // WARNING WARNING WARNING
- //
- // WARNING: Anything changed here also needs to be updated on the native side (object.h see type CalendarDataBaseObject)
- // WARNING: The type loader will rearrange class member offsets so the mscorwks!CalendarDataBaseObject
- // WARNING: must be manually structured to match the true loaded class layout
- //
- internal class CalendarData
+ internal partial class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
- internal String sNativeName ; // Calendar Name for the locale
+ internal String sNativeName; // Calendar Name for the locale
// Formats
- internal String[] saShortDates ; // Short Data format, default first
- internal String[] saYearMonths ; // Year/Month Data format, default first
- internal String[] saLongDates ; // Long Data format, default first
- internal String sMonthDay ; // Month/Day format
+ internal String[] saShortDates; // Short Data format, default first
+ internal String[] saYearMonths; // Year/Month Data format, default first
+ internal String[] saLongDates; // Long Data format, default first
+ internal String sMonthDay; // Month/Day format
// Calendar Parts Names
- internal String[] saEraNames ; // Names of Eras
- internal String[] saAbbrevEraNames ; // Abbreviated Era Names
- internal String[] saAbbrevEnglishEraNames ; // Abbreviated Era Names in English
- internal String[] saDayNames ; // Day Names, null to use locale data, starts on Sunday
- internal String[] saAbbrevDayNames ; // Abbrev Day Names, null to use locale data, starts on Sunday
- internal String[] saSuperShortDayNames ; // Super short Day of week names
- internal String[] saMonthNames ; // Month Names (13)
- internal String[] saAbbrevMonthNames ; // Abbrev Month Names (13)
- internal String[] saMonthGenitiveNames ; // Genitive Month Names (13)
- internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
- internal String[] saLeapYearMonthNames ; // Multiple strings for the month names in a leap year.
+ internal String[] saEraNames; // Names of Eras
+ internal String[] saAbbrevEraNames; // Abbreviated Era Names
+ internal String[] saAbbrevEnglishEraNames; // Abbreviated Era Names in English
+ internal String[] saDayNames; // Day Names, null to use locale data, starts on Sunday
+ internal String[] saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
+ internal String[] saSuperShortDayNames; // Super short Day of week names
+ internal String[] saMonthNames; // Month Names (13)
+ internal String[] saAbbrevMonthNames; // Abbrev Month Names (13)
+ internal String[] saMonthGenitiveNames; // Genitive Month Names (13)
+ internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
+ internal String[] saLeapYearMonthNames; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
- internal int iTwoDigitYearMax=2029 ; // Max 2 digit year (for Y2K bug data entry)
- internal int iCurrentEra=0 ; // current era # (usually 1)
+ internal int iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
+ internal int iCurrentEra = 0; // current era # (usually 1)
// Use overrides?
- internal bool bUseUserOverrides ; // True if we want user overrides.
+ internal bool bUseUserOverrides; // True if we want user overrides.
// Static invariant for the invariant locale
- internal static CalendarData Invariant;
+ internal static readonly CalendarData Invariant = CreateInvariant();
// Private constructor
- private CalendarData() {}
+ private CalendarData() { }
- // Invariant constructor
- static CalendarData()
+ // Invariant factory
+ private static CalendarData CreateInvariant()
{
-
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
- invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
+ invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
- invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
- invariant.iCurrentEra = 1; // Current era #
+ invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
+ invariant.iCurrentEra = 1; // Current era #
// Formats
- invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
- invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy"}; // long date format
- invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
- invariant.sMonthDay = "MMMM dd"; // Month day pattern
+ invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
+ invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy" }; // long date format
+ invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
+ invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
- invariant.saEraNames = new String[] { "A.D." }; // Era names
- invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
- invariant.saAbbrevEnglishEraNames=new String[] { "AD" }; // Abbreviated era names in English
- invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
- invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
- invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
- invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
+ invariant.saEraNames = new String[] { "A.D." }; // Era names
+ invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
+ invariant.saAbbrevEnglishEraNames = new String[] { "AD" }; // Abbreviated era names in English
+ invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
+ invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
+ invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
+ invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
- invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
- invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
- invariant.saAbbrevMonthGenitiveNames=invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
- invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
+ invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
+ invariant.saAbbrevMonthGenitiveNames = invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
+ invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
- invariant.bUseUserOverrides = false;
+ invariant.bUseUserOverrides = false;
- // Calendar was built, go ahead and assign it...
- Invariant = invariant;
+ return invariant;
}
-
-
//
// Get a bunch of data for a calendar
//
- internal CalendarData(String localeName, int calendarId, bool bUseUserOverrides)
+ internal CalendarData(String localeName, CalendarId calendarId, bool bUseUserOverrides)
{
- // Call nativeGetCalendarData to populate the data
this.bUseUserOverrides = bUseUserOverrides;
- if (!nativeGetCalendarData(this, localeName, calendarId))
+
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ if (!LoadCalendarDataFromSystem(localeName, calendarId))
{
- Debug.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
-
+ Debug.Assert(false, "[CalendarData] LoadCalendarDataFromSystem call isn't expected to fail for calendar " + calendarId + " locale " + localeName);
+
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
- if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
-
+ if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
+
// Formats
- if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
- if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
- if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
- if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
-
+ if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
+ if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
+ if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
+ if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
+
// Calendar Parts Names
- if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
- if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
+ if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
+ if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
- if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
- if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
- if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
- if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
- if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
+ if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
+ if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
+ if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
+ if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
+ if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
- // Clean up the escaping of the formats
- this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates);
- this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates);
- this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths);
- this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay);
-
- if ((CalendarId)calendarId == CalendarId.TAIWAN)
+ if (calendarId == CalendarId.TAIWAN)
{
- if (CultureInfo.IsTaiwanSku)
+ if (SystemSupportsTaiwaneseCalendar())
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
@@ -166,11 +143,11 @@ namespace System.Globalization
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
- if (this.saMonthGenitiveNames == null || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
+ if (this.saMonthGenitiveNames == null || this.saMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
- if (this.saAbbrevMonthGenitiveNames == null || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
+ if (this.saAbbrevMonthGenitiveNames == null || this.saAbbrevMonthGenitiveNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
- if (this.saLeapYearMonthNames == null || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
+ if (this.saLeapYearMonthNames == null || this.saLeapYearMonthNames.Length == 0 || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
@@ -178,7 +155,7 @@ namespace System.Globalization
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
- if (calendarId == (int)CalendarId.JAPAN)
+ if (calendarId == CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
@@ -193,12 +170,12 @@ namespace System.Globalization
this.iCurrentEra = this.saEraNames.Length;
}
- private void InitializeEraNames(string localeName, int calendarId)
+ private void InitializeEraNames(string localeName, CalendarId calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
- switch ((CalendarId)calendarId)
+ switch (calendarId)
{
- // For Localized Gregorian we really expect the data from the OS.
+ // For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
@@ -207,7 +184,7 @@ namespace System.Globalization
}
break;
- // The rest of the calendars have constant data, so we'll just use that
+ // The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
@@ -237,9 +214,9 @@ namespace System.Globalization
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
-
+
case CalendarId.TAIWAN:
- if (CultureInfo.IsTaiwanSku)
+ if (SystemSupportsTaiwaneseCalendar())
{
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
@@ -252,11 +229,11 @@ namespace System.Globalization
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
-
+
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
-
+
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
@@ -276,25 +253,25 @@ namespace System.Globalization
}
}
- private void InitializeAbbreviatedEraNames(string localeName, int calendarId)
+ private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
- switch ((CalendarId)calendarId)
+ switch (calendarId)
{
- // For Localized Gregorian we really expect the data from the OS.
+ // For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
- // Fallback for culture.dll missing
+ // Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
- // The rest of the calendars have constant data, so we'll just use that
+ // The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
- case CalendarId.JULIAN:
+ case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
- break;
+ break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
@@ -316,12 +293,12 @@ namespace System.Globalization
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
- this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2,2);
+ this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2, 2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
- }
+ }
break;
case CalendarId.PERSIAN:
@@ -338,7 +315,7 @@ namespace System.Globalization
}
}
- internal static CalendarData GetCalendarData(int calendarId)
+ internal static CalendarData GetCalendarData(CalendarId calendarId)
{
//
// Get a calendar.
@@ -348,50 +325,47 @@ namespace System.Globalization
//
// Get a culture name
+ // TODO: Note that this doesn't handle the new calendars (lunisolar, etc)
String culture = CalendarIdToCultureName(calendarId);
-
+
// Return our calendar
- return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
+ return CultureInfo.GetCultureInfo(culture)._cultureData.GetCalendar(calendarId);
}
- //
- // Helper methods
- //
- private static String CalendarIdToCultureName(int calendarId)
+ private static String CalendarIdToCultureName(CalendarId calendarId)
{
- // note that this doesn't handle the new calendars (lunisolar, etc)
switch (calendarId)
{
- case Calendar.CAL_GREGORIAN_US:
+ case CalendarId.GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
-
- case Calendar.CAL_JAPAN:
+
+ case CalendarId.JAPAN:
return "ja-JP"; // "ja-JP" Japan
- case Calendar.CAL_TAIWAN: // zh-TW Taiwan
- return "zh-TW";
-
- case Calendar.CAL_KOREA:
+ case CalendarId.TAIWAN:
+ return "zh-TW"; // zh-TW Taiwan
+
+ case CalendarId.KOREA:
return "ko-KR"; // "ko-KR" Korea
-
- case Calendar.CAL_HIJRI:
- case Calendar.CAL_GREGORIAN_ARABIC:
- case Calendar.CAL_UMALQURA:
+
+ case CalendarId.HIJRI:
+ case CalendarId.GREGORIAN_ARABIC:
+ case CalendarId.UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
- case Calendar.CAL_THAI:
+ case CalendarId.THAI:
return "th-TH"; // "th-TH" Thailand
-
- case Calendar.CAL_HEBREW:
+
+ case CalendarId.HEBREW:
return "he-IL"; // "he-IL" Israel
-
- case Calendar.CAL_GREGORIAN_ME_FRENCH:
+
+ case CalendarId.GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
-
- case Calendar.CAL_GREGORIAN_XLIT_ENGLISH:
- case Calendar.CAL_GREGORIAN_XLIT_FRENCH:
+
+ case CalendarId.GREGORIAN_XLIT_ENGLISH:
+ case CalendarId.GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
-
+
default:
// Default to gregorian en-US
break;
@@ -399,20 +373,6 @@ namespace System.Globalization
return "en-US";
}
-
-
- // Get native two digit year max
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern int nativeGetTwoDigitYearMax(int calID);
-
- // Call native side to load our calendar data
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar);
-
- // Call native side to figure out which calendars are allowed
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars);
-
}
- }
+}
diff --git a/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs b/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs
deleted file mode 100644
index fa2a6429f1..0000000000
--- a/src/mscorlib/src/System/Globalization/CalendarWeekRule.cs
+++ /dev/null
@@ -1,19 +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.
-
-namespace System.Globalization {
- using System;
-
-
- [Serializable]
- public enum CalendarWeekRule
- {
-
- FirstDay = 0, // Week 1 begins on the first day of the year
-
- FirstFullWeek = 1, // Week 1 begins on first FirstDayOfWeek not before the first day of the year
-
- FirstFourDayWeek = 2 // Week 1 begins on first FirstDayOfWeek such that FirstDayOfWeek+3 is not before the first day of the year
- };
-}
diff --git a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs b/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
deleted file mode 100644
index 1113cd58ba..0000000000
--- a/src/mscorlib/src/System/Globalization/CalendricalCalculationsHelper.cs
+++ /dev/null
@@ -1,414 +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.
-
-namespace System.Globalization
-{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- internal class CalendricalCalculationsHelper
- {
- const double FullCircleOfArc = 360.0; // 360.0;
- const int HalfCircleOfArc = 180;
- const double TwelveHours = 0.5; // half a day
- const double Noon2000Jan01 = 730120.5;
- internal const double MeanTropicalYearInDays = 365.242189;
- const double MeanSpeedOfSun = MeanTropicalYearInDays / FullCircleOfArc;
- const double LongitudeSpring = 0.0;
- const double TwoDegreesAfterSpring = 2.0;
- const int SecondsPerDay = 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds
-
- const int DaysInUniformLengthCentury = 36525;
- const int SecondsPerMinute = 60;
- const int MinutesPerDegree = 60;
-
- static long StartOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1));
- static long StartOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1));
-
- static double[] Coefficients1900to1987 = new double[] { -0.00002, 0.000297, 0.025184, -0.181133, 0.553040, -0.861938, 0.677066, -0.212591 };
- static double[] Coefficients1800to1899 = new double[] { -0.000009, 0.003844, 0.083563, 0.865736, 4.867575, 15.845535, 31.332267, 38.291999, 28.316289, 11.636204, 2.043794 };
- static double[] Coefficients1700to1799 = new double[] { 8.118780842, -0.005092142, 0.003336121, -0.0000266484 };
- static double[] Coefficients1620to1699 = new double[] { 196.58333, -4.0675, 0.0219167 };
- static double[] LambdaCoefficients = new double[] { 280.46645, 36000.76983, 0.0003032 };
- static double[] AnomalyCoefficients = new double[] { 357.52910, 35999.05030, -0.0001559, -0.00000048 };
- static double[] EccentricityCoefficients = new double[] { 0.016708617, -0.000042037, -0.0000001236 };
- static double[] Coefficients = new double[] { Angle(23, 26, 21.448), Angle(0, 0, -46.8150), Angle(0, 0, -0.00059), Angle(0, 0, 0.001813) };
- static double[] CoefficientsA = new double[] { 124.90, -1934.134, 0.002063 };
- static double[] CoefficientsB = new double[] { 201.11, 72001.5377, 0.00057 };
-
- static double RadiansFromDegrees(double degree)
- {
- return degree * Math.PI / 180;
- }
-
- static double SinOfDegree(double degree)
- {
- return Math.Sin(RadiansFromDegrees(degree));
- }
-
- static double CosOfDegree(double degree)
- {
- return Math.Cos(RadiansFromDegrees(degree));
- }
- static double TanOfDegree(double degree)
- {
- return Math.Tan(RadiansFromDegrees(degree));
- }
-
- public static double Angle(int degrees, int minutes, double seconds)
- {
- return ((seconds / SecondsPerMinute + minutes) / MinutesPerDegree) + degrees;
- }
-
- static double Obliquity(double julianCenturies)
- {
- return PolynomialSum(Coefficients, julianCenturies);
- }
-
- internal static long GetNumberOfDays(DateTime date)
- {
- return date.Ticks / GregorianCalendar.TicksPerDay;
- }
-
- static int GetGregorianYear(double numberOfDays)
- {
- return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * GregorianCalendar.TicksPerDay), DateTime.MaxValue.Ticks)).Year;
- }
-
- enum CorrectionAlgorithm
- {
- Default,
- Year1988to2019,
- Year1900to1987,
- Year1800to1899,
- Year1700to1799,
- Year1620to1699
- }
-
- struct EphemerisCorrectionAlgorithmMap
- {
- public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm)
- {
- _lowestYear = year;
- _algorithm = algorithm;
- }
-
- internal int _lowestYear;
- internal CorrectionAlgorithm _algorithm;
- };
-
- static EphemerisCorrectionAlgorithmMap[] EphemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[]
- {
- // lowest year that starts algorithm, algorithm to use
- new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default),
- new EphemerisCorrectionAlgorithmMap(1988, CorrectionAlgorithm.Year1988to2019),
- new EphemerisCorrectionAlgorithmMap(1900, CorrectionAlgorithm.Year1900to1987),
- new EphemerisCorrectionAlgorithmMap(1800, CorrectionAlgorithm.Year1800to1899),
- new EphemerisCorrectionAlgorithmMap(1700, CorrectionAlgorithm.Year1700to1799),
- new EphemerisCorrectionAlgorithmMap(1620, CorrectionAlgorithm.Year1620to1699),
- new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) // default must be last
- };
-
- static double Reminder(double divisor, double dividend)
- {
- double whole = Math.Floor(divisor / dividend);
- return divisor - (dividend * whole);
- }
-
- static double NormalizeLongitude(double longitude)
- {
- longitude = Reminder(longitude, FullCircleOfArc);
- if (longitude < 0)
- {
- longitude += FullCircleOfArc;
- }
- return longitude;
- }
-
- static public double AsDayFraction(double longitude)
- {
- return longitude / FullCircleOfArc;
- }
-
- static double PolynomialSum(double[] coefficients, double indeterminate)
- {
- double sum = coefficients[0];
- double indeterminateRaised = 1;
- for (int i=1; i<coefficients.Length; i++)
- {
- indeterminateRaised *= indeterminate;
- sum += (coefficients[i] * indeterminateRaised);
- }
-
- return sum;
- }
-
- static double CenturiesFrom1900(int gregorianYear)
- {
- long july1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 7, 1));
- return (double) (july1stOfYear - StartOf1900Century) / DaysInUniformLengthCentury;
- }
-
- // the following formulas defines a polynomial function which gives us the amount that the earth is slowing down for specific year ranges
- static double DefaultEphemerisCorrection(int gregorianYear)
- {
- Debug.Assert(gregorianYear < 1620 || 2020 <= gregorianYear);
- long january1stOfYear = GetNumberOfDays(new DateTime(gregorianYear, 1, 1));
- double daysSinceStartOf1810 = january1stOfYear - StartOf1810;
- double x = TwelveHours + daysSinceStartOf1810;
- return ((Math.Pow(x, 2) / 41048480) - 15) / SecondsPerDay;
- }
-
- static double EphemerisCorrection1988to2019(int gregorianYear)
- {
- Debug.Assert(1988 <= gregorianYear && gregorianYear <= 2019);
- return (double)(gregorianYear - 1933) / SecondsPerDay;
- }
-
- static double EphemerisCorrection1900to1987(int gregorianYear)
- {
- Debug.Assert(1900 <= gregorianYear && gregorianYear <= 1987);
- double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
- return PolynomialSum(Coefficients1900to1987, centuriesFrom1900);
- }
-
- static double EphemerisCorrection1800to1899(int gregorianYear)
- {
- Debug.Assert(1800 <= gregorianYear && gregorianYear <= 1899);
- double centuriesFrom1900 = CenturiesFrom1900(gregorianYear);
- return PolynomialSum(Coefficients1800to1899, centuriesFrom1900);
- }
-
- static double EphemerisCorrection1700to1799(int gregorianYear)
- {
- Debug.Assert(1700 <= gregorianYear && gregorianYear <= 1799);
- double yearsSince1700 = gregorianYear - 1700;
- return PolynomialSum(Coefficients1700to1799, yearsSince1700) / SecondsPerDay;
- }
-
- static double EphemerisCorrection1620to1699(int gregorianYear)
- {
- Debug.Assert(1620 <= gregorianYear && gregorianYear <= 1699);
- double yearsSince1600 = gregorianYear - 1600;
- return PolynomialSum(Coefficients1620to1699, yearsSince1600) / SecondsPerDay;
- }
-
- // ephemeris-correction: correction to account for the slowing down of the rotation of the earth
- static double EphemerisCorrection(double time)
- {
- int year = GetGregorianYear(time);
- foreach (EphemerisCorrectionAlgorithmMap map in EphemerisCorrectionTable)
- {
- if (map._lowestYear <= year)
- {
- switch (map._algorithm)
- {
- case CorrectionAlgorithm.Default: return DefaultEphemerisCorrection(year);
- case CorrectionAlgorithm.Year1988to2019: return EphemerisCorrection1988to2019(year);
- case CorrectionAlgorithm.Year1900to1987: return EphemerisCorrection1900to1987(year);
- case CorrectionAlgorithm.Year1800to1899: return EphemerisCorrection1800to1899(year);
- case CorrectionAlgorithm.Year1700to1799: return EphemerisCorrection1700to1799(year);
- case CorrectionAlgorithm.Year1620to1699: return EphemerisCorrection1620to1699(year);
- }
-
- break; // break the loop and assert eventually
- }
- }
-
- Debug.Assert(false, "Not expected to come here");
- return DefaultEphemerisCorrection(year);
- }
-
- static public double JulianCenturies(double moment)
- {
- double dynamicalMoment = moment + EphemerisCorrection(moment);
- return (dynamicalMoment - Noon2000Jan01) / DaysInUniformLengthCentury;
- }
-
- static bool IsNegative(double value)
- {
- return Math.Sign(value) == -1;
- }
-
- static double CopySign(double value, double sign)
- {
- return (IsNegative(value) == IsNegative(sign)) ? value : -value;
- }
-
- // equation-of-time; approximate the difference between apparent solar time and mean solar time
- // formal definition is EOT = GHA - GMHA
- // GHA is the Greenwich Hour Angle of the apparent (actual) Sun
- // GMHA is the Greenwich Mean Hour Angle of the mean (fictitious) Sun
- // http://www.esrl.noaa.gov/gmd/grad/solcalc/
- // http://en.wikipedia.org/wiki/Equation_of_time
- static double EquationOfTime(double time)
- {
- double julianCenturies = JulianCenturies(time);
- double lambda = PolynomialSum(LambdaCoefficients, julianCenturies);
- double anomaly = PolynomialSum(AnomalyCoefficients, julianCenturies);
- double eccentricity = PolynomialSum(EccentricityCoefficients, julianCenturies);
-
- double epsilon = Obliquity(julianCenturies);
- double tanHalfEpsilon = TanOfDegree(epsilon / 2);
- double y = tanHalfEpsilon * tanHalfEpsilon;
-
- double dividend = ((y * SinOfDegree(2 * lambda))
- - (2 * eccentricity * SinOfDegree(anomaly))
- + (4 * eccentricity * y * SinOfDegree(anomaly) * CosOfDegree(2 * lambda))
- - (0.5 * Math.Pow(y, 2) * SinOfDegree(4 * lambda))
- - (1.25 * Math.Pow(eccentricity, 2) * SinOfDegree(2 * anomaly)));
- double divisor = 2 * Math.PI;
- double equation = dividend / divisor;
-
- // approximation of equation of time is not valid for dates that are many millennia in the past or future
- // thus limited to a half day
- return CopySign(Math.Min(Math.Abs(equation), TwelveHours), equation);
- }
-
- static double AsLocalTime(double apparentMidday, double longitude)
- {
- // slightly inaccurate since equation of time takes mean time not apparent time as its argument, but the difference is negligible
- double universalTime = apparentMidday - AsDayFraction(longitude);
- return apparentMidday - EquationOfTime(universalTime);
- }
-
- // midday
- static public double Midday(double date, double longitude)
- {
- return AsLocalTime(date+TwelveHours, longitude) - AsDayFraction(longitude);
- }
-
- static double InitLongitude(double longitude)
- {
- return NormalizeLongitude(longitude + HalfCircleOfArc) - HalfCircleOfArc;
- }
-
- // midday-in-tehran
- static public double MiddayAtPersianObservationSite(double date)
- {
- return Midday(date, InitLongitude(52.5)); // 52.5 degrees east - longitude of UTC+3:30 which defines Iranian Standard Time
- }
-
- static double PeriodicTerm(double julianCenturies, int x, double y, double z)
- {
- return x * SinOfDegree(y + z * julianCenturies);
- }
-
- static double SumLongSequenceOfPeriodicTerms(double julianCenturies)
- {
- double sum = 0.0;
- sum += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892);
- sum += PeriodicTerm(julianCenturies, 195207, 340.19128, 35999.1376958);
- sum += PeriodicTerm(julianCenturies, 119433, 63.91854, 35999.4089666);
- sum += PeriodicTerm(julianCenturies, 112392, 331.2622, 35998.7287385);
- sum += PeriodicTerm(julianCenturies, 3891, 317.843, 71998.20261);
- sum += PeriodicTerm(julianCenturies, 2819, 86.631, 71998.4403);
- sum += PeriodicTerm(julianCenturies, 1721, 240.052, 36000.35726);
- sum += PeriodicTerm(julianCenturies, 660, 310.26, 71997.4812);
- sum += PeriodicTerm(julianCenturies, 350, 247.23, 32964.4678);
- sum += PeriodicTerm(julianCenturies, 334, 260.87, -19.441);
- sum += PeriodicTerm(julianCenturies, 314, 297.82, 445267.1117);
- sum += PeriodicTerm(julianCenturies, 268, 343.14, 45036.884);
- sum += PeriodicTerm(julianCenturies, 242, 166.79, 3.1008);
- sum += PeriodicTerm(julianCenturies, 234, 81.53, 22518.4434);
- sum += PeriodicTerm(julianCenturies, 158, 3.5, -19.9739);
- sum += PeriodicTerm(julianCenturies, 132, 132.75, 65928.9345);
- sum += PeriodicTerm(julianCenturies, 129, 182.95, 9038.0293);
- sum += PeriodicTerm(julianCenturies, 114, 162.03, 3034.7684);
- sum += PeriodicTerm(julianCenturies, 99, 29.8, 33718.148);
- sum += PeriodicTerm(julianCenturies, 93, 266.4, 3034.448);
- sum += PeriodicTerm(julianCenturies, 86, 249.2, -2280.773);
- sum += PeriodicTerm(julianCenturies, 78, 157.6, 29929.992);
- sum += PeriodicTerm(julianCenturies, 72, 257.8, 31556.493);
- sum += PeriodicTerm(julianCenturies, 68, 185.1, 149.588);
- sum += PeriodicTerm(julianCenturies, 64, 69.9, 9037.75);
- sum += PeriodicTerm(julianCenturies, 46, 8.0, 107997.405);
- sum += PeriodicTerm(julianCenturies, 38, 197.1, -4444.176);
- sum += PeriodicTerm(julianCenturies, 37, 250.4, 151.771);
- sum += PeriodicTerm(julianCenturies, 32, 65.3, 67555.316);
- sum += PeriodicTerm(julianCenturies, 29, 162.7, 31556.08);
- sum += PeriodicTerm(julianCenturies, 28, 341.5, -4561.54);
- sum += PeriodicTerm(julianCenturies, 27, 291.6, 107996.706);
- sum += PeriodicTerm(julianCenturies, 27, 98.5, 1221.655);
- sum += PeriodicTerm(julianCenturies, 25, 146.7, 62894.167);
- sum += PeriodicTerm(julianCenturies, 24, 110.0, 31437.369);
- sum += PeriodicTerm(julianCenturies, 21, 5.2, 14578.298);
- sum += PeriodicTerm(julianCenturies, 21, 342.6, -31931.757);
- sum += PeriodicTerm(julianCenturies, 20, 230.9, 34777.243);
- sum += PeriodicTerm(julianCenturies, 18, 256.1, 1221.999);
- sum += PeriodicTerm(julianCenturies, 17, 45.3, 62894.511);
- sum += PeriodicTerm(julianCenturies, 14, 242.9, -4442.039);
- sum += PeriodicTerm(julianCenturies, 13, 115.2, 107997.909);
- sum += PeriodicTerm(julianCenturies, 13, 151.8, 119.066);
- sum += PeriodicTerm(julianCenturies, 13, 285.3, 16859.071);
- sum += PeriodicTerm(julianCenturies, 12, 53.3, -4.578);
- sum += PeriodicTerm(julianCenturies, 10, 126.6, 26895.292);
- sum += PeriodicTerm(julianCenturies, 10, 205.7, -39.127);
- sum += PeriodicTerm(julianCenturies, 10, 85.9, 12297.536);
- sum += PeriodicTerm(julianCenturies, 10, 146.1, 90073.778);
- return sum;
- }
-
- static double Aberration(double julianCenturies)
- {
- return (0.0000974 * CosOfDegree(177.63 + (35999.01848 * julianCenturies))) - 0.005575;
- }
-
- static double Nutation(double julianCenturies)
- {
- double a = PolynomialSum(CoefficientsA, julianCenturies);
- double b = PolynomialSum(CoefficientsB, julianCenturies);
- return (-0.004778 * SinOfDegree(a)) - (0.0003667 * SinOfDegree(b));
- }
-
- static public double Compute(double time)
- {
- double julianCenturies = JulianCenturies(time);
- double lambda = 282.7771834
- + (36000.76953744 * julianCenturies)
- + (0.000005729577951308232 * SumLongSequenceOfPeriodicTerms(julianCenturies));
-
- double longitude = lambda + Aberration(julianCenturies) + Nutation(julianCenturies);
- return InitLongitude(longitude);
- }
-
- static public double AsSeason(double longitude)
- {
- return (longitude < 0) ? (longitude + FullCircleOfArc) : longitude;
- }
-
- static double EstimatePrior(double longitude, double time)
- {
- double timeSunLastAtLongitude = time - (MeanSpeedOfSun * AsSeason(InitLongitude(Compute(time) - longitude)));
- double longitudeErrorDelta = InitLongitude(Compute(timeSunLastAtLongitude) - longitude);
- return Math.Min(time, timeSunLastAtLongitude - (MeanSpeedOfSun * longitudeErrorDelta));
- }
-
- // persian-new-year-on-or-before
- // number of days is the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
- // 1/1/0001 is absolute date 1.
- internal static long PersianNewYearOnOrBefore(long numberOfDays)
- {
- double date = (double) numberOfDays;
-
- double approx = EstimatePrior(LongitudeSpring, MiddayAtPersianObservationSite(date));
- long lowerBoundNewYearDay = (long) Math.Floor(approx) - 1;
- long upperBoundNewYearDay = lowerBoundNewYearDay + 3; // estimate is generally within a day of the actual occurrance (at the limits, the error expands, since the calculations rely on the mean tropical year which changes...)
- long day = lowerBoundNewYearDay;
- for (; day != upperBoundNewYearDay; ++day)
- {
- double midday = MiddayAtPersianObservationSite((double) day);
- double l = Compute(midday);
- if ((LongitudeSpring <= l) && (l <= TwoDegreesAfterSpring))
- {
- break;
- }
- }
- Debug.Assert(day != upperBoundNewYearDay);
-
- return day - 1;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
index 2822b418ef..8e3bb47424 100644
--- a/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfo.cs
@@ -12,22 +12,12 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
- //This class has only static members and therefore doesn't need to be serialized.
-
- using System;
- using System.Threading;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Reflection;
- using System.Security;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-
- public static class CharUnicodeInfo
+namespace System.Globalization
+{
+ public static partial class CharUnicodeInfo
{
//--------------------------------------------------------------------//
// Internal Information //
@@ -36,95 +26,18 @@ namespace System.Globalization {
//
// Native methods to access the Unicode category data tables in charinfo.nlp.
//
- internal const char HIGH_SURROGATE_START = '\ud800';
- internal const char HIGH_SURROGATE_END = '\udbff';
- internal const char LOW_SURROGATE_START = '\udc00';
- internal const char LOW_SURROGATE_END = '\udfff';
+ internal const char HIGH_SURROGATE_START = '\ud800';
+ internal const char HIGH_SURROGATE_END = '\udbff';
+ internal const char LOW_SURROGATE_START = '\udc00';
+ internal const char LOW_SURROGATE_END = '\udfff';
internal const int UNICODE_CATEGORY_OFFSET = 0;
internal const int BIDI_CATEGORY_OFFSET = 1;
- static bool s_initialized = InitTable();
-
- // The native pointer to the 12:4:4 index table of the Unicode cateogry data.
- unsafe static ushort* s_pCategoryLevel1Index;
- unsafe static byte* s_pCategoriesValue;
-
- // The native pointer to the 12:4:4 index table of the Unicode numeric data.
- // The value of this index table is an index into the real value table stored in s_pNumericValues.
- unsafe static ushort* s_pNumericLevel1Index;
-
- // The numeric value table, which is indexed by s_pNumericLevel1Index.
- // Every item contains the value for numeric value.
- // unsafe static double* s_pNumericValues;
- // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting
- // at 4-byte boundary. This cause a alignment issue since double is 8-byte.
- unsafe static byte* s_pNumericValues;
-
- // The digit value table, which is indexed by s_pNumericLevel1Index. It shares the same indice as s_pNumericValues.
- // Every item contains the value for decimal digit/digit value.
- unsafe static DigitValues* s_pDigitValues;
-
- internal const String UNICODE_INFO_FILE_NAME = "charinfo.nlp";
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
- //
- // This is the header for the native data table that we load from UNICODE_INFO_FILE_NAME.
- //
- // Excplicit layout is used here since a syntax like char[16] can not be used in sequential layout.
- [StructLayout(LayoutKind.Explicit)]
- internal unsafe struct UnicodeDataHeader {
- [FieldOffset(0)]
- internal char TableName; // WCHAR[16]
- [FieldOffset(0x20)]
- internal ushort version; // WORD[4]
- [FieldOffset(0x28)]
- internal uint OffsetToCategoriesIndex; // DWORD
- [FieldOffset(0x2c)]
- internal uint OffsetToCategoriesValue; // DWORD
- [FieldOffset(0x30)]
- internal uint OffsetToNumbericIndex; // DWORD
- [FieldOffset(0x34)]
- internal uint OffsetToDigitValue; // DWORD
- [FieldOffset(0x38)]
- internal uint OffsetToNumbericValue; // DWORD
-
- }
-
- // NOTE: It's important to specify pack size here, since the size of the structure is 2 bytes. Otherwise,
- // the default pack size will be 4.
-
- [StructLayout(LayoutKind.Sequential, Pack=2)]
- internal struct DigitValues {
- internal sbyte decimalDigit;
- internal sbyte digit;
- }
-
-
- //We need to allocate the underlying table that provides us with the information that we
- //use. We allocate this once in the class initializer and then we don't need to worry
- //about it again.
- //
- unsafe static bool InitTable() {
-
- // Go to native side and get pointer to the native table
- byte * pDataTable = GlobalizationAssembly.GetGlobalizationResourceBytePtr(typeof(CharUnicodeInfo).Assembly, UNICODE_INFO_FILE_NAME);
-
- UnicodeDataHeader* mainHeader = (UnicodeDataHeader*)pDataTable;
-
- // Set up the native pointer to different part of the tables.
- s_pCategoryLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToCategoriesIndex);
- s_pCategoriesValue = (byte*) (pDataTable + mainHeader->OffsetToCategoriesValue);
- s_pNumericLevel1Index = (ushort*) (pDataTable + mainHeader->OffsetToNumbericIndex);
- s_pNumericValues = (byte*) (pDataTable + mainHeader->OffsetToNumbericValue);
- s_pDigitValues = (DigitValues*) (pDataTable + mainHeader->OffsetToDigitValue);
-
- return true;
- }
-
-
////////////////////////////////////////////////////////////////////////
//
// Actions:
@@ -137,14 +50,18 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- internal static int InternalConvertToUtf32(String s, int index) {
+ internal static int InternalConvertToUtf32(String s, int index)
+ {
Debug.Assert(s != null, "s != null");
Debug.Assert(index >= 0 && index < s.Length, "index < s.Length");
- if (index < s.Length - 1) {
+ if (index < s.Length - 1)
+ {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
- if (temp1 >= 0 && temp1 <= 0x3ff) {
- int temp2 = (int)s[index+1] - LOW_SURROGATE_START;
- if (temp2 >= 0 && temp2 <= 0x3ff) {
+ if (temp1 >= 0 && temp1 <= 0x3ff)
+ {
+ int temp2 = (int)s[index + 1] - LOW_SURROGATE_START;
+ if (temp2 >= 0 && temp2 <= 0x3ff)
+ {
// Convert the surrogate to UTF32 and get the result.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
@@ -152,7 +69,6 @@ namespace System.Globalization {
}
return ((int)s[index]);
}
-
////////////////////////////////////////////////////////////////////////
//
// Convert a character or a surrogate pair starting at index of string s
@@ -175,16 +91,20 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- internal static int InternalConvertToUtf32(String s, int index, out int charLength) {
+ internal static int InternalConvertToUtf32(String s, int index, out int charLength)
+ {
Debug.Assert(s != null, "s != null");
Debug.Assert(s.Length > 0, "s.Length > 0");
Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
charLength = 1;
- if (index < s.Length - 1) {
+ if (index < s.Length - 1)
+ {
int temp1 = (int)s[index] - HIGH_SURROGATE_START;
- if (temp1 >= 0 && temp1 <= 0x3ff) {
- int temp2 = (int)s[index+1] - LOW_SURROGATE_START;
- if (temp2 >= 0 && temp2 <= 0x3ff) {
+ if (temp1 >= 0 && temp1 <= 0x3ff)
+ {
+ int temp2 = (int)s[index + 1] - LOW_SURROGATE_START;
+ if (temp2 >= 0 && temp2 <= 0x3ff)
+ {
// Convert the surrogate to UTF32 and get the result.
charLength++;
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
@@ -210,7 +130,8 @@ namespace System.Globalization {
UnicodeCategory uc = GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
- switch (uc) {
+ switch (uc)
+ {
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
@@ -225,7 +146,8 @@ namespace System.Globalization {
UnicodeCategory uc = GetUnicodeCategory(c);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
- switch (uc) {
+ switch (uc)
+ {
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
@@ -235,12 +157,14 @@ namespace System.Globalization {
return (false);
}
+
//
// This is called by the public char and string, index versions
//
// Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
//
- internal unsafe static double InternalGetNumericValue(int ch) {
+ internal static unsafe double InternalGetNumericValue(int ch)
+ {
Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
@@ -248,52 +172,34 @@ namespace System.Globalization {
// The offset is referred to an float item in m_pNumericFloatData.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)];
- byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]);
- // Get the result from the 0 -3 bit of ch.
-#if BIT64
- // To get around the IA64 alignment issue. Our double data is aligned in 8-byte boundary, but loader loads the embeded table starting
- // at 4-byte boundary. This cause a alignment issue since double is 8-byte.
- byte* pSourcePtr = &(s_pNumericValues[pBytePtr[(ch & 0x000f)] * sizeof(double)]);
- if (((long)pSourcePtr % 8) != 0) {
- // We are not aligned in 8-byte boundary. Do a copy.
- double ret;
- byte* retPtr = (byte*)&ret;
- Buffer.Memcpy(retPtr, pSourcePtr, sizeof(double));
- return (ret);
+
+ fixed (ushort* pUshortPtr = &(s_pNumericLevel1Index[index]))
+ {
+ byte* pBytePtr = (byte*)pUshortPtr;
+ fixed (byte* pByteNum = s_pNumericValues)
+ {
+ double* pDouble = (double*)pByteNum;
+ return pDouble[pBytePtr[(ch & 0x000f)]];
+ }
}
- return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]);
-#else
- return (((double*)s_pNumericValues)[pBytePtr[(ch & 0x000f)]]);
-#endif
}
- //
- // This is called by the public char and string, index versions
- //
- // Note that for ch in the range D800-DFFF we just treat it as any other non-numeric character
- //
- internal unsafe static DigitValues* InternalGetDigitValues(int ch) {
+ internal static unsafe ushort InternalGetDigitValues(int ch)
+ {
Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pNumericLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
- // The offset is referred to an float item in m_pNumericFloatData.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pNumericLevel1Index[index + ((ch >> 4) & 0x000f)];
- byte* pBytePtr = (byte*)&(s_pNumericLevel1Index[index]);
- // Get the result from the 0 -3 bit of ch.
- return &(s_pDigitValues[pBytePtr[(ch & 0x000f)]]);
- }
- internal unsafe static sbyte InternalGetDecimalDigitValue(int ch) {
- return (InternalGetDigitValues(ch)->decimalDigit);
- }
-
- internal unsafe static sbyte InternalGetDigitValue(int ch) {
- return (InternalGetDigitValues(ch)->digit);
+ fixed (ushort* pUshortPtr = &(s_pNumericLevel1Index[index]))
+ {
+ byte* pBytePtr = (byte*)pUshortPtr;
+ return s_pDigitValues[pBytePtr[(ch & 0x000f)]];
+ }
}
-
////////////////////////////////////////////////////////////////////////
//
//Returns the numeric value associated with the character c. If the character is a fraction,
@@ -310,114 +216,91 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public static double GetNumericValue(char ch) {
+ public static double GetNumericValue(char ch)
+ {
return (InternalGetNumericValue(ch));
}
- public static double GetNumericValue(String s, int index) {
- if (s == null) {
+ public static double GetNumericValue(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
return (InternalGetNumericValue(InternalConvertToUtf32(s, index)));
-
}
- ////////////////////////////////////////////////////////////////////////
- //
- //Returns the decimal digit value associated with the character c.
- //
- // The value should be from 0 ~ 9.
- // If the character does not have a numeric value, the return value is -1.
- // From Unicode.org: Decimal Digits. Digits that can be used to form decimal-radix numbers.
- //Returns:
- // the decimal digit value for the specified Unicode character. If the character does not have a decimal digit value, the return value is -1.
- //Arguments:
- // ch a Unicode character
- //Exceptions:
- // ArgumentNullException
- // ArgumentOutOfRangeException
- //
- ////////////////////////////////////////////////////////////////////////
-
-
- public static int GetDecimalDigitValue(char ch) {
- return (InternalGetDecimalDigitValue(ch));
+ public static int GetDecimalDigitValue(char ch)
+ {
+ return (sbyte)(InternalGetDigitValues(ch) >> 8);
}
-
- public static int GetDecimalDigitValue(String s, int index) {
- if (s == null) {
+ public static int GetDecimalDigitValue(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
- return (InternalGetDecimalDigitValue(InternalConvertToUtf32(s, index)));
+ return (sbyte)(InternalGetDigitValues(InternalConvertToUtf32(s, index)) >> 8);
}
- ////////////////////////////////////////////////////////////////////////
- //
- //Action: Returns the digit value associated with the character c.
- // If the character does not have a numeric value, the return value is -1.
- // From Unicode.org: If the character represents a digit, not necessarily a decimal digit,
- // the value is here. This covers digits which do not form decimal radix forms, such as the compatibility superscript digits.
- //
- // An example is: U+2460 IRCLED DIGIT ONE. This character has digit value 1, but does not have associcated decimal digit value.
- //
- //Returns:
- // the digit value for the specified Unicode character. If the character does not have a digit value, the return value is -1.
- //Arguments:
- // ch a Unicode character
- //Exceptions:
- // ArgumentNullException
- // ArgumentOutOfRangeException
- //
- ////////////////////////////////////////////////////////////////////////
-
-
- public static int GetDigitValue(char ch) {
- return (InternalGetDigitValue(ch));
+ public static int GetDigitValue(char ch)
+ {
+ return (sbyte)(InternalGetDigitValues(ch) & 0x00FF);
}
-
- public static int GetDigitValue(String s, int index) {
- if (s == null) {
+ public static int GetDigitValue(String s, int index)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
- if (index < 0 || index >= s.Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
+
Contract.EndContractBlock();
- return (InternalGetDigitValue(InternalConvertToUtf32(s, index)));
+ return (sbyte)(InternalGetDigitValues(InternalConvertToUtf32(s, index)) & 0x00FF);
}
public static UnicodeCategory GetUnicodeCategory(char ch)
{
- return (InternalGetUnicodeCategory(ch)) ;
+ return (InternalGetUnicodeCategory(ch));
}
public static UnicodeCategory GetUnicodeCategory(String s, int index)
{
- if (s==null)
+ if (s == null)
throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
+ if (((uint)index) >= ((uint)s.Length))
+ {
throw new ArgumentOutOfRangeException(nameof(index));
}
Contract.EndContractBlock();
return InternalGetUnicodeCategory(s, index);
}
- internal unsafe static UnicodeCategory InternalGetUnicodeCategory(int ch) {
+ internal static unsafe UnicodeCategory InternalGetUnicodeCategory(int ch)
+ {
return ((UnicodeCategory)InternalGetCategoryValue(ch, UNICODE_CATEGORY_OFFSET));
}
+
////////////////////////////////////////////////////////////////////////
//
//Action: Returns the Unicode Category property for the character c.
@@ -432,37 +315,28 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- internal unsafe static byte InternalGetCategoryValue(int ch, int offset) {
+ internal static unsafe byte InternalGetCategoryValue(int ch, int offset)
+ {
Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range.");
// Get the level 2 item from the highest 12 bit (8 - 19) of ch.
ushort index = s_pCategoryLevel1Index[ch >> 8];
// Get the level 2 WORD offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table.
// Note that & has the lower precedence than addition, so don't forget the parathesis.
index = s_pCategoryLevel1Index[index + ((ch >> 4) & 0x000f)];
- byte* pBytePtr = (byte*)&(s_pCategoryLevel1Index[index]);
- // Get the result from the 0 -3 bit of ch.
- byte valueIndex = pBytePtr[(ch & 0x000f)];
- byte uc = s_pCategoriesValue[valueIndex * 2 + offset];
- //
- // Make sure that OtherNotAssigned is the last category in UnicodeCategory.
- // If that changes, change the following assertion as well.
- //
- //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
- return (uc);
- }
-// internal static BidiCategory GetBidiCategory(char ch) {
-// return ((BidiCategory)InternalGetCategoryValue(c, BIDI_CATEGORY_OFFSET));
-// }
-
- internal static BidiCategory GetBidiCategory(String s, int index) {
- if (s==null)
- throw new ArgumentNullException(nameof(s));
- if (((uint)index)>=((uint)s.Length)) {
- throw new ArgumentOutOfRangeException(nameof(index));
+ fixed (ushort* pUshortPtr = &(s_pCategoryLevel1Index[index]))
+ {
+ byte* pBytePtr = (byte*)pUshortPtr;
+ // Get the result from the 0 -3 bit of ch.
+ byte valueIndex = pBytePtr[(ch & 0x000f)];
+ byte uc = s_pCategoriesValue[valueIndex * 2 + offset];
+ //
+ // Make sure that OtherNotAssigned is the last category in UnicodeCategory.
+ // If that changes, change the following assertion as well.
+ //
+ //Debug.Assert(uc >= 0 && uc <= UnicodeCategory.OtherNotAssigned, "Table returns incorrect Unicode category");
+ return (uc);
}
- Contract.EndContractBlock();
- return ((BidiCategory)InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET));
}
////////////////////////////////////////////////////////////////////////
@@ -478,13 +352,27 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index) {
+ internal static UnicodeCategory InternalGetUnicodeCategory(String value, int index)
+ {
Debug.Assert(value != null, "value can not be null");
Debug.Assert(index < value.Length, "index < value.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(value, index)));
}
+ internal static BidiCategory GetBidiCategory(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+
+ return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET));
+ }
+
////////////////////////////////////////////////////////////////////////
//
// Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1.
@@ -492,15 +380,17 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength) {
+ internal static UnicodeCategory InternalGetUnicodeCategory(String str, int index, out int charLength)
+ {
Debug.Assert(str != null, "str can not be null");
- Debug.Assert(str.Length > 0, "str.Length > 0");;
+ Debug.Assert(str.Length > 0, "str.Length > 0"); ;
Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length");
return (InternalGetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)));
}
- internal static bool IsCombiningCategory(UnicodeCategory uc) {
+ internal static bool IsCombiningCategory(UnicodeCategory uc)
+ {
Debug.Assert(uc >= 0, "uc >= 0");
return (
uc == UnicodeCategory.NonSpacingMark ||
diff --git a/src/mscorlib/src/System/Globalization/CharUnicodeInfoData.cs b/src/mscorlib/src/System/Globalization/CharUnicodeInfoData.cs
new file mode 100644
index 0000000000..b1bef8146e
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CharUnicodeInfoData.cs
@@ -0,0 +1,1247 @@
+// 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.Globalization
+{
+ public static partial class CharUnicodeInfo
+ {
+ // THE FOLLOWING DATA IS AUTO GENERATED BY GenUnicodeProp.pl SCRIPT UNDER THE TOOLS FOLDER
+ // PLEASE DON'T MODIFY BY HAND
+
+
+ // 12:4:4 index table of the Unicode cateogry data.
+ private static ushort[] s_pCategoryLevel1Index = new ushort[]
+ {
+ 0x1100, 0x1110, 0x1120, 0x1130, 0x1140, 0x1150, 0x1160, 0x1170, 0x1180, 0x1190, 0x11a0, 0x11b0, 0x11c0, 0x11d0, 0x11e0, 0x11f0,
+ 0x1200, 0x1210, 0x1220, 0x1230, 0x1240, 0x1210, 0x1250, 0x1260, 0x1270, 0x1280, 0x1290, 0x12a0, 0x12b0, 0x12c0, 0x12d0, 0x12e0,
+ 0x12f0, 0x1300, 0x1310, 0x1320, 0x1330, 0x1340, 0x1350, 0x1360, 0x1370, 0x1380, 0x1390, 0x13a0, 0x13b0, 0x13c0, 0x13d0, 0x13e0,
+ 0x13f0, 0x1400, 0x1410, 0x1420, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1430, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1440,
+ 0x1450, 0x1210, 0x1210, 0x1210, 0x1460, 0x1210, 0x1470, 0x1480, 0x1490, 0x14a0, 0x14b0, 0x14c0, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x14d0, 0x14e0, 0x14e0, 0x14e0, 0x14e0, 0x14e0, 0x14e0, 0x14e0, 0x14e0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x1210, 0x1500, 0x1510, 0x1520, 0x1530, 0x1540, 0x1550,
+ 0x1560, 0x1570, 0x1580, 0x1590, 0x15a0, 0x15b0, 0x1210, 0x15c0, 0x15d0, 0x15e0, 0x15f0, 0x1600, 0x1610, 0x1620, 0x1630, 0x1620,
+ 0x1640, 0x1650, 0x1660, 0x1670, 0x1680, 0x1690, 0x16a0, 0x16b0, 0x16c0, 0x1620, 0x16d0, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1210, 0x1210, 0x1210, 0x16e0, 0x16f0, 0x1700, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1710, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1210, 0x1210, 0x1720, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1210, 0x1210, 0x1730, 0x1740, 0x1620, 0x1620, 0x1620, 0x1750,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1760, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1770, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1780, 0x1790, 0x17a0, 0x17b0, 0x17c0, 0x17d0, 0x17e0, 0x17f0, 0x1370, 0x1370, 0x1800, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1810, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1820, 0x1620,
+ 0x1830, 0x1840, 0x1850, 0x1860, 0x1870, 0x1880, 0x1890, 0x18a0, 0x18b0, 0x18c0, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x18d0, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x18e0, 0x18f0, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210,
+ 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1210, 0x1900, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1210, 0x1210, 0x1910, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1920, 0x1930, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620, 0x1620,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x1940,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0,
+ 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x14f0, 0x1940,
+ 0x1950, 0x1958, 0x1960, 0x1968, 0x1970, 0x1978, 0x1980, 0x1988, 0x1990, 0x1998, 0x19a0, 0x19a8, 0x19b0, 0x19b8, 0x19c0, 0x19c8,
+ 0x19d0, 0x19d0, 0x19d0, 0x19d8, 0x19e0, 0x19d0, 0x19d0, 0x19e8, 0x19f0, 0x19f8, 0x1a00, 0x1a08, 0x1a10, 0x1a18, 0x19d0, 0x1a20,
+ 0x19d0, 0x19d0, 0x19d0, 0x1a28, 0x1a30, 0x19c0, 0x19c0, 0x19c0, 0x19c0, 0x1a38, 0x19c0, 0x1a40, 0x1a48, 0x1a50, 0x1a58, 0x1a60,
+ 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a70, 0x1a78, 0x1a80, 0x1a88, 0x19c0, 0x1a90, 0x1a98, 0x19d0, 0x1aa0,
+ 0x19b0, 0x19b0, 0x19b0, 0x19c0, 0x19c0, 0x19c0, 0x19d0, 0x19d0, 0x1aa8, 0x19d0, 0x19d0, 0x19d0, 0x1ab0, 0x19d0, 0x19d0, 0x19d0,
+ 0x19d0, 0x19d0, 0x19d0, 0x1ab8, 0x19b0, 0x1ac0, 0x1ac8, 0x19c0, 0x1ad0, 0x1ad8, 0x1a68, 0x1ae0, 0x1ae8, 0x1af0, 0x1af8, 0x1b00,
+ 0x1b08, 0x1b10, 0x1b18, 0x1b18, 0x1b20, 0x1a68, 0x1b28, 0x1b30, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b38, 0x1b40, 0x1b48,
+ 0x1b50, 0x1b58, 0x1b18, 0x1a68, 0x1b60, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b68, 0x1b70, 0x1b78, 0x1af0, 0x1b80, 0x1b88,
+ 0x1af0, 0x1b90, 0x1b98, 0x1ba0, 0x1af0, 0x1ba8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1b18, 0x1bb8, 0x1bb0, 0x1bb0, 0x1bc0, 0x1a68,
+ 0x1bc8, 0x1bd0, 0x1bd0, 0x1bd8, 0x1be0, 0x1be8, 0x1bf0, 0x1bf8, 0x1c00, 0x1c08, 0x1c10, 0x1c18, 0x1c20, 0x1c28, 0x1c30, 0x1c38,
+ 0x1c40, 0x1c08, 0x1c10, 0x1c48, 0x1c50, 0x1c58, 0x1c60, 0x1c68, 0x1c70, 0x1c78, 0x1c10, 0x1c80, 0x1c88, 0x1c90, 0x1c30, 0x1c98,
+ 0x1ca0, 0x1c08, 0x1c10, 0x1ca8, 0x1cb0, 0x1cb8, 0x1c30, 0x1cc0, 0x1cc8, 0x1cd0, 0x1cd8, 0x1ce0, 0x1ce8, 0x1cf0, 0x1c60, 0x1cf8,
+ 0x1d00, 0x1d08, 0x1c10, 0x1d10, 0x1d18, 0x1d20, 0x1c30, 0x1d28, 0x1d30, 0x1d08, 0x1c10, 0x1d38, 0x1d40, 0x1d48, 0x1c30, 0x1d50,
+ 0x1d30, 0x1d08, 0x1bd0, 0x1d58, 0x1d60, 0x1d68, 0x1c30, 0x1d70, 0x1d78, 0x1d80, 0x1bd0, 0x1d88, 0x1d90, 0x1d98, 0x1c60, 0x1da0,
+ 0x1da8, 0x1bd0, 0x1bd0, 0x1db0, 0x1db8, 0x1dc0, 0x1bb0, 0x1bb0, 0x1dc8, 0x1dd0, 0x1dd8, 0x1de0, 0x1de8, 0x1df0, 0x1bb0, 0x1bb0,
+ 0x1df8, 0x1e00, 0x1e08, 0x1e10, 0x1e18, 0x1bd0, 0x1e20, 0x1e28, 0x1e30, 0x1e38, 0x1a68, 0x1e40, 0x1e48, 0x1e50, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1e58, 0x1e60, 0x1e68, 0x1e70, 0x1e78, 0x1e80, 0x1e88, 0x1e90, 0x19b0, 0x19b0, 0x1e98, 0x1bd0, 0x1bd0, 0x1ea0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1ea8, 0x1eb0, 0x1bd0, 0x1bd0, 0x1ea8, 0x1bd0, 0x1bd0, 0x1eb8, 0x1ec0, 0x1ec8, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1ec0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1ed0, 0x1ed8, 0x1ee0, 0x1bd0, 0x1ee8, 0x19b0, 0x19b0, 0x19b0, 0x19b0, 0x19b0, 0x1ef0,
+ 0x1ef8, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1f00, 0x1bd0, 0x1f08, 0x1f10, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1f18, 0x1f20,
+ 0x1f28, 0x1f30, 0x1bd0, 0x1f38, 0x1bd0, 0x1f40, 0x1f28, 0x1f48, 0x1bd0, 0x1bd0, 0x1bd0, 0x1f50, 0x1f58, 0x1f60, 0x1f68, 0x1f70,
+ 0x1f78, 0x1f68, 0x1bd0, 0x1bd0, 0x1f80, 0x1bd0, 0x1bd0, 0x1f88, 0x1bd0, 0x1bd0, 0x1f90, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1f98,
+ 0x1bd0, 0x1fa0, 0x1fa8, 0x1fb0, 0x1fb8, 0x1bd0, 0x1fc0, 0x1fc8, 0x1bd0, 0x1bd0, 0x1fd0, 0x1bd0, 0x1fd8, 0x1fe0, 0x1fe8, 0x1fe8,
+ 0x1bd0, 0x1ff0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1ff8, 0x2000, 0x2008, 0x1f68, 0x1f68, 0x2010, 0x2018, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x2020, 0x1bd0, 0x1bd0, 0x2028, 0x2030, 0x1e68, 0x2038, 0x2040, 0x2048, 0x1bd0, 0x2050, 0x2058, 0x1bd0, 0x1bd0, 0x2060, 0x2068,
+ 0x1bd0, 0x1bd0, 0x2070, 0x2078, 0x2080, 0x2058, 0x1bd0, 0x2088, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x2090, 0x2098, 0x20a0, 0x20a8,
+ 0x19c0, 0x19c0, 0x20b0, 0x20b8, 0x20b8, 0x20b8, 0x20c0, 0x20c8, 0x19c0, 0x20d0, 0x20b8, 0x20b8, 0x1a68, 0x1a68, 0x1a68, 0x20d8,
+ 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x20e0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0,
+ 0x20e8, 0x20f0, 0x20e8, 0x20e8, 0x20f0, 0x20f8, 0x20e8, 0x2100, 0x2108, 0x2108, 0x2108, 0x2110, 0x2118, 0x2120, 0x2128, 0x2130,
+ 0x2138, 0x2140, 0x2148, 0x2150, 0x2158, 0x2160, 0x2168, 0x2170, 0x2178, 0x2180, 0x2188, 0x2190, 0x1bb0, 0x2198, 0x21a0, 0x21a8,
+ 0x21b0, 0x21b8, 0x21c0, 0x21c8, 0x21d0, 0x21d8, 0x21e0, 0x21e0, 0x21e8, 0x21f0, 0x21f8, 0x1fe8, 0x2200, 0x2208, 0x1fe8, 0x2210,
+ 0x2218, 0x2220, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218,
+ 0x2228, 0x1fe8, 0x2230, 0x2238, 0x2240, 0x2240, 0x2240, 0x2248, 0x1fe8, 0x2250, 0x2218, 0x2258, 0x1fe8, 0x2260, 0x2268, 0x2270,
+ 0x1fe8, 0x1fe8, 0x2278, 0x1bb0, 0x2270, 0x1bb0, 0x21d8, 0x21d8, 0x2280, 0x2288, 0x2240, 0x2240, 0x2240, 0x2240, 0x2290, 0x21d8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2298, 0x22a0, 0x1fe8, 0x1fe8, 0x22a8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x22b0, 0x1fe8, 0x1fe8, 0x1fe8, 0x22b8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x22c0, 0x22c8, 0x21d8, 0x22d0, 0x1fe8, 0x1fe8, 0x22d8, 0x2218, 0x22e0, 0x2218,
+ 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240,
+ 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x22e8, 0x22f0, 0x2218, 0x2218, 0x2218, 0x22f8, 0x2218, 0x2300,
+ 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218, 0x2218,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x2218, 0x2308, 0x1fe8, 0x1fe8, 0x2310, 0x1fe8, 0x2318, 0x1fe8, 0x2320, 0x2328, 0x2330, 0x2338, 0x1bb0,
+ 0x19b0, 0x19b0, 0x2340, 0x19c0, 0x19c0, 0x2348, 0x2350, 0x2358, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x19d0, 0x2360, 0x2368,
+ 0x19c0, 0x19c0, 0x2370, 0x1bd0, 0x1bd0, 0x1bd0, 0x2378, 0x2380, 0x1bd0, 0x2388, 0x2390, 0x2390, 0x2390, 0x2390, 0x1a68, 0x1a68,
+ 0x2398, 0x23a0, 0x23a8, 0x23b0, 0x23b8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1fe8, 0x23c0, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x23c8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x23d0, 0x1bb0, 0x23d8,
+ 0x23e0, 0x23e8, 0x23f0, 0x23f8, 0x1da8, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2400, 0x1ef8, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2408,
+ 0x2410, 0x1bd0, 0x1fc0, 0x1da8, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1fa0, 0x2418, 0x1bd0, 0x2420, 0x1fe8, 0x1fe8, 0x23c8, 0x1bd0,
+ 0x2240, 0x2428, 0x2430, 0x2240, 0x2438, 0x2440, 0x2240, 0x2448, 0x2430, 0x2240, 0x2240, 0x2450, 0x2458, 0x2240, 0x2240, 0x2460,
+ 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2468, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2470, 0x2240, 0x2478,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1f98, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1f98, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x2480, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1e20, 0x1fe8, 0x1fe8, 0x1fe8, 0x2278, 0x1bd0, 0x1bd0, 0x2088,
+ 0x2488, 0x1bd0, 0x2490, 0x1bb0, 0x19d0, 0x19d0, 0x2498, 0x24a0, 0x19d0, 0x24a8, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x24b0, 0x24b8,
+ 0x1a60, 0x24c0, 0x24c8, 0x24d0, 0x19d0, 0x19d0, 0x19d0, 0x24d8, 0x24e0, 0x24e8, 0x24f0, 0x24f8, 0x1bb0, 0x1bb0, 0x1bb0, 0x2500,
+ 0x2508, 0x1bd0, 0x2510, 0x2518, 0x1bd0, 0x1bd0, 0x1bd0, 0x2520, 0x2528, 0x1bd0, 0x1bd0, 0x2530, 0x2538, 0x1f68, 0x1a68, 0x2540,
+ 0x2058, 0x1bd0, 0x2548, 0x1bd0, 0x2550, 0x2558, 0x1bd0, 0x1e20, 0x1bc8, 0x1bd0, 0x1bd0, 0x2560, 0x2568, 0x2570, 0x2578, 0x2580,
+ 0x1bd0, 0x1bd0, 0x2588, 0x2590, 0x2598, 0x25a0, 0x1bd0, 0x25a8, 0x1bd0, 0x1bd0, 0x1bd0, 0x25b0, 0x25b8, 0x25c0, 0x25c8, 0x25d0,
+ 0x25d8, 0x25e0, 0x2390, 0x19c0, 0x19c0, 0x25e8, 0x25f0, 0x19c0, 0x19c0, 0x19c0, 0x19c0, 0x19c0, 0x1bd0, 0x1bd0, 0x25f8, 0x1f68,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2600, 0x1bd0, 0x2608, 0x1bd0, 0x1bd0, 0x1fd0,
+ 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610, 0x2610,
+ 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1fc0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1fd8, 0x1bb0, 0x1bb0,
+ 0x2620, 0x2628, 0x2630, 0x2638, 0x2640, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x2648, 0x2650, 0x2658, 0x1b18, 0x1b18,
+ 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18,
+ 0x1b18, 0x1b18, 0x1b18, 0x2660, 0x1bb0, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x2668, 0x1b18, 0x1b18, 0x2670, 0x1bb0, 0x1bb0, 0x2678,
+ 0x1a68, 0x2680, 0x1a68, 0x2688, 0x2690, 0x2698, 0x26a0, 0x26a8, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x1b18, 0x26b0,
+ 0x26b8, 0x1968, 0x1970, 0x1978, 0x1980, 0x26c0, 0x26c8, 0x26d0, 0x1bd0, 0x26d8, 0x1bd0, 0x1fa0, 0x26e0, 0x26e8, 0x26f0, 0x26f8,
+ 0x2700, 0x1bd0, 0x1ec8, 0x2708, 0x1fc0, 0x1fc0, 0x1bb0, 0x1bb0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2420,
+ 0x2710, 0x2718, 0x2718, 0x2720, 0x2728, 0x2728, 0x2728, 0x2730, 0x2738, 0x23d8, 0x2740, 0x1bb0, 0x1bb0, 0x2240, 0x2240, 0x2748,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bd0, 0x1e20, 0x1bd0, 0x1bd0, 0x1bd0, 0x1c90, 0x2750, 0x2758,
+ 0x1bd0, 0x1bd0, 0x2760, 0x1bd0, 0x2768, 0x1bd0, 0x1bd0, 0x2770, 0x1bd0, 0x2778, 0x1bd0, 0x1bd0, 0x2780, 0x2788, 0x1bb0, 0x1bb0,
+ 0x19b0, 0x19b0, 0x2790, 0x19c0, 0x19c0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1fc0, 0x1f68, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1f88, 0x1bd0, 0x1bd0, 0x1bd0, 0x2798, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x2388, 0x1bd0, 0x1f98, 0x1f88, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x27a0, 0x1af0, 0x1af0, 0x27a8, 0x1af0, 0x27b0, 0x1af0, 0x27b8, 0x1af0, 0x27c0, 0x27c8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1af0, 0x27d0,
+ 0x1af0, 0x27d8, 0x1af0, 0x27e0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1af0, 0x1af0, 0x1af0, 0x27e8, 0x27f0, 0x27f8, 0x27f0, 0x27f0,
+ 0x2800, 0x2808, 0x1af0, 0x2810, 0x2818, 0x2820, 0x1af0, 0x2828, 0x1af0, 0x2830, 0x1bb0, 0x1bb0, 0x2838, 0x1af0, 0x2840, 0x2848,
+ 0x1af0, 0x1af0, 0x1af0, 0x2850, 0x1af0, 0x2858, 0x1af0, 0x2860, 0x1af0, 0x2868, 0x2870, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x2878, 0x1bb0, 0x1bb0, 0x1bb0, 0x2880, 0x2880, 0x2880, 0x2888, 0x2890, 0x2890, 0x2890, 0x2898,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x28a0, 0x28a8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x28b0, 0x1bd0, 0x1bd0, 0x28b8, 0x28c0, 0x28c8, 0x28d0, 0x28d8, 0x2048, 0x1bd0, 0x1bd0, 0x28e0, 0x28e8, 0x1bd0, 0x28f0, 0x1f68,
+ 0x28f8, 0x1bd0, 0x2900, 0x2908, 0x2910, 0x1bd0, 0x1bd0, 0x2918, 0x2048, 0x1bd0, 0x1bd0, 0x2920, 0x2928, 0x2930, 0x2938, 0x2940,
+ 0x1bd0, 0x1c78, 0x2948, 0x2950, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x2958, 0x2960, 0x2968, 0x1bd0, 0x1bd0, 0x2970, 0x2978, 0x1f68,
+ 0x2980, 0x1c08, 0x1c10, 0x1c80, 0x2988, 0x2990, 0x2998, 0x29a0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bd0, 0x1bd0, 0x1bd0, 0x29a8, 0x29b0, 0x1f68, 0x1bb0, 0x1bb0,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bd0, 0x1bd0, 0x29b8, 0x29c0, 0x29c8, 0x29d0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x29d8, 0x29e0, 0x1f68, 0x1bb0, 0x1bb0, 0x1bd0, 0x1bd0, 0x29e8, 0x29f0, 0x1f68, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x29f8, 0x2a00, 0x2a08, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x19b0, 0x19b0, 0x19c0, 0x19c0, 0x1e08, 0x2a10,
+ 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bd0, 0x1bd0, 0x1bd0, 0x28f0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1fd8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x21e0, 0x21e0, 0x21e0, 0x21e0, 0x21e0, 0x21e0, 0x2a18, 0x2a20, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2600, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1fa0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2388, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x28f0, 0x1bd0, 0x1fa0, 0x2570, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bd0, 0x1fc0, 0x2a28,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x2a30, 0x2a38, 0x2a40, 0x2a48, 0x2a50, 0x1bd0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1fc8, 0x2a58, 0x2a60, 0x2a68, 0x28d8, 0x2a70, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x2a78, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2420, 0x1e20, 0x28f0, 0x2a80, 0x2a88, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2240, 0x2a90,
+ 0x2240, 0x2240, 0x2a98, 0x2240, 0x2240, 0x2240, 0x2aa0, 0x2aa8, 0x2ab0, 0x2240, 0x2ab8, 0x2240, 0x2240, 0x2240, 0x2ac0, 0x1bb0,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2ac8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2278, 0x2718, 0x2ad0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x19b0, 0x2ad8, 0x19c0, 0x2ae0, 0x2ae8, 0x2af0, 0x20e8, 0x19b0, 0x2af8, 0x2b00, 0x2b08, 0x2b10, 0x2b18, 0x19b0, 0x2ad8, 0x19c0,
+ 0x2b20, 0x2b28, 0x19c0, 0x2b30, 0x2b38, 0x2b40, 0x2b48, 0x19b0, 0x2b50, 0x19c0, 0x19b0, 0x2ad8, 0x19c0, 0x2ae0, 0x2ae8, 0x19c0,
+ 0x20e8, 0x19b0, 0x2af8, 0x2b48, 0x19b0, 0x2b50, 0x19c0, 0x19b0, 0x2ad8, 0x19c0, 0x2b58, 0x19b0, 0x2b60, 0x2b68, 0x2b70, 0x2b78,
+ 0x19c0, 0x2b80, 0x19b0, 0x2b88, 0x2b90, 0x2b98, 0x2ba0, 0x19c0, 0x2ba8, 0x19b0, 0x2bb0, 0x19c0, 0x2bb8, 0x2bc0, 0x2bc0, 0x2bc0,
+ 0x1a68, 0x1a68, 0x1a68, 0x2bc8, 0x1a68, 0x1a68, 0x2bd0, 0x2bd8, 0x2be0, 0x2be8, 0x1ad8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x1af0, 0x2bf0, 0x2bf8, 0x1bb0, 0x1bb0,
+ 0x2c00, 0x1b18, 0x2c08, 0x2c10, 0x2c18, 0x2c20, 0x2c28, 0x2c30, 0x2c38, 0x2c40, 0x2c48, 0x2c40, 0x1bb0, 0x1bb0, 0x1bb0, 0x2c50,
+ 0x1fe8, 0x1fe8, 0x23d8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x23c8, 0x2c58, 0x2c60, 0x2c60, 0x2c60, 0x1fe8, 0x23d0,
+ 0x2c68, 0x2240, 0x2460, 0x2240, 0x2240, 0x2240, 0x2c70, 0x2240, 0x2240, 0x2c78, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x2c80, 0x2240,
+ 0x2c88, 0x2240, 0x2240, 0x2c78, 0x2ac0, 0x2c90, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2c98,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x23c0, 0x1fe8, 0x1fe8, 0x2ca0, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2740, 0x2ca8, 0x23c8,
+ 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x23c8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2cb0, 0x1bb0, 0x1bb0,
+ 0x23d8, 0x1fe8, 0x1fe8, 0x1fe8, 0x2cb8, 0x1ee8, 0x1fe8, 0x1fe8, 0x2cb8, 0x1fe8, 0x2cc0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bb0, 0x2cc8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x2cb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x2740, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2388, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1fc8, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1fc0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0,
+ 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x1bd0, 0x2a78, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1bd0, 0x1fc0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x2cd0, 0x1bb0, 0x2cd8, 0x2cd8, 0x2cd8, 0x2cd8, 0x2cd8, 0x2cd8, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0, 0x1bb0,
+ 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1a68, 0x1bb0,
+ 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2618, 0x2ce0,
+ 0x0101, 0x0101, 0x0101, 0x0101, 0x0201, 0x0203, 0x0304, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0303, 0x0203,
+ 0x0605, 0x0706, 0x0708, 0x0606, 0x0a09, 0x0b06, 0x0d0c, 0x0c0c, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x060c, 0x0f0f, 0x060f,
+ 0x1006, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x0910, 0x0a06, 0x1211,
+ 0x1311, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0913, 0x0a0f, 0x010f,
+ 0x0101, 0x0101, 0x0301, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101, 0x0101,
+ 0x0614, 0x0808, 0x0808, 0x0615, 0x1511, 0x1716, 0x180f, 0x1115, 0x1a19, 0x1b1b, 0x1311, 0x0606, 0x1b11, 0x1c16, 0x1d1d, 0x061d,
+ 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x0f10, 0x1010, 0x1010, 0x1010, 0x1310,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0f13, 0x1313, 0x1313, 0x1313, 0x1313,
+ 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1013, 0x1013, 0x1013, 0x1013,
+ 0x1013, 0x1013, 0x1013, 0x1013, 0x1313, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1010, 0x1013, 0x1013, 0x1313,
+ 0x1013, 0x1310, 0x1310, 0x1010, 0x1013, 0x1010, 0x1313, 0x1010, 0x1010, 0x1013, 0x1310, 0x1010, 0x1310, 0x1313, 0x1010, 0x1013,
+ 0x1310, 0x1310, 0x1310, 0x1010, 0x1013, 0x1313, 0x1310, 0x1010, 0x1013, 0x1010, 0x1013, 0x1013, 0x1310, 0x1613, 0x1310, 0x1313,
+ 0x1616, 0x1616, 0x1e10, 0x1013, 0x131e, 0x1e10, 0x1013, 0x1013, 0x1013, 0x1013, 0x1013, 0x1013, 0x1013, 0x1013, 0x1313, 0x1310,
+ 0x1013, 0x131e, 0x1310, 0x1010, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1313, 0x1313, 0x1313, 0x1010, 0x1013, 0x1310,
+ 0x1013, 0x1013, 0x1010, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1313, 0x1313, 0x1316, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313,
+ 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x201f, 0x1f20, 0x1f1f, 0x1f1f, 0x1f1f, 0x1111, 0x1111, 0x2020, 0x2020, 0x2020, 0x2020, 0x2020,
+ 0x1f1f, 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x1f1f, 0x1f1f, 0x111f, 0x1111, 0x1111, 0x1111, 0x1120, 0x111f,
+ 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x1111, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121,
+ 0x1310, 0x1310, 0x1120, 0x1310, 0x0000, 0x131f, 0x1313, 0x1006, 0x0000, 0x0000, 0x1111, 0x0610, 0x1010, 0x0010, 0x0010, 0x1010,
+ 0x1013, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1000, 0x1010, 0x1010, 0x1010, 0x1010, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1013, 0x1313, 0x1010, 0x1310, 0x1313, 0x1310, 0x1310, 0x1310, 0x1310,
+ 0x1313, 0x1313, 0x1310, 0x100f, 0x1013, 0x1310, 0x1013, 0x1010, 0x1310, 0x2122, 0x2121, 0x2121, 0x2323, 0x1310, 0x1310, 0x1310,
+ 0x1010, 0x1013, 0x1013, 0x1013, 0x1013, 0x1013, 0x1013, 0x1313, 0x1000, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010,
+ 0x1010, 0x1010, 0x1010, 0x0010, 0x1f00, 0x2424, 0x2424, 0x2424, 0x1300, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x2400, 0x0025, 0x1500, 0x0815, 0x2100, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121,
+ 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2126, 0x2127, 0x2721, 0x2121, 0x2127, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x0028, 0x0000, 0x0000,
+ 0x2828, 0x2728, 0x0027, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2929, 0x2929, 0x2929, 0x0f0f, 0x072a, 0x2b07, 0x2c0c, 0x1515,
+ 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2c21, 0x002d, 0x2c2c, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e,
+ 0x2e2f, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x212e, 0x2121, 0x2121, 0x3030, 0x3030, 0x3030, 0x3030, 0x3030, 0x3107, 0x2c31, 0x2e2e,
+ 0x2e21, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2c, 0x2121, 0x2121, 0x2121, 0x2921, 0x2115,
+ 0x2121, 0x2121, 0x2f21, 0x212f, 0x1521, 0x2121, 0x2121, 0x2e2e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x2e2e, 0x322e, 0x2e32,
+ 0x2c2c, 0x2c2c, 0x2c2c, 0x2c2c, 0x2c2c, 0x2c2c, 0x2c2c, 0x2d00, 0x212e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e,
+ 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x0021, 0x2e00, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121,
+ 0x2e21, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3333, 0x3333, 0x3333, 0x3333, 0x3333, 0x2828, 0x2828, 0x2828,
+ 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2128, 0x2121, 0x2121, 0x2121, 0x2121, 0x3434, 0x0615, 0x0606, 0x0034, 0x0000, 0x0000,
+ 0x2828, 0x2828, 0x2828, 0x2121, 0x2121, 0x2134, 0x2121, 0x2121, 0x2121, 0x2121, 0x2134, 0x2121, 0x2134, 0x2121, 0x2121, 0x0000,
+ 0x2727, 0x2727, 0x2727, 0x2727, 0x2727, 0x2727, 0x2727, 0x0027, 0x2828, 0x2828, 0x2828, 0x2828, 0x2128, 0x2121, 0x0000, 0x0027,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2e2e, 0x2e2e, 0x002e, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x2100, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x3521, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3521, 0x1621, 0x3535,
+ 0x2135, 0x2121, 0x2121, 0x2121, 0x3521, 0x3535, 0x2135, 0x3535, 0x2116, 0x2121, 0x2121, 0x2121, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x2121, 0x2424, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x1f24, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x2116, 0x3535, 0x1600, 0x1616, 0x1616, 0x1616, 0x0016, 0x1600, 0x0016, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x1616, 0x1616, 0x0016, 0x0016, 0x0000, 0x1616, 0x1616, 0x0000, 0x1621, 0x3535,
+ 0x2135, 0x2121, 0x0021, 0x3500, 0x0035, 0x3500, 0x2135, 0x0016, 0x0000, 0x0000, 0x0000, 0x3500, 0x0000, 0x0000, 0x1616, 0x1600,
+ 0x1616, 0x2121, 0x0000, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x1616, 0x0808, 0x3737, 0x3737, 0x3737, 0x0822, 0x0000, 0x0000,
+ 0x2100, 0x3521, 0x1600, 0x1616, 0x1616, 0x0016, 0x0000, 0x1600, 0x0016, 0x1616, 0x1600, 0x0016, 0x1616, 0x0000, 0x0021, 0x3535,
+ 0x2135, 0x0021, 0x0000, 0x2100, 0x0021, 0x2100, 0x2121, 0x0000, 0x2100, 0x0000, 0x0000, 0x0000, 0x1600, 0x1616, 0x0016, 0x0016,
+ 0x0000, 0x0000, 0x0000, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x2121, 0x1616, 0x2116, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2100, 0x3521, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x0016, 0x1616, 0x1600, 0x1616, 0x1616, 0x0000, 0x1621, 0x3535, 0x2135, 0x2121, 0x2121, 0x2100, 0x3521, 0x3500, 0x2135, 0x0000,
+ 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0824, 0x0000, 0x0000, 0x0000, 0x1600, 0x0000, 0x0000, 0x0000,
+ 0x2100, 0x3535, 0x1600, 0x1616, 0x1616, 0x1616, 0x0016, 0x1600, 0x0016, 0x1616, 0x1600, 0x1616, 0x1616, 0x0000, 0x1621, 0x2135,
+ 0x2135, 0x2121, 0x0021, 0x3500, 0x0035, 0x3500, 0x2135, 0x0000, 0x0000, 0x0000, 0x0000, 0x3521, 0x0000, 0x0000, 0x1616, 0x1600,
+ 0x1622, 0x3737, 0x3737, 0x3737, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1621, 0x1600, 0x1616, 0x1616, 0x0016, 0x0000, 0x1616,
+ 0x0016, 0x1616, 0x1616, 0x0000, 0x1600, 0x0016, 0x0016, 0x1616, 0x0000, 0x1600, 0x0016, 0x0000, 0x1616, 0x0016, 0x0000, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x3535, 0x3521, 0x0035, 0x0000, 0x3535, 0x0035, 0x3535, 0x2135, 0x0000,
+ 0x0016, 0x0000, 0x0000, 0x3500, 0x0000, 0x0000, 0x0000, 0x0000, 0x3737, 0x1537, 0x1515, 0x1515, 0x0815, 0x0015, 0x0000, 0x0000,
+ 0x3521, 0x3535, 0x1600, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x0016, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x1600, 0x2121, 0x3521, 0x3535, 0x0035, 0x2121, 0x0021, 0x2121, 0x2121, 0x0000,
+ 0x0000, 0x0000, 0x2100, 0x0021, 0x1616, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1d1d, 0x1d1d, 0x1d1d, 0x221d,
+ 0x2100, 0x3535, 0x1600, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1616, 0x0000, 0x1621, 0x3835,
+ 0x3535, 0x3535, 0x0035, 0x3538, 0x0035, 0x3535, 0x2121, 0x0000, 0x0000, 0x0000, 0x3500, 0x0035, 0x0000, 0x0000, 0x0000, 0x0016,
+ 0x1600, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x1600, 0x3535,
+ 0x2135, 0x2121, 0x0021, 0x3535, 0x0035, 0x3535, 0x2135, 0x0016, 0x0000, 0x0000, 0x0000, 0x3500, 0x0000, 0x0000, 0x0000, 0x1600,
+ 0x3737, 0x3737, 0x3737, 0x0000, 0x2200, 0x1616, 0x1616, 0x1616, 0x0000, 0x3535, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1600, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x0021, 0x0000, 0x3500, 0x3535, 0x2121, 0x0021, 0x0021, 0x3535, 0x3535, 0x3535, 0x3535,
+ 0x0000, 0x3535, 0x0024, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x2116, 0x1616, 0x2121, 0x2121, 0x2121, 0x0021, 0x0000, 0x0800, 0x1616, 0x1616, 0x1616, 0x211f, 0x2121, 0x2121, 0x2121, 0x2421,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x2424, 0x0000, 0x0000, 0x1600, 0x0016, 0x0016, 0x1600, 0x0016, 0x0016, 0x1600, 0x0000,
+ 0x0000, 0x0000, 0x1616, 0x1616, 0x1600, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1600, 0x1600, 0x0000, 0x1616, 0x1600, 0x1616,
+ 0x2116, 0x1616, 0x2121, 0x2121, 0x2121, 0x2100, 0x1621, 0x0000, 0x1616, 0x1616, 0x0016, 0x001f, 0x2121, 0x2121, 0x2121, 0x0000,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0000, 0x1616, 0x1616, 0x2216, 0x2222, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424,
+ 0x2424, 0x2224, 0x2224, 0x2222, 0x2121, 0x2222, 0x2222, 0x2222, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x3737, 0x3737, 0x3737,
+ 0x3737, 0x3737, 0x2122, 0x2122, 0x2122, 0x0a09, 0x0a09, 0x3535, 0x1616, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x2100, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x3521,
+ 0x2121, 0x2121, 0x2421, 0x2121, 0x1616, 0x1616, 0x2116, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2100, 0x2121, 0x2121, 0x2121,
+ 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x0021, 0x2222, 0x2222, 0x2222, 0x2222, 0x2221, 0x2222, 0x2222, 0x0022, 0x2222,
+ 0x2424, 0x2424, 0x2224, 0x2222, 0x2422, 0x0024, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3516, 0x2135, 0x2121,
+ 0x3521, 0x2121, 0x2121, 0x2121, 0x2135, 0x3521, 0x2135, 0x1621, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x2424, 0x2424, 0x2424,
+ 0x1616, 0x1616, 0x1616, 0x3535, 0x2121, 0x1616, 0x1616, 0x2121, 0x1621, 0x3535, 0x1635, 0x3516, 0x3535, 0x3535, 0x3535, 0x1616,
+ 0x2116, 0x2121, 0x1621, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3521, 0x2135, 0x3521, 0x3535, 0x3535, 0x2135, 0x3516,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x3535, 0x2135, 0x2222, 0x1010, 0x1010, 0x1010, 0x1000, 0x0000, 0x0000, 0x1000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2416, 0x161f, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x1616, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x0016, 0x0016, 0x1616, 0x1616, 0x0000, 0x0016, 0x1616, 0x1616, 0x0000, 0x1616, 0x1616, 0x1616, 0x0016,
+ 0x0016, 0x1616, 0x1616, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x2100, 0x2121, 0x2424, 0x2424, 0x2424, 0x2424, 0x3724, 0x3737, 0x3737, 0x3737,
+ 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x0037, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x0000, 0x0000,
+ 0x1010, 0x1010, 0x1010, 0x0000, 0x1313, 0x1313, 0x1313, 0x0000, 0x1625, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2416, 0x1624, 0x1605, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0916, 0x000a, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2416, 0x2424, 0x3939,
+ 0x1639, 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616,
+ 0x1616, 0x2121, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x2121, 0x2421, 0x0024, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x2121, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0016, 0x2121, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x2121, 0x2135, 0x2121, 0x2121, 0x2121, 0x3535, 0x3535, 0x3535, 0x3535, 0x3521, 0x2135, 0x2121, 0x2121, 0x2121,
+ 0x2121, 0x2121, 0x2424, 0x1f24, 0x2424, 0x0824, 0x2116, 0x0000, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0000, 0x0000, 0x0000,
+ 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x0000, 0x0000, 0x0000, 0x0606, 0x0606, 0x0606, 0x0625, 0x0606, 0x2106, 0x2121, 0x0018,
+ 0x1616, 0x1f16, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x2116, 0x0016, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x2121, 0x3521, 0x3535, 0x2135, 0x3521, 0x3535, 0x0000, 0x0000,
+ 0x3535, 0x3521, 0x3535, 0x3535, 0x2135, 0x2121, 0x0000, 0x0000, 0x0015, 0x0000, 0x0606, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x1616, 0x1616, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x0000,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0037, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515,
+ 0x1616, 0x1616, 0x1616, 0x2116, 0x3521, 0x2135, 0x0000, 0x2424, 0x1616, 0x1616, 0x3516, 0x3521, 0x2121, 0x2121, 0x2121, 0x0021,
+ 0x3521, 0x3521, 0x2135, 0x2121, 0x2121, 0x2121, 0x3521, 0x3535, 0x3535, 0x2135, 0x2121, 0x2121, 0x2121, 0x2121, 0x0021, 0x2100,
+ 0x2424, 0x2424, 0x2424, 0x1f24, 0x2424, 0x2424, 0x2424, 0x0000, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x0023,
+ 0x2121, 0x2121, 0x1635, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3521, 0x2121, 0x2121, 0x3521, 0x3521, 0x3535,
+ 0x3535, 0x3521, 0x1635, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x2224, 0x2222, 0x2222, 0x2222, 0x2222, 0x2122, 0x2121, 0x2121,
+ 0x2121, 0x2121, 0x2222, 0x2222, 0x2222, 0x2222, 0x0022, 0x0000, 0x2121, 0x1635, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x3516, 0x2121, 0x2121, 0x3535, 0x2121, 0x2135, 0x2121, 0x1616, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x3521, 0x2121, 0x3535, 0x2135, 0x2135, 0x2121, 0x3535, 0x0000, 0x0000, 0x0000, 0x0000, 0x2424, 0x2424,
+ 0x1616, 0x1616, 0x3535, 0x3535, 0x3535, 0x3535, 0x2121, 0x2121, 0x2121, 0x2121, 0x3535, 0x2121, 0x0000, 0x2400, 0x2424, 0x2424,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0000, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1f1f, 0x1f1f, 0x1f1f, 0x2424,
+ 0x2424, 0x2424, 0x2424, 0x2424, 0x0000, 0x0000, 0x0000, 0x0000, 0x2121, 0x2421, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121,
+ 0x3521, 0x2121, 0x2121, 0x2121, 0x1621, 0x1616, 0x2116, 0x1616, 0x1616, 0x3535, 0x1621, 0x0016, 0x2121, 0x0000, 0x0000, 0x0000,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f,
+ 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x131f, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x131f, 0x1313, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1f13, 0x1f1f, 0x1f1f, 0x2121, 0x2121, 0x2121, 0x0000, 0x0000, 0x0000, 0x2121, 0x2121,
+ 0x1310, 0x1310, 0x1310, 0x1313, 0x1313, 0x1313, 0x1313, 0x1310, 0x1313, 0x1313, 0x1313, 0x1313, 0x1010, 0x1010, 0x1010, 0x1010,
+ 0x1313, 0x1313, 0x1313, 0x0000, 0x1010, 0x1010, 0x1010, 0x0000, 0x1313, 0x1313, 0x1313, 0x1313, 0x1000, 0x1000, 0x1000, 0x1000,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0000, 0x1313, 0x1313, 0x1313, 0x1313, 0x1e1e, 0x1e1e, 0x1e1e, 0x1e1e,
+ 0x1313, 0x1313, 0x0013, 0x1313, 0x1010, 0x1010, 0x111e, 0x1113, 0x1111, 0x1313, 0x0013, 0x1313, 0x1010, 0x1010, 0x111e, 0x1111,
+ 0x1313, 0x1313, 0x0000, 0x1313, 0x1010, 0x1010, 0x1100, 0x1111, 0x1313, 0x1313, 0x1313, 0x1313, 0x1010, 0x1010, 0x1110, 0x1111,
+ 0x0000, 0x1313, 0x0013, 0x1313, 0x1010, 0x1010, 0x111e, 0x0011, 0x0505, 0x0505, 0x0505, 0x0505, 0x0505, 0x1805, 0x1818, 0x3b3a,
+ 0x2525, 0x2525, 0x2525, 0x0606, 0x1c17, 0x1709, 0x1c17, 0x1709, 0x0606, 0x0606, 0x0606, 0x0606, 0x3d3c, 0x3f3e, 0x4140, 0x1442,
+ 0x0707, 0x0707, 0x0607, 0x0606, 0x1706, 0x061c, 0x0606, 0x1206, 0x0612, 0x0606, 0x0943, 0x060a, 0x0606, 0x0606, 0x0606, 0x0606,
+ 0x0606, 0x060f, 0x0612, 0x0606, 0x0606, 0x0606, 0x0606, 0x0506, 0x1818, 0x1818, 0x0018, 0x4544, 0x4746, 0x1818, 0x1818, 0x1818,
+ 0x1f1b, 0x0000, 0x1b1b, 0x1b1b, 0x1b1b, 0x0b0b, 0x090f, 0x1f0a, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x0b0b, 0x090f, 0x000a,
+ 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x001f, 0x0000, 0x0808, 0x0808, 0x0808, 0x0808, 0x0808, 0x0808, 0x0808, 0x0808,
+ 0x0808, 0x0808, 0x0808, 0x0808, 0x0808, 0x0808, 0x0808, 0x0008, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2321, 0x2323,
+ 0x2123, 0x2323, 0x2123, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1515, 0x1510, 0x1515, 0x1015, 0x1515, 0x1013, 0x1010, 0x1313, 0x1010, 0x1310, 0x1015, 0x1515, 0x100f, 0x1010, 0x1010, 0x1515,
+ 0x1515, 0x1515, 0x1510, 0x1510, 0x1510, 0x1010, 0x1010, 0x1319, 0x1010, 0x1010, 0x1613, 0x1616, 0x1316, 0x1515, 0x1313, 0x1010,
+ 0x0f0f, 0x0f0f, 0x100f, 0x1313, 0x1313, 0x0f15, 0x1515, 0x2213, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d,
+ 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x1039, 0x3913, 0x3939, 0x1d39, 0x1515, 0x0000, 0x0000,
+ 0x0f0f, 0x0f0f, 0x150f, 0x1515, 0x1515, 0x0f0f, 0x1515, 0x1515, 0x150f, 0x0f15, 0x1515, 0x150f, 0x1515, 0x1515, 0x1515, 0x150f,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0f0f, 0x1515, 0x150f, 0x150f, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515,
+ 0x1515, 0x1515, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f,
+ 0x0f0f, 0x1a0b, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x1515, 0x1515, 0x1515, 0x1515, 0x0a09, 0x0a09, 0x1515, 0x1515,
+ 0x0f0f, 0x1515, 0x1515, 0x1515, 0x0915, 0x150a, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222,
+ 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1522, 0x150f, 0x1515,
+ 0x1515, 0x1515, 0x2215, 0x1515, 0x1515, 0x0f15, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0f0f, 0x0f0f, 0x0f0f, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0015, 0x0000, 0x0000, 0x1515, 0x1515, 0x1515, 0x0015, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x2222, 0x2222,
+ 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1d1d, 0x1d1d, 0x1d1d, 0x1515, 0x1515, 0x1515, 0x0f15, 0x1515, 0x1515, 0x1515, 0x1515,
+ 0x0f15, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0f15, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1522, 0x1515,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d,
+ 0x1d1d, 0x1d1d, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0f0f, 0x0f0f, 0x090f, 0x0f0a, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f,
+ 0x0f0f, 0x0f0f, 0x0f0f, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0f0f, 0x090f, 0x090a, 0x090a, 0x090a, 0x090a, 0x090a, 0x090a,
+ 0x090a, 0x090a, 0x090a, 0x090a, 0x0f0a, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0a09, 0x0a09, 0x0f0f, 0x0f0f,
+ 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0f0f, 0x0a09, 0x0f0f, 0x0f0f, 0x0f0f, 0x150f, 0x0f15, 0x0f0f, 0x0f0f, 0x150f, 0x1515,
+ 0x1515, 0x1515, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x1500, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0015, 0x1515, 0x1515, 0x1515,
+ 0x1515, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1515, 0x1515,
+ 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x0010, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0013,
+ 0x1310, 0x1010, 0x1310, 0x1013, 0x1013, 0x1013, 0x1013, 0x1010, 0x1310, 0x1310, 0x1013, 0x1313, 0x1313, 0x1313, 0x1f1f, 0x1010,
+ 0x1310, 0x1310, 0x1513, 0x1515, 0x1515, 0x1015, 0x1013, 0x2113, 0x2121, 0x1310, 0x0000, 0x0000, 0x0600, 0x0606, 0x1d06, 0x0606,
+ 0x1313, 0x1313, 0x1313, 0x1300, 0x0000, 0x0000, 0x1300, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x0000, 0x1f00,
+ 0x0024, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2100, 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x1616, 0x1616, 0x0016, 0x0606, 0x1c17, 0x1c17, 0x0606, 0x1706, 0x061c, 0x1c17, 0x0606,
+ 0x0606, 0x0606, 0x0606, 0x2506, 0x0606, 0x0625, 0x1c17, 0x0606, 0x1c17, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0606, 0x0606, 0x2006,
+ 0x0606, 0x0606, 0x0606, 0x0606, 0x0606, 0x2525, 0x0606, 0x0606, 0x0625, 0x0009, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1500, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1515, 0x1515, 0x1515, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x0000,
+ 0x0605, 0x0606, 0x1f15, 0x3916, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x1515, 0x0a09, 0x0a09, 0x0a09, 0x0a09, 0x0925, 0x0a0a,
+ 0x3915, 0x3939, 0x3939, 0x3939, 0x3939, 0x2121, 0x2121, 0x3535, 0x1f25, 0x1f1f, 0x1f1f, 0x1515, 0x3939, 0x1f39, 0x0616, 0x1515,
+ 0x1616, 0x1616, 0x1616, 0x0016, 0x2100, 0x1121, 0x1f11, 0x161f, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0616, 0x1f1f, 0x161f,
+ 0x0000, 0x0000, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2222, 0x3737, 0x3737, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x0000, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1522, 0x0015,
+ 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x3737, 0x3737, 0x3737, 0x3737,
+ 0x1d15, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1515, 0x2215,
+ 0x1d22, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1515, 0x1515,
+ 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x0022, 0x2222, 0x2222, 0x2222, 0x1522, 0x1515, 0x2215, 0x2222, 0x2222,
+ 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1515, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1522,
+ 0x1616, 0x1616, 0x1f16, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x061f, 0x0606,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x1616, 0x0000, 0x0000, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x2116,
+ 0x2323, 0x0623, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2006, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1f1f, 0x2121,
+ 0x1616, 0x1616, 0x1616, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x2121, 0x2424, 0x2424, 0x2424, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1111, 0x1111, 0x1111, 0x2011, 0x2020, 0x2020, 0x2020, 0x2020, 0x1111, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310,
+ 0x1313, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x131f, 0x1313, 0x1313, 0x1313, 0x1013, 0x1013, 0x1013, 0x1310,
+ 0x1310, 0x1310, 0x1310, 0x1310, 0x4820, 0x1048, 0x1013, 0x1613, 0x1310, 0x1310, 0x1313, 0x1310, 0x1310, 0x1310, 0x1310, 0x1310,
+ 0x1310, 0x1310, 0x1310, 0x1310, 0x1310, 0x1010, 0x1010, 0x0000, 0x1010, 0x1010, 0x1310, 0x1310, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x1600, 0x1f1f, 0x1613, 0x1616, 0x1616, 0x1616, 0x1621, 0x1616, 0x1621, 0x1616, 0x2116, 0x1616, 0x1616,
+ 0x1616, 0x3516, 0x2135, 0x3521, 0x1515, 0x1515, 0x0000, 0x0000, 0x3737, 0x3737, 0x3737, 0x2222, 0x1908, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x0606, 0x0606, 0x0000, 0x0000, 0x0000, 0x0000, 0x3535, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000, 0x2424,
+ 0x2121, 0x1616, 0x1616, 0x1616, 0x2424, 0x1624, 0x1624, 0x0000, 0x1616, 0x1616, 0x1616, 0x2121, 0x2121, 0x2121, 0x2121, 0x2424,
+ 0x1616, 0x1616, 0x1616, 0x2116, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x3535, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2400,
+ 0x1616, 0x2116, 0x3535, 0x2121, 0x2121, 0x3535, 0x3521, 0x3535, 0x2435, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424, 0x1f00,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0000, 0x0000, 0x2424, 0x1616, 0x1616, 0x2116, 0x161f, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x1616, 0x1616, 0x0016, 0x1616, 0x1616, 0x1616, 0x1616, 0x2116, 0x2121, 0x2121, 0x3521,
+ 0x2135, 0x3521, 0x2135, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x2116, 0x1616, 0x1616, 0x1616, 0x1616, 0x3521, 0x0000,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0000, 0x2424, 0x2424, 0x161f, 0x1616, 0x1616, 0x2216, 0x2222, 0x3516, 0x3521, 0x1616,
+ 0x1621, 0x2121, 0x1621, 0x2116, 0x1621, 0x1616, 0x1616, 0x2121, 0x2116, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1600, 0x1f16, 0x2424, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3516, 0x2121, 0x3535,
+ 0x2424, 0x1f16, 0x351f, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000, 0x1600, 0x1616, 0x1616, 0x0016, 0x1600, 0x1616, 0x1616, 0x0016,
+ 0x1600, 0x1616, 0x1616, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x4813, 0x1f1f, 0x1f1f,
+ 0x1313, 0x1313, 0x1313, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x3516, 0x2135, 0x3535, 0x3521, 0x2435, 0x2135, 0x0000,
+ 0x1616, 0x1616, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x1600, 0x1616, 0x1616,
+ 0x4949, 0x4949, 0x4949, 0x4949, 0x4949, 0x4949, 0x4949, 0x4949, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a,
+ 0x1313, 0x1313, 0x1313, 0x0013, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1300, 0x1313, 0x1313, 0x0000, 0x0000, 0x2800, 0x2821,
+ 0x2828, 0x2828, 0x2828, 0x2828, 0x0b28, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x0028, 0x2828, 0x2828, 0x0028, 0x0028,
+ 0x2828, 0x2800, 0x0028, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2e2e, 0x4b4b, 0x4b4b, 0x4b4b, 0x4b4b, 0x4b4b, 0x4b4b, 0x4b4b,
+ 0x4b4b, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2e00, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e,
+ 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x090a, 0x0000, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e,
+ 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x0000, 0x0000, 0x0000, 0x0000, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x152b, 0x0000,
+ 0x0606, 0x0606, 0x0606, 0x0906, 0x060a, 0x0000, 0x0000, 0x0000, 0x2506, 0x1225, 0x0912, 0x090a, 0x090a, 0x090a, 0x090a, 0x090a,
+ 0x090a, 0x090a, 0x060a, 0x0906, 0x060a, 0x0606, 0x1206, 0x1212, 0x060c, 0x000c, 0x0c06, 0x0606, 0x0925, 0x090a, 0x090a, 0x070a,
+ 0x0606, 0x0d0b, 0x0f0f, 0x000f, 0x0806, 0x0607, 0x0000, 0x0000, 0x2e2e, 0x2e2e, 0x002e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e,
+ 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x002e, 0x1800, 0x0600, 0x0706, 0x0708, 0x0606, 0x0a09, 0x0b06, 0x0d0c, 0x0c0c,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0913, 0x0a0f, 0x090f, 0x060a, 0x0a09, 0x0606, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x161f, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1f1f,
+ 0x0000, 0x1616, 0x1616, 0x1616, 0x0000, 0x1616, 0x1616, 0x1616, 0x0000, 0x1616, 0x1616, 0x1616, 0x0000, 0x1616, 0x0016, 0x0000,
+ 0x0808, 0x110f, 0x0815, 0x0008, 0x0f15, 0x0f0f, 0x150f, 0x0015, 0x0000, 0x0000, 0x0000, 0x0000, 0x4c00, 0x4c4c, 0x1515, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x1616, 0x1600,
+ 0x0624, 0x0024, 0x0000, 0x3700, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737,
+ 0x3737, 0x3737, 0x0000, 0x2200, 0x2222, 0x2222, 0x2222, 0x2222, 0x4d4d, 0x4d4d, 0x4d4d, 0x4d4d, 0x4d4d, 0x4d4d, 0x4d4d, 0x4d4d,
+ 0x4d4d, 0x4d4d, 0x1d4d, 0x1d1d, 0x151d, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1d1d, 0x0015, 0x0000,
+ 0x0015, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2122, 0x0000,
+ 0x1b21, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x0000, 0x0000,
+ 0x3737, 0x3737, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3916, 0x1616, 0x1616, 0x1616, 0x1616, 0x0039, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x2121, 0x2121, 0x0021, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2400,
+ 0x1616, 0x1616, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x3924, 0x3939, 0x3939, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1010, 0x1010, 0x1010, 0x1010, 0x1313, 0x1313, 0x1313, 0x1313, 0x1616, 0x1616, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2400,
+ 0x2828, 0x2828, 0x2828, 0x0000, 0x0028, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2800, 0x0028, 0x0000, 0x0028, 0x2800,
+ 0x2828, 0x2828, 0x2828, 0x2700, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x2828, 0x2828, 0x2828, 0x4f28, 0x4e4f, 0x4e4e, 0x4e4e, 0x4e4e,
+ 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x0028, 0x0000, 0x0000, 0x0000, 0x4e00, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e,
+ 0x2828, 0x0028, 0x2828, 0x0000, 0x0000, 0x4e00, 0x4e4e, 0x4e4e, 0x2828, 0x2828, 0x2828, 0x4e4e, 0x4e4e, 0x4e4e, 0x0000, 0x0600,
+ 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x0000, 0x0000, 0x2700, 0x2828, 0x2828, 0x2828, 0x2828, 0x0000, 0x0000, 0x4e4e, 0x2828,
+ 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x0000, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e,
+ 0x2128, 0x2121, 0x2100, 0x0021, 0x0000, 0x0000, 0x2121, 0x2121, 0x2828, 0x2828, 0x2800, 0x2828, 0x2800, 0x2828, 0x2828, 0x2828,
+ 0x2828, 0x2828, 0x0000, 0x0000, 0x2121, 0x0021, 0x0000, 0x2100, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2727, 0x2727, 0x2727, 0x2727, 0x0027, 0x0000, 0x0000, 0x0000, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x4e28, 0x274e,
+ 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x2828, 0x4e28, 0x4e4e, 0x2828, 0x2828, 0x2828, 0x2828, 0x284f, 0x2828, 0x2828, 0x2828,
+ 0x2828, 0x2828, 0x2128, 0x0021, 0x0000, 0x4e00, 0x4e4e, 0x4e4e, 0x2727, 0x2727, 0x2727, 0x0027, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2828, 0x2828, 0x2828, 0x0000, 0x0600, 0x0606, 0x0606, 0x0606, 0x2828, 0x2828, 0x2828, 0x0000, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e,
+ 0x2828, 0x0028, 0x0000, 0x0000, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x2828, 0x0000, 0x0000, 0x0000, 0x2700, 0x2727, 0x0027, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x4e00, 0x4e4e, 0x4e4e, 0x4e4e, 0x2828, 0x2828, 0x2828, 0x2828, 0x0028, 0x0000, 0x0000, 0x0000,
+ 0x5050, 0x5050, 0x5050, 0x5050, 0x5050, 0x5050, 0x5050, 0x5050, 0x5050, 0x0050, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x5151, 0x5151, 0x5151, 0x5151, 0x5151, 0x5151, 0x5151, 0x5151, 0x5151, 0x0051, 0x0000, 0x0000, 0x0000, 0x4e4e, 0x4e4e, 0x4e4e,
+ 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x5252, 0x0052,
+ 0x2135, 0x1635, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2121, 0x2121, 0x2121, 0x2121,
+ 0x2121, 0x2121, 0x2121, 0x2421, 0x2424, 0x2424, 0x2424, 0x0000, 0x0000, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d, 0x1d1d,
+ 0x1d1d, 0x1d1d, 0x1d1d, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2100,
+ 0x3535, 0x2135, 0x2121, 0x3521, 0x2135, 0x2421, 0x3a24, 0x2424, 0x2424, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x0016, 0x0000, 0x0000, 0x0000, 0x2121, 0x1621, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x2116, 0x2121, 0x2121, 0x2135, 0x2121, 0x2121, 0x2121, 0x0021, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636,
+ 0x2424, 0x2424, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x2116, 0x2424, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x3516, 0x3535, 0x2121, 0x2121, 0x2121, 0x2121, 0x3521, 0x1635, 0x1616, 0x2416, 0x2424, 0x2424, 0x2121, 0x2421, 0x0000,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x2416, 0x2416, 0x2424, 0x3700, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737, 0x3737,
+ 0x3737, 0x3737, 0x0037, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3535, 0x2135,
+ 0x2121, 0x3535, 0x3521, 0x2121, 0x2424, 0x2424, 0x2424, 0x0000, 0x1616, 0x1616, 0x1616, 0x0016, 0x0016, 0x1616, 0x1616, 0x1600,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x2416, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2116, 0x3535, 0x2135, 0x2121, 0x2121, 0x2121, 0x0021, 0x0000, 0x0000,
+ 0x2121, 0x3535, 0x1600, 0x1616, 0x1616, 0x1616, 0x0016, 0x1600, 0x3521, 0x3535, 0x0035, 0x3500, 0x0035, 0x3500, 0x3535, 0x0000,
+ 0x0016, 0x0000, 0x0000, 0x3500, 0x0000, 0x0000, 0x1600, 0x1616, 0x1616, 0x3535, 0x0000, 0x2121, 0x2121, 0x2121, 0x0021, 0x0000,
+ 0x2121, 0x2121, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3535, 0x2135, 0x2121, 0x2121, 0x3521, 0x3521, 0x3535, 0x2135,
+ 0x3521, 0x2121, 0x1616, 0x1624, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x3516,
+ 0x3535, 0x2121, 0x2121, 0x0000, 0x3535, 0x3535, 0x2121, 0x2135, 0x2421, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424, 0x2424,
+ 0x2424, 0x2424, 0x2424, 0x2424, 0x1616, 0x1616, 0x2121, 0x0000, 0x3535, 0x2135, 0x2121, 0x2121, 0x2121, 0x3521, 0x2135, 0x2135,
+ 0x2421, 0x2424, 0x0016, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x2116, 0x2135, 0x3535,
+ 0x2121, 0x2121, 0x2121, 0x2135, 0x0000, 0x0000, 0x0000, 0x0000, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x2100, 0x2121,
+ 0x3535, 0x2121, 0x2121, 0x2135, 0x2121, 0x2121, 0x0000, 0x0000, 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x3737, 0x2424, 0x2224,
+ 0x3737, 0x0037, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1600, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x3939, 0x0039,
+ 0x2424, 0x2424, 0x0024, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2121, 0x2121, 0x2421, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2121, 0x2121, 0x2121, 0x2421, 0x2424, 0x2424, 0x2222, 0x2222, 0x1f1f, 0x1f1f, 0x2224, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x3636, 0x3636, 0x3636, 0x3636, 0x3636, 0x3700, 0x3737, 0x3737, 0x3737, 0x1600, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x1616,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x0000, 0x1600, 0x1616, 0x3516, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535,
+ 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x3535, 0x0035,
+ 0x2121, 0x1f21, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1f1f, 0x1616, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1616, 0x1616, 0x1616, 0x1616, 0x1616, 0x0000, 0x2122, 0x2421, 0x1818, 0x1818, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2222, 0x2222, 0x2222, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2222, 0x2222, 0x2222, 0x0022, 0x2200, 0x2222, 0x2222, 0x2222,
+ 0x2222, 0x2222, 0x3522, 0x2135, 0x2121, 0x2222, 0x3522, 0x3535, 0x3535, 0x1835, 0x1818, 0x1818, 0x1818, 0x2118, 0x2121, 0x2121,
+ 0x2121, 0x2221, 0x2122, 0x2121, 0x2121, 0x2121, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2121, 0x2121, 0x2222,
+ 0x2222, 0x2222, 0x2222, 0x2222, 0x0022, 0x0000, 0x0000, 0x0000, 0x1515, 0x2121, 0x1521, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x3737, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1313, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1313,
+ 0x1313, 0x1313, 0x0013, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1010, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0010, 0x1010, 0x0000, 0x0010, 0x1000, 0x0010, 0x1000, 0x1010, 0x0010, 0x1010,
+ 0x1010, 0x1010, 0x1010, 0x1313, 0x1313, 0x1300, 0x1300, 0x1313, 0x1313, 0x1313, 0x1300, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1010, 0x1000, 0x1010, 0x0010, 0x1000, 0x1010, 0x1010, 0x1010, 0x0010, 0x1010, 0x1010, 0x1010, 0x0010, 0x1313,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1010, 0x1000, 0x1010, 0x0010, 0x1010, 0x1010, 0x0010, 0x0010, 0x0000, 0x1010, 0x1010, 0x1010,
+ 0x0010, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1010, 0x1010,
+ 0x1010, 0x1010, 0x1010, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0000, 0x1010, 0x1010, 0x1010, 0x1010,
+ 0x5310, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0f13, 0x1313, 0x1313,
+ 0x1313, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x5310, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x0f13, 0x1313, 0x1313, 0x1313, 0x1010, 0x1010, 0x1010, 0x1010, 0x5310, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313,
+ 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x1313, 0x0f13, 0x1313, 0x1313, 0x1313, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010,
+ 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x1010, 0x5310, 0x1313, 0x1313, 0x1313, 0x1313, 0x0f13, 0x1313, 0x1313, 0x1313,
+ 0x1010, 0x1010, 0x1010, 0x1010, 0x5310, 0x1313, 0x1313, 0x1313, 0x1313, 0x0f13, 0x1313, 0x1313, 0x1313, 0x1310, 0x0000, 0x0e0e,
+ 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x0e0e, 0x2121, 0x2121, 0x2121, 0x2221, 0x2222, 0x2122, 0x2121, 0x2121,
+ 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2121, 0x2221, 0x2222, 0x2222, 0x2222, 0x2122, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222,
+ 0x2222, 0x2222, 0x2221, 0x2422, 0x2424, 0x2424, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2100, 0x2121, 0x2121,
+ 0x2828, 0x2828, 0x0028, 0x4e00, 0x4e4e, 0x4e4e, 0x4e4e, 0x4e4e, 0x2121, 0x2121, 0x2121, 0x0021, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2e2e, 0x2e2e, 0x2e00, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e00, 0x002e, 0x002e, 0x2e00, 0x2e00, 0x2e2e, 0x2e2e, 0x2e2e,
+ 0x2e2e, 0x002e, 0x2e2e, 0x2e2e, 0x2e00, 0x2e00, 0x0000, 0x0000, 0x0000, 0x002e, 0x0000, 0x2e00, 0x2e00, 0x2e00, 0x2e00, 0x2e2e,
+ 0x2e00, 0x002e, 0x002e, 0x2e00, 0x2e00, 0x2e00, 0x2e00, 0x2e00, 0x2e00, 0x002e, 0x002e, 0x2e00, 0x2e2e, 0x002e, 0x2e2e, 0x2e2e,
+ 0x2e2e, 0x002e, 0x2e2e, 0x2e2e, 0x2e00, 0x2e2e, 0x002e, 0x002e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e00, 0x2e2e, 0x2e2e,
+ 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x2e2e, 0x0000, 0x0000, 0x2e00, 0x2e2e, 0x2e00, 0x2e2e, 0x2e2e, 0x2e00, 0x2e2e, 0x2e2e,
+ 0x0f0f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0015,
+ 0x1500, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1b1b, 0x1d1b, 0x001d, 0x0000,
+ 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x1515, 0x0000, 0x0000, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x0022, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x2222, 0x0022, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x2222, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1115, 0x1111, 0x1111,
+ 0x1515, 0x1515, 0x1500, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0015, 0x0000,
+ 0x1515, 0x1515, 0x0015, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x1515, 0x0000, 0x1515, 0x1515, 0x1515, 0x1515, 0x0015, 0x0000, 0x0000, 0x0000,
+ 0x1800, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818, 0x1818,
+ 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x4a4a, 0x0000, 0xeeee, 0xeeee
+ };
+
+ private static byte[] s_pCategoriesValue = new byte[]
+ {
+ 0x1d, 0x00, 0x0e, 0x0e, 0x0e, 0x10, 0x0e, 0x0f, 0x0e, 0x11, 0x0b, 0x11, 0x18, 0x12, 0x18, 0x0a,
+ 0x1a, 0x0a, 0x14, 0x12, 0x15, 0x12, 0x19, 0x09, 0x18, 0x0c, 0x13, 0x09, 0x08, 0x08, 0x19, 0x12,
+ 0x00, 0x00, 0x1b, 0x12, 0x12, 0x12, 0x01, 0x00, 0x0b, 0x0c, 0x1c, 0x12, 0x04, 0x00, 0x16, 0x12,
+ 0x0f, 0x0e, 0x1c, 0x0a, 0x19, 0x0a, 0x0a, 0x08, 0x17, 0x12, 0x0a, 0x12, 0x02, 0x00, 0x03, 0x00,
+ 0x03, 0x12, 0x05, 0x0d, 0x1c, 0x00, 0x07, 0x0d, 0x18, 0x00, 0x13, 0x12, 0x13, 0x03, 0x18, 0x03,
+ 0x04, 0x03, 0x0f, 0x0b, 0x19, 0x04, 0x1a, 0x04, 0x18, 0x04, 0x0f, 0x04, 0x04, 0x04, 0x03, 0x04,
+ 0x08, 0x0b, 0x18, 0x0b, 0x1c, 0x04, 0x08, 0x03, 0x03, 0x03, 0x06, 0x00, 0x08, 0x00, 0x0a, 0x00,
+ 0x05, 0x00, 0x09, 0x00, 0x0f, 0x00, 0x0f, 0x03, 0x0c, 0x11, 0x0d, 0x0f, 0x0f, 0x01, 0x0f, 0x05,
+ 0x0f, 0x07, 0x0f, 0x02, 0x0f, 0x06, 0x19, 0x0c, 0x0f, 0x13, 0x0f, 0x14, 0x0f, 0x15, 0x0f, 0x16,
+ 0x1b, 0x00, 0x10, 0x00, 0x11, 0x00, 0x1b, 0x04, 0x0f, 0x12, 0x09, 0x12, 0x0a, 0x03, 0x1c, 0x03,
+ 0x00, 0x03, 0x01, 0x03, 0x0a, 0x0b, 0x19, 0x00
+ };
+ // 12:4:4 index table of the Unicode numeric data.
+ private static ushort[] s_pNumericLevel1Index = new ushort[]
+ {
+ 0x1100, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1120, 0x1130, 0x1110, 0x1140, 0x1150, 0x1160, 0x1170, 0x1180, 0x1190, 0x11a0,
+ 0x11b0, 0x1110, 0x1110, 0x11c0, 0x1110, 0x1110, 0x11d0, 0x11e0, 0x11f0, 0x1200, 0x1210, 0x1220, 0x1230, 0x1110, 0x1110, 0x1110,
+ 0x1240, 0x1250, 0x1110, 0x1110, 0x1260, 0x1110, 0x1110, 0x1270, 0x1110, 0x1110, 0x1110, 0x1110, 0x1280, 0x1110, 0x1110, 0x1110,
+ 0x1290, 0x12a0, 0x12b0, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x12c0, 0x1110, 0x12d0, 0x12e0, 0x12f0, 0x1300, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1310, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x11f0,
+ 0x1110, 0x1320, 0x1330, 0x1340, 0x1350, 0x1110, 0x1110, 0x1110, 0x1360, 0x1370, 0x1380, 0x1390, 0x13a0, 0x1110, 0x13b0, 0x1110,
+ 0x13c0, 0x13d0, 0x1300, 0x1110, 0x13e0, 0x1110, 0x13f0, 0x1400, 0x1410, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1420, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1430, 0x1440, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1450, 0x1110, 0x1110, 0x1110, 0x1460, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1470, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1480, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1490, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110, 0x1110,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14c0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14c8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14d0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14d8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14e0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14e8, 0x14f0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14f8, 0x1500, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1508, 0x1510,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x1518,
+ 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1520, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1528, 0x1530, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1538, 0x1540, 0x1540, 0x1548, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1550, 0x1558, 0x1560, 0x1568, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1570, 0x1578,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1580, 0x1588, 0x1590, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1598,
+ 0x15a0, 0x14a0, 0x15a8, 0x15b0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x15b8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x15c0, 0x14a0, 0x15c8, 0x15d0, 0x14a0, 0x14a0, 0x15c0, 0x14a0, 0x14a0, 0x15d8, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x15e0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x15e8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0,
+ 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a8,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x15f0, 0x15f8, 0x14a0, 0x14a0, 0x14a0, 0x1600, 0x14a0, 0x1608, 0x14a0, 0x1610,
+ 0x1618, 0x1620, 0x1628, 0x1630, 0x1638, 0x1640, 0x1648, 0x1650, 0x1658, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1660, 0x1668,
+ 0x14a0, 0x14a0, 0x1670, 0x14a0, 0x1678, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1680, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1688, 0x14a0, 0x1690, 0x14a0, 0x14a0, 0x1698, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x16a0,
+ 0x14a0, 0x16a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x16b0, 0x16b8, 0x16c0, 0x16c8, 0x16d0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x16d8, 0x14a0, 0x14a0, 0x16e0, 0x14a0, 0x16e8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x16a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x16f0, 0x14a0, 0x16f0, 0x14a0, 0x14a0, 0x16f8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1700,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1708, 0x1710, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1718, 0x1720, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8,
+ 0x14a0, 0x14a0, 0x14a0, 0x14b8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x1660, 0x1728,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x1730, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1738, 0x1740,
+ 0x1748, 0x1750, 0x1758, 0x1760, 0x1768, 0x1770, 0x1778, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1780, 0x1788, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x16b8, 0x1790, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1798, 0x17a0, 0x17a8, 0x17b0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x1618, 0x14a0, 0x14a0, 0x14a0,
+ 0x17b8, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x17c0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0, 0x14a0,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0c0b, 0x0000, 0x0000, 0x0d00, 0x0000, 0x0f0e, 0x0010, 0x0000, 0x0000, 0x0000, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09,
+ 0x0000, 0x0000, 0x1211, 0x0e13, 0x1410, 0x0000, 0x0000, 0x0000, 0x0000, 0x0f0e, 0x1110, 0x1312, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1615, 0x0017, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1918, 0x1b1a, 0x1a19, 0x001b,
+ 0x1615, 0x0e17, 0x100f, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x1c0f, 0x1e1d, 0x201f,
+ 0x2221, 0x2423, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0d00, 0x0c0b, 0x2625, 0x2827,
+ 0x2a29, 0x2b15, 0x2d2c, 0x2f2e, 0x3130, 0x1632, 0x0033, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3534,
+ 0x0036, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1918, 0x1b1a, 0x3837, 0x3a39, 0x3c3b, 0x0000, 0x0000, 0x0000,
+ 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x000d, 0x0000, 0x0000, 0x003d, 0x0000, 0x2625, 0x2827, 0x2a29, 0x0000, 0x0000, 0x0000,
+ 0x0d3d, 0x0c0b, 0x2625, 0x2827, 0x2a29, 0x0000, 0x0000, 0x0000, 0x3f3e, 0x4140, 0x4342, 0x4544, 0x4746, 0x1248, 0x4a49, 0x194b,
+ 0x1a19, 0x371b, 0x3938, 0x3b3a, 0x153c, 0x4d4c, 0x162e, 0x174e, 0x4f17, 0x0033, 0x3900, 0x502e, 0x1851, 0x0000, 0x0000, 0x0000,
+ 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x4d4c, 0x5352, 0x1454, 0x3534, 0x2b36, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x4d4c,
+ 0x5352, 0x1454, 0x3534, 0x2b36, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x4d4c, 0x5352, 0x1454, 0x3534, 0x2b36, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x4c3d, 0x524d, 0x5453, 0x3414, 0x3635, 0x0d2b, 0x0c0b, 0x2625, 0x2827, 0x2a29, 0x3d15,
+ 0x0000, 0x0000, 0x0000, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x0b0d, 0x250c, 0x2726,
+ 0x2928, 0x152a, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0f00, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x1800, 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x1b1a, 0x3837, 0x3a39, 0x3c3b, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x2b15, 0x002c, 0x0000, 0x0000, 0x0000, 0x1a19, 0x371b, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x1a19, 0x371b, 0x3938, 0x3b3a, 0x153c, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x2b15, 0x2d2c, 0x2f2e, 0x3130,
+ 0x5500, 0x5756, 0x5958, 0x5b5a, 0x5d5c, 0x5e2c, 0x605f, 0x6261, 0x6300, 0x6564, 0x2d66, 0x6867, 0x6a69, 0x6c6b, 0x6e6d, 0x2e6f,
+ 0x0000, 0x0000, 0x0000, 0x1a19, 0x371b, 0x3938, 0x3b3a, 0x183c, 0x0f0e, 0x1110, 0x1312, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1b00, 0x0000, 0x0000, 0x0000, 0x1500, 0x0000, 0x0000, 0x001a, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0018, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3900, 0x3900, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1500, 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x1b1a, 0x3837, 0x3a39, 0x3c3b,
+ 0x2b15, 0x2d2c, 0x2f2e, 0x3130, 0x1632, 0x7170, 0x4e72, 0x7473, 0x7675, 0x7717, 0x7978, 0x7a4f, 0x7c7b, 0x337d, 0x7f7e, 0x5080,
+ 0x8281, 0x8483, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0f0e, 0x3819, 0x4e2e, 0x504f, 0x1538, 0x162e, 0x174e, 0x384f,
+ 0x2e15, 0x4e16, 0x3317, 0x1550, 0x1919, 0x1a19, 0x1a1a, 0x381a, 0x1515, 0x1515, 0x2c15, 0x2e2e, 0x2e2e, 0x7116, 0x4e4e, 0x4e4e,
+ 0x174e, 0x384f, 0x0f2e, 0x420f, 0x0010, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0e18, 0x0000, 0x0000,
+ 0x1900, 0x1b1a, 0x3837, 0x3a39, 0x3c3b, 0x2b15, 0x2d2c, 0x2f2e, 0x3130, 0x1632, 0x7170, 0x4e72, 0x7473, 0x7675, 0x0000, 0x0000,
+ 0x3819, 0x2e15, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3200, 0x0000, 0x0000, 0x0000, 0x0000, 0x0076, 0x0000, 0x0000,
+ 0x1900, 0x151a, 0x162b, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1a19, 0x151b, 0x162b, 0x3317,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x1b1a, 0x3837, 0x2b15, 0x0000, 0x0000, 0x0000, 0x1900, 0x1b1a, 0x3737, 0x1538, 0x162b,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x1538, 0x162b, 0x0000, 0x0000, 0x0000, 0x1519, 0x162b, 0x1b1a, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0f85, 0x0000, 0x1a19, 0x371b, 0x3938, 0x3b3a, 0x153c, 0x2c2b, 0x2e2d, 0x302f,
+ 0x0000, 0x7016, 0x7271, 0x734e, 0x7574, 0x1776, 0x7877, 0x4f79, 0x7b7a, 0x7d7c, 0x7e33, 0x807f, 0x8150, 0x8382, 0x5184, 0x8786,
+ 0x8988, 0x8b8a, 0x8d8c, 0x8f8e, 0x9190, 0x9392, 0x9594, 0x9796, 0x0b0d, 0x250c, 0x2b15, 0x1716, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x002e, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x2b15,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x1a19, 0x371b, 0x2b15, 0x1716, 0x0000, 0x0000, 0x0000, 0x0000, 0x1900, 0x1b1a, 0x1537, 0x162b,
+ 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x3819, 0x2e15, 0x1716, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x2c2b, 0x2e2d, 0x302f,
+ 0x3231, 0x7016, 0x7271, 0x734e, 0x7574, 0x0f76, 0x410e, 0x0042, 0x0000, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x152a, 0x2c2b, 0x2e2d,
+ 0x302f, 0x3231, 0x1716, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x3130, 0x1632, 0x0017, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x2b15, 0x0000, 0x0000, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x2b15, 0x2d2c, 0x2f2e,
+ 0x3130, 0x0032, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x1b1a, 0x3837, 0x3a39, 0x3c3b, 0x371b, 0x3938, 0x3b3a, 0x373c,
+ 0x3938, 0x3b3a, 0x193c, 0x1b1a, 0x3837, 0x3a39, 0x3c3b, 0x1a19, 0x371b, 0x1a38, 0x1b1b, 0x3837, 0x3a39, 0x3c3b, 0x1a19, 0x1b1b,
+ 0x3837, 0x9998, 0x1a19, 0x1b1b, 0x3837, 0x1b1b, 0x3737, 0x3737, 0x3a39, 0x3a3a, 0x3b3b, 0x3c3c, 0x3c3c, 0x1b1a, 0x3837, 0x1939,
+ 0x1b1a, 0x3737, 0x3838, 0x1b1a, 0x1a19, 0x4241, 0x4148, 0x1242, 0x470e, 0x0e0e, 0x410f, 0x2d42, 0x372e, 0x3938, 0x3b3a, 0x003c,
+ 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x1500, 0x3316, 0x9b9a, 0x9d9c, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000,
+ 0x3231, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0201,
+ 0x0403, 0x0605, 0x0807, 0x0a09, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x0201, 0x0403,
+ 0x0605, 0x0807, 0x0a09, 0x0201, 0x0403, 0x0605, 0x0807, 0x0a09, 0x3d3d, 0x0b0d, 0x250c, 0x2726, 0x2928, 0x182a, 0x0018, 0x0000,
+ 0x003c, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xeeee, 0xeeee, 0xeeee, 0xeeee
+ };
+ // Every item contains the value for numeric value.
+ private static byte[] s_pNumericValues = new byte[]
+ {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xb0, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x8f, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x34, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3e, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4e, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x51, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x54, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x56, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xc3, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x22, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x92, 0x24, 0x49, 0x92, 0x24, 0x49, 0xc2, 0x3f, 0x1c, 0xc7, 0x71, 0x1c, 0xc7, 0x71, 0xbc, 0x3f,
+ 0x9a, 0x99, 0x99, 0x99, 0x99, 0x99, 0xb9, 0x3f, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xd5, 0x3f,
+ 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xe5, 0x3f, 0x9a, 0x99, 0x99, 0x99, 0x99, 0x99, 0xc9, 0x3f,
+ 0x9a, 0x99, 0x99, 0x99, 0x99, 0x99, 0xd9, 0x3f, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0xe3, 0x3f,
+ 0x9a, 0x99, 0x99, 0x99, 0x99, 0x99, 0xe9, 0x3f, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xc5, 0x3f,
+ 0xab, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xea, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd8, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xec, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x7f, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xb3, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0xe8, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0xf8, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x36, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3b, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3d, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x40, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x41, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x41, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x42, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x43, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x44, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x45, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x46, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x47, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x47, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x48, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x69, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x72, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x82, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x85, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x89, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x8c, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x9f, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0xa7, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xaf, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0xb7, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0xbb, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0xbf, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x94, 0xc1, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xd3, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0xdd, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xe3, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0xed, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x17, 0xf1, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0xf3, 0x40,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xf9, 0xf5, 0x40, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xed, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0x08, 0x41, 0x00, 0x00, 0x00, 0x00, 0x80, 0x4f, 0x12, 0x41,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0x18, 0x41, 0x00, 0x00, 0x00, 0x00, 0x80, 0x84, 0x1e, 0x41,
+ 0x00, 0x00, 0x00, 0x00, 0x80, 0x4f, 0x22, 0x41, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x5c, 0x25, 0x41,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x6a, 0x28, 0x41, 0x00, 0x00, 0x00, 0x00, 0x40, 0x77, 0x2b, 0x41,
+ 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xb5, 0x3f, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xc5, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd0, 0x3f, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xd5, 0x3f,
+ 0xab, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xda, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x3f,
+ 0xab, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xe2, 0x3f, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0xe5, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe8, 0x3f, 0xab, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xea, 0x3f,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x5e, 0x0a, 0x41, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5e, 0x1a, 0x41,
+ 0x00, 0x00, 0x00, 0x00, 0x80, 0x84, 0x2e, 0x41, 0x00, 0x00, 0x00, 0x00, 0x84, 0xd7, 0x97, 0x41,
+ 0x00, 0x00, 0x00, 0x20, 0x5f, 0xa0, 0x02, 0x42, 0x00, 0x00, 0x00, 0xa2, 0x94, 0x1a, 0x6d, 0x42
+ };
+
+ private static ushort[] s_pDigitValues = new ushort []
+ {
+ 0xffff, 0x0000, 0x0101, 0x0202, 0x0303, 0x0404, 0x0505, 0x0606,
+ 0x0707, 0x0808, 0x0909, 0xff02, 0xff03, 0xff01, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xff04, 0xff05, 0xff06,
+ 0xff07, 0xff08, 0xff09, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xff00, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
+ 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0x0000, 0x0000
+ };
+
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
deleted file mode 100644
index 374ed0dcfa..0000000000
--- a/src/mscorlib/src/System/Globalization/ChineseLunisolarCalendar.cs
+++ /dev/null
@@ -1,397 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about ChineseLunisolarCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1901/02/19 2101/01/28
- ** ChineseLunisolar 1901/01/01 2100/12/29
- */
-
- [Serializable]
- public class ChineseLunisolarCalendar : EastAsianLunisolarCalendar {
-
-
- //
- // The era value for the current era.
- //
-
- public const int ChineseEra = 1;
- //internal static Calendar m_defaultInstance;
-
- internal const int MIN_LUNISOLAR_YEAR = 1901;
- internal const int MAX_LUNISOLAR_YEAR = 2100;
-
- internal const int MIN_GREGORIAN_YEAR = 1901;
- internal const int MIN_GREGORIAN_MONTH = 2;
- internal const int MIN_GREGORIAN_DAY = 19;
-
- internal const int MAX_GREGORIAN_YEAR = 2101;
- internal const int MAX_GREGORIAN_MONTH = 1;
- internal const int MAX_GREGORIAN_DAY = 28;
-
- internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
- internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
-
- public override DateTime MinSupportedDateTime {
- get
- {
- return (minDate);
- }
- }
-
-
- public override DateTime MaxSupportedDateTime {
- get
- {
- return (maxDate);
- }
- }
-
- protected override int DaysInYearBeforeMinSupportedYear
- {
- get
- {
- // 1900: 1-29 2-30 3-29 4-29 5-30 6-29 7-30 8-30 Leap8-29 9-30 10-30 11-29 12-30 from Calendrical Tabulations
- return 384;
- }
- }
-
-
- static readonly int [,] yinfo =
- {
- /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
-1901 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1902 */{ 0 , 2 , 8 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1903 */{ 5 , 1 , 29 , 21096 },/* 29 30 29 30 29 29 30 29 29 30 30 29 30 383
-1904 */{ 0 , 2 , 16 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1905 */{ 0 , 2 , 4 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1906 */{ 4 , 1 , 25 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1907 */{ 0 , 2 , 13 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1908 */{ 0 , 2 , 2 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355
-1909 */{ 2 , 1 , 22 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1910 */{ 0 , 2 , 10 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1911 */{ 6 , 1 , 30 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1912 */{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
-1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
-1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
-1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
-1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
-1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
-1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
-1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
-1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
-1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
-1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
-1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384
-1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
-1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
-1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
-1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384
-1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
-2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354
-2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
-2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
-2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
-2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355
-2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
-2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
-2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
-2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
-2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
-2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
-2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-2051 */{ 0 , 2 , 11 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-2052 */{ 8 , 2 , 1 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-2053 */{ 0 , 2 , 19 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-2054 */{ 0 , 2 , 8 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-2055 */{ 6 , 1 , 28 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-2056 */{ 0 , 2 , 15 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-2057 */{ 0 , 2 , 4 , 27424 },/* 29 30 30 29 30 29 30 30 29 29 30 29 0 354
-2058 */{ 4 , 1 , 24 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 29 384
-2059 */{ 0 , 2 , 12 , 43744 },/* 30 29 30 29 30 29 30 29 30 30 30 29 0 355
-2060 */{ 0 , 2 , 2 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-2061 */{ 3 , 1 , 21 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 29 384
-2062 */{ 0 , 2 , 9 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-2063 */{ 7 , 1 , 29 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-2064 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-2065 */{ 0 , 2 , 5 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-2066 */{ 5 , 1 , 26 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-2067 */{ 0 , 2 , 14 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-2068 */{ 0 , 2 , 3 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355
-2069 */{ 4 , 1 , 23 , 21224 },/* 29 30 29 30 29 29 30 29 30 30 30 29 30 384
-2070 */{ 0 , 2 , 11 , 21200 },/* 29 30 29 30 29 29 30 29 30 30 29 30 0 354
-2071 */{ 8 , 1 , 31 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-2072 */{ 0 , 2 , 19 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2073 */{ 0 , 2 , 7 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-2074 */{ 6 , 1 , 27 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-2075 */{ 0 , 2 , 15 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2076 */{ 0 , 2 , 5 , 21920 },/* 29 30 29 30 29 30 29 30 30 29 30 29 0 354
-2077 */{ 4 , 1 , 24 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 29 384
-2078 */{ 0 , 2 , 12 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-2079 */{ 0 , 2 , 2 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-2080 */{ 3 , 1 , 22 , 43320 },/* 30 29 30 29 30 29 29 30 29 29 30 30 30 384
-2081 */{ 0 , 2 , 9 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 0 354
-2082 */{ 7 , 1 , 29 , 29336 },/* 29 30 30 30 29 29 30 29 30 29 29 30 30 384
-2083 */{ 0 , 2 , 17 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-2084 */{ 0 , 2 , 6 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2085 */{ 5 , 1 , 26 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
-2086 */{ 0 , 2 , 14 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-2087 */{ 0 , 2 , 3 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-2088 */{ 4 , 1 , 24 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 29 383
-2089 */{ 0 , 2 , 10 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-2090 */{ 8 , 1 , 30 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-2091 */{ 0 , 2 , 18 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-2092 */{ 0 , 2 , 7 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355
-2093 */{ 6 , 1 , 27 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
-2094 */{ 0 , 2 , 15 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-2095 */{ 0 , 2 , 5 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-2096 */{ 4 , 1 , 25 , 42216 },/* 30 29 30 29 29 30 29 29 30 30 30 29 30 384
-2097 */{ 0 , 2 , 12 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-2098 */{ 0 , 2 , 1 , 53584 },/* 30 30 29 30 29 29 29 30 29 30 29 30 0 354
-2099 */{ 2 , 1 , 21 , 55592 },/* 30 30 29 30 30 29 29 30 29 29 30 29 30 384
-2100 */{ 0 , 2 , 9 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
- */};
-
-
- internal override int MinCalendarYear {
- get
- {
- return (MIN_LUNISOLAR_YEAR);
- }
- }
-
- internal override int MaxCalendarYear {
- get
- {
- return (MAX_LUNISOLAR_YEAR);
- }
- }
-
- internal override DateTime MinDate {
- get
- {
- return (minDate);
- }
- }
-
- internal override DateTime MaxDate {
- get
- {
- return (maxDate);
- }
- }
-
- internal override EraInfo[] CalEraInfo {
- get
- {
- return (null);
- }
- }
-
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR ));
- }
- Contract.EndContractBlock();
-
- return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
- }
-
- internal override int GetYear(int year, DateTime time) {
- return year;
- }
-
- internal override int GetGregorianYear(int year, int era) {
- if (era != CurrentEra && era != ChineseEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
-
- if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
- }
- Contract.EndContractBlock();
-
- return year;
- }
-
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of ChineseLunisolarCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
-
- /*
- internal static Calendar GetDefaultInstance()
- {
- if (m_defaultInstance == null) {
- m_defaultInstance = new ChineseLunisolarCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
- // Construct an instance of ChineseLunisolar calendar.
-
- public ChineseLunisolarCalendar() {
- }
-
-
- public override int GetEra(DateTime time) {
- CheckTicksRange(time.Ticks);
- return (ChineseEra);
- }
-
- internal override int ID {
- get {
- return (CAL_CHINESELUNISOLAR);
- }
- }
-
- internal override int BaseCalendarID {
- get {
- //Use CAL_GREGORIAN just to get CurrentEraValue as 1 since we do not have data under the ID CAL_ChineseLunisolar yet
- return (CAL_GREGORIAN);
- }
- }
-
-
- public override int[] Eras {
- get {
- return (new int[] {ChineseEra});
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs
new file mode 100644
index 0000000000..2a20de76bb
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.Invariant.cs
@@ -0,0 +1,238 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Globalization
+{
+ public partial class CompareInfo
+ {
+ internal static unsafe int InvariantIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+ Debug.Assert(startIndex >= 0 && startIndex < source.Length);
+
+ fixed (char* pSource = source) fixed (char* pValue = value)
+ {
+ char* pSrc = &pSource[startIndex];
+ int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : true);
+ if (index >= 0)
+ {
+ return index + startIndex;
+ }
+ return -1;
+ }
+ }
+
+ internal static unsafe int InvariantLastIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+ Debug.Assert(startIndex >= 0 && startIndex < source.Length);
+
+ fixed (char* pSource = source) fixed (char* pValue = value)
+ {
+ char* pSrc = &pSource[startIndex - count + 1];
+ int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : false);
+ if (index >= 0)
+ {
+ return index + startIndex - count + 1;
+ }
+ return -1;
+ }
+ }
+
+ private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool start)
+ {
+ int ctrSource = 0; // index value into source
+ int ctrValue = 0; // index value into value
+ char sourceChar; // Character for case lookup in source
+ char valueChar; // Character for case lookup in value
+ int lastSourceStart;
+
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+ Debug.Assert(sourceCount >= 0);
+ Debug.Assert(valueCount >= 0);
+
+ if (valueCount == 0)
+ {
+ return start ? 0 : sourceCount - 1;
+ }
+
+ if (sourceCount < valueCount)
+ {
+ return -1;
+ }
+
+ if (start)
+ {
+ lastSourceStart = sourceCount - valueCount;
+ if (ignoreCase)
+ {
+ char firstValueChar = InvariantToUpper(value[0]);
+ for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
+ {
+ sourceChar = InvariantToUpper(source[ctrSource]);
+ if (sourceChar != firstValueChar)
+ {
+ continue;
+ }
+
+ for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
+ {
+ sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
+ valueChar = InvariantToUpper(value[ctrValue]);
+
+ if (sourceChar != valueChar)
+ {
+ break;
+ }
+ }
+
+ if (ctrValue == valueCount)
+ {
+ return ctrSource;
+ }
+ }
+ }
+ else
+ {
+ char firstValueChar = value[0];
+ for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
+ {
+ sourceChar = source[ctrSource];
+ if (sourceChar != firstValueChar)
+ {
+ continue;
+ }
+
+ for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
+ {
+ sourceChar = source[ctrSource + ctrValue];
+ valueChar = value[ctrValue];
+
+ if (sourceChar != valueChar)
+ {
+ break;
+ }
+ }
+
+ if (ctrValue == valueCount)
+ {
+ return ctrSource;
+ }
+ }
+ }
+ }
+ else
+ {
+ lastSourceStart = sourceCount - valueCount;
+ if (ignoreCase)
+ {
+ char firstValueChar = InvariantToUpper(value[0]);
+ for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
+ {
+ sourceChar = InvariantToUpper(source[ctrSource]);
+ if (sourceChar != firstValueChar)
+ {
+ continue;
+ }
+ for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
+ {
+ sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
+ valueChar = InvariantToUpper(value[ctrValue]);
+
+ if (sourceChar != valueChar)
+ {
+ break;
+ }
+ }
+
+ if (ctrValue == valueCount)
+ {
+ return ctrSource;
+ }
+ }
+ }
+ else
+ {
+ char firstValueChar = value[0];
+ for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
+ {
+ sourceChar = source[ctrSource];
+ if (sourceChar != firstValueChar)
+ {
+ continue;
+ }
+
+ for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
+ {
+ sourceChar = source[ctrSource + ctrValue];
+ valueChar = value[ctrValue];
+
+ if (sourceChar != valueChar)
+ {
+ break;
+ }
+ }
+
+ if (ctrValue == valueCount)
+ {
+ return ctrSource;
+ }
+ }
+ }
+ }
+
+ return -1;
+ }
+
+ private static char InvariantToUpper(char c)
+ {
+ return (uint)(c - 'a') <= (uint)('z' - 'a') ? (char)(c - 0x20) : c;
+ }
+
+ private unsafe SortKey InvariantCreateSortKey(string source, CompareOptions options)
+ {
+ if (source == null) { throw new ArgumentNullException(nameof(source)); }
+ Contract.EndContractBlock();
+
+ if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
+ }
+
+ byte [] keyData;
+ if (source.Length == 0)
+ {
+ keyData = Array.Empty<byte>();
+ }
+ else
+ {
+ // In the invariant mode, all string comparisons are done as ordinal so when generating the sort keys we generate it according to this fact
+ keyData = new byte[source.Length * sizeof(char)];
+
+ fixed (char* pChar = source) fixed (byte* pByte = keyData)
+ {
+ if ((options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0)
+ {
+ short *pShort = (short *) pByte;
+ for (int i=0; i<source.Length; i++)
+ {
+ pShort[i] = (short) InvariantToUpper(source[i]);
+ }
+ }
+ else
+ {
+ Buffer.MemoryCopy(pChar, pByte, keyData.Length, keyData.Length);
+ }
+ }
+ }
+ return new SortKey(Name, source, options, keyData);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs
new file mode 100644
index 0000000000..edc9a7f575
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs
@@ -0,0 +1,439 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+
+namespace System.Globalization
+{
+ public partial class CompareInfo
+ {
+ [NonSerialized]
+ private Interop.GlobalizationInterop.SafeSortHandle _sortHandle;
+
+ [NonSerialized]
+ private bool _isAsciiEqualityOrdinal;
+
+ private void InitSort(CultureInfo culture)
+ {
+ _sortName = culture.SortName;
+
+ if (_invariantMode)
+ {
+ _isAsciiEqualityOrdinal = true;
+ }
+ else
+ {
+ Interop.GlobalizationInterop.ResultCode resultCode = Interop.GlobalizationInterop.GetSortHandle(GetNullTerminatedUtf8String(_sortName), out _sortHandle);
+ if (resultCode != Interop.GlobalizationInterop.ResultCode.Success)
+ {
+ _sortHandle.Dispose();
+
+ if (resultCode == Interop.GlobalizationInterop.ResultCode.OutOfMemory)
+ throw new OutOfMemoryException();
+
+ throw new ExternalException(SR.Arg_ExternalException);
+ }
+ _isAsciiEqualityOrdinal = (_sortName == "en-US" || _sortName == "");
+ }
+ }
+
+ internal static unsafe int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+
+ if (value.Length == 0)
+ {
+ return startIndex;
+ }
+
+ if (count < value.Length)
+ {
+ return -1;
+ }
+
+ if (ignoreCase)
+ {
+ fixed (char* pSource = source)
+ {
+ int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
+ return index != -1 ?
+ startIndex + index :
+ -1;
+ }
+ }
+
+ int endIndex = startIndex + (count - value.Length);
+ for (int i = startIndex; i <= endIndex; i++)
+ {
+ int valueIndex, sourceIndex;
+
+ for (valueIndex = 0, sourceIndex = i;
+ valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
+ valueIndex++, sourceIndex++) ;
+
+ if (valueIndex == value.Length)
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+
+ internal static unsafe int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+
+ if (value.Length == 0)
+ {
+ return startIndex;
+ }
+
+ if (count < value.Length)
+ {
+ return -1;
+ }
+
+ // startIndex is the index into source where we start search backwards from.
+ // leftStartIndex is the index into source of the start of the string that is
+ // count characters away from startIndex.
+ int leftStartIndex = startIndex - count + 1;
+
+ if (ignoreCase)
+ {
+ fixed (char* pSource = source)
+ {
+ int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
+ return lastIndex != -1 ?
+ leftStartIndex + lastIndex :
+ -1;
+ }
+ }
+
+ for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
+ {
+ int valueIndex, sourceIndex;
+
+ for (valueIndex = 0, sourceIndex = i;
+ valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
+ valueIndex++, sourceIndex++) ;
+
+ if (valueIndex == value.Length) {
+ return i;
+ }
+ }
+
+ 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);
+
+ return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
+ }
+
+ private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(string1 != null);
+ Debug.Assert(string2 != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ fixed (char* pString1 = string1)
+ {
+ fixed (char* pString2 = string2)
+ {
+ return Interop.GlobalizationInterop.CompareString(_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
+ }
+ }
+ }
+
+ internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+
+ int index;
+
+ if (target.Length == 0)
+ {
+ if(matchLengthPtr != null)
+ *matchLengthPtr = 0;
+ return startIndex;
+ }
+
+ if (options == CompareOptions.Ordinal)
+ {
+ index = IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
+ if(index != -1)
+ {
+ if(matchLengthPtr != null)
+ *matchLengthPtr = target.Length;
+ }
+ return index;
+ }
+
+ if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
+ {
+ index = IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
+ if(index != -1)
+ {
+ if(matchLengthPtr != null)
+ *matchLengthPtr = target.Length;
+ }
+ return index;
+ }
+
+ fixed (char* pSource = source)
+ {
+ index = Interop.GlobalizationInterop.IndexOf(_sortHandle, target, target.Length, pSource + startIndex, count, options, matchLengthPtr);
+
+ return index != -1 ? index + startIndex : -1;
+ }
+ }
+
+ private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+
+ if (target.Length == 0)
+ {
+ return startIndex;
+ }
+
+ if (options == CompareOptions.Ordinal)
+ {
+ return LastIndexOfOrdinalCore(source, target, startIndex, count, ignoreCase: false);
+ }
+
+ if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort())
+ {
+ return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
+ }
+
+ // startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
+ // of the start of the string that is count characters away from startIndex.
+ int leftStartIndex = (startIndex - count + 1);
+
+ fixed (char* pSource = source)
+ {
+ int lastIndex = Interop.GlobalizationInterop.LastIndexOf(_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
+
+ return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
+ }
+ }
+
+ private bool StartsWith(string source, string prefix, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(prefix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort())
+ {
+ return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
+ }
+
+ return Interop.GlobalizationInterop.StartsWith(_sortHandle, prefix, prefix.Length, source, source.Length, options);
+ }
+
+ private bool EndsWith(string source, string suffix, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(suffix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort())
+ {
+ return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
+ }
+
+ return Interop.GlobalizationInterop.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options);
+ }
+
+ private unsafe SortKey CreateSortKey(String source, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ if (source==null) { throw new ArgumentNullException(nameof(source)); }
+ Contract.EndContractBlock();
+
+ if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
+ }
+
+ byte [] keyData;
+ if (source.Length == 0)
+ {
+ keyData = Array.Empty<Byte>();
+ }
+ else
+ {
+ int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
+ keyData = new byte[sortKeyLength];
+
+ fixed (byte* pSortKey = keyData)
+ {
+ Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
+ }
+ }
+
+ return new SortKey(Name, source, options, keyData);
+ }
+
+ private unsafe static bool IsSortable(char *text, int length)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ int index = 0;
+ UnicodeCategory uc;
+
+ while (index < length)
+ {
+ if (Char.IsHighSurrogate(text[index]))
+ {
+ if (index == length - 1 || !Char.IsLowSurrogate(text[index+1]))
+ return false; // unpaired surrogate
+
+ uc = CharUnicodeInfo.InternalGetUnicodeCategory(Char.ConvertToUtf32(text[index], text[index+1]));
+ if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
+ return false;
+
+ index += 2;
+ continue;
+ }
+
+ if (Char.IsLowSurrogate(text[index]))
+ {
+ return false; // unpaired surrogate
+ }
+
+ uc = CharUnicodeInfo.GetUnicodeCategory(text[index]);
+ if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned)
+ {
+ return false;
+ }
+
+ index++;
+ }
+
+ return true;
+ }
+
+ // -----------------------------
+ // ---- PAL layer ends here ----
+ // -----------------------------
+
+ internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ if (source.Length == 0)
+ {
+ return 0;
+ }
+
+ int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, null, 0, options);
+
+ // As an optimization, for small sort keys we allocate the buffer on the stack.
+ if (sortKeyLength <= 256)
+ {
+ byte* pSortKey = stackalloc byte[sortKeyLength];
+ Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
+ return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
+ }
+
+ byte[] sortKey = new byte[sortKeyLength];
+
+ fixed (byte* pSortKey = sortKey)
+ {
+ Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
+ return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
+ }
+ }
+
+ [DllImport(JitHelpers.QCall)]
+ [SuppressUnmanagedCodeSecurity]
+ private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
+
+ private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
+ {
+ if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
+ {
+ return CompareOptions.OrdinalIgnoreCase;
+ }
+ else
+ {
+ return CompareOptions.Ordinal;
+ }
+ }
+
+ private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
+ {
+ // Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
+ return (options & CompareOptions.IgnoreSymbols) == 0;
+ }
+
+ private static byte[] GetNullTerminatedUtf8String(string s)
+ {
+ int byteLen = System.Text.Encoding.UTF8.GetByteCount(s);
+
+ // Allocate an extra byte (which defaults to 0) as the null terminator.
+ byte[] buffer = new byte[byteLen + 1];
+
+ int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0);
+
+ Debug.Assert(bytesWritten == byteLen);
+
+ return buffer;
+ }
+
+ private SortVersion GetSortVersion()
+ {
+ Debug.Assert(!_invariantMode);
+
+ int sortVersion = Interop.GlobalizationInterop.GetSortVersion();
+ return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0,
+ (byte) (LCID >> 24),
+ (byte) ((LCID & 0x00FF0000) >> 16),
+ (byte) ((LCID & 0x0000FF00) >> 8),
+ (byte) (LCID & 0xFF)));
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
new file mode 100644
index 0000000000..d20bb9f9f3
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
@@ -0,0 +1,486 @@
+// 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.Security;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+
+namespace System.Globalization
+{
+ public partial class CompareInfo
+ {
+ private unsafe void InitSort(CultureInfo culture)
+ {
+ _sortName = culture.SortName;
+
+ _name = culture._name;
+ _sortName = culture.SortName;
+
+ if (_invariantMode)
+ {
+ _sortHandle = IntPtr.Zero;
+ }
+ else
+ {
+ const uint LCMAP_SORTHANDLE = 0x20000000;
+ IntPtr handle;
+ int ret = Interop.Kernel32.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
+ _sortHandle = ret > 0 ? handle : IntPtr.Zero;
+ }
+ }
+
+ private static unsafe int FindStringOrdinal(
+ uint dwFindStringOrdinalFlags,
+ string stringSource,
+ int offset,
+ int cchSource,
+ string value,
+ int cchValue,
+ bool bIgnoreCase)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ fixed (char* pSource = stringSource)
+ fixed (char* pValue = value)
+ {
+ int ret = Interop.Kernel32.FindStringOrdinal(
+ dwFindStringOrdinalFlags,
+ pSource + offset,
+ cchSource,
+ pValue,
+ cchValue,
+ bIgnoreCase ? 1 : 0);
+ return ret < 0 ? ret : ret + offset;
+ }
+ }
+
+ internal static int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+
+ return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase);
+ }
+
+ internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ Debug.Assert(source != null);
+ Debug.Assert(value != null);
+
+ return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase);
+ }
+
+ private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(source != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ if (source.Length == 0)
+ {
+ return 0;
+ }
+
+ int flags = GetNativeCompareFlags(options);
+ int tmpHash = 0;
+#if CORECLR
+ tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags, 0);
+#else
+ fixed (char* pSource = source)
+ {
+ if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
+ LCMAP_HASH | (uint)flags,
+ pSource, source.Length,
+ &tmpHash, sizeof(int),
+ null, null, _sortHandle) == 0)
+ {
+ Environment.FailFast("LCMapStringEx failed!");
+ }
+ }
+#endif
+ return tmpHash;
+ }
+
+ private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ // Use the OS to compare and then convert the result to expected value by subtracting 2
+ return Interop.Kernel32.CompareStringOrdinal(string1, count1, string2, count2, true) - 2;
+ }
+
+ private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(string1 != null);
+ Debug.Assert(string2 != null);
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
+
+ fixed (char* pLocaleName = localeName)
+ fixed (char* pString1 = string1)
+ fixed (char* pString2 = string2)
+ {
+ int result = Interop.Kernel32.CompareStringEx(
+ pLocaleName,
+ (uint)GetNativeCompareFlags(options),
+ pString1 + offset1,
+ length1,
+ pString2 + offset2,
+ length2,
+ null,
+ null,
+ _sortHandle);
+
+ if (result == 0)
+ {
+ Environment.FailFast("CompareStringEx failed");
+ }
+
+ // Map CompareStringEx return value to -1, 0, 1.
+ return result - 2;
+ }
+ }
+
+ private unsafe int FindString(
+ uint dwFindNLSStringFlags,
+ string lpStringSource,
+ int startSource,
+ int cchSource,
+ string lpStringValue,
+ int startValue,
+ int cchValue,
+ int *pcchFound)
+ {
+ Debug.Assert(!_invariantMode);
+
+ string localeName = _sortHandle != IntPtr.Zero ? null : _sortName;
+
+ fixed (char* pLocaleName = localeName)
+ fixed (char* pSource = lpStringSource)
+ fixed (char* pValue = lpStringValue)
+ {
+ char* pS = pSource + startSource;
+ char* pV = pValue + startValue;
+
+ return Interop.Kernel32.FindNLSStringEx(
+ pLocaleName,
+ dwFindNLSStringFlags,
+ pS,
+ cchSource,
+ pV,
+ cchValue,
+ pcchFound,
+ null,
+ null,
+ _sortHandle);
+ }
+ }
+
+ internal unsafe int IndexOfCore(String source, String target, int startIndex, int count, CompareOptions options, int* matchLengthPtr)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(source != null);
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+
+ if (target.Length == 0)
+ {
+ if (matchLengthPtr != null)
+ *matchLengthPtr = 0;
+ return 0;
+ }
+
+ if (source.Length == 0)
+ {
+ return -1;
+ }
+
+ if ((options & CompareOptions.Ordinal) != 0)
+ {
+ int retValue = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false);
+ if (retValue >= 0)
+ {
+ if (matchLengthPtr != null)
+ *matchLengthPtr = target.Length;
+ }
+ return retValue;
+ }
+ else
+ {
+ int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count,
+ target, 0, target.Length, matchLengthPtr);
+ if (retValue >= 0)
+ {
+ return retValue + startIndex;
+ }
+ }
+
+ return -1;
+ }
+
+ private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(target != null);
+ Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
+
+ // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for
+ // and add a precondition that target is not empty.
+ if (target.Length == 0)
+ return startIndex; // keep Whidbey compatibility
+
+ if ((options & CompareOptions.Ordinal) != 0)
+ {
+ return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true);
+ }
+ else
+ {
+ int retValue = FindString(FIND_FROMEND | (uint) GetNativeCompareFlags(options), source, startIndex - count + 1,
+ count, target, 0, target.Length, null);
+
+ if (retValue >= 0)
+ {
+ return retValue + startIndex - (count - 1);
+ }
+ }
+
+ return -1;
+ }
+
+ private unsafe bool StartsWith(string source, string prefix, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(prefix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length,
+ prefix, 0, prefix.Length, null) >= 0;
+ }
+
+ private unsafe bool EndsWith(string source, string suffix, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(!string.IsNullOrEmpty(source));
+ Debug.Assert(!string.IsNullOrEmpty(suffix));
+ Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
+
+ return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length,
+ suffix, 0, suffix.Length, null) >= 0;
+ }
+
+ // PAL ends here
+ [NonSerialized]
+ private IntPtr _sortHandle;
+
+ private const uint LCMAP_SORTKEY = 0x00000400;
+ private const uint LCMAP_HASH = 0x00040000;
+
+ private const int FIND_STARTSWITH = 0x00100000;
+ private const int FIND_ENDSWITH = 0x00200000;
+ private const int FIND_FROMSTART = 0x00400000;
+ private const int FIND_FROMEND = 0x00800000;
+
+ // TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false?
+ private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex)
+ {
+ int retValue = -1;
+
+ int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex;
+
+ fixed (char* pSource = source, spTarget = target)
+ {
+ char* spSubSource = pSource + sourceStartIndex;
+
+ if (findLastIndex)
+ {
+ int startPattern = (sourceCount - 1) - targetCount + 1;
+ if (startPattern < 0)
+ return -1;
+
+ char patternChar0 = spTarget[0];
+ for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--)
+ {
+ if (spSubSource[ctrSrc] != patternChar0)
+ continue;
+
+ int ctrPat;
+ for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
+ {
+ if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
+ break;
+ }
+ if (ctrPat == targetCount)
+ {
+ retValue = ctrSrc;
+ break;
+ }
+ }
+
+ if (retValue >= 0)
+ {
+ retValue += startIndex - sourceCount + 1;
+ }
+ }
+ else
+ {
+ int endPattern = (sourceCount - 1) - targetCount + 1;
+ if (endPattern < 0)
+ return -1;
+
+ char patternChar0 = spTarget[0];
+ for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++)
+ {
+ if (spSubSource[ctrSrc] != patternChar0)
+ continue;
+ int ctrPat;
+ for (ctrPat = 1; ctrPat < targetCount; ctrPat++)
+ {
+ if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat])
+ break;
+ }
+ if (ctrPat == targetCount)
+ {
+ retValue = ctrSrc;
+ break;
+ }
+ }
+
+ if (retValue >= 0)
+ {
+ retValue += startIndex;
+ }
+ }
+ }
+
+ return retValue;
+ }
+
+ private unsafe SortKey CreateSortKey(String source, CompareOptions options)
+ {
+ Debug.Assert(!_invariantMode);
+
+ if (source == null) { throw new ArgumentNullException(nameof(source)); }
+ Contract.EndContractBlock();
+
+ if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
+ }
+
+ byte [] keyData = null;
+ if (source.Length == 0)
+ {
+ keyData = Array.Empty<byte>();
+ }
+ else
+ {
+ fixed (char *pSource = source)
+ {
+ int result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
+ LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options),
+ pSource, source.Length,
+ null, 0,
+ null, null, _sortHandle);
+ if (result == 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidFlag, "source");
+ }
+
+ keyData = new byte[result];
+
+ fixed (byte* pBytes = keyData)
+ {
+ result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName,
+ LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options),
+ pSource, source.Length,
+ pBytes, keyData.Length,
+ null, null, _sortHandle);
+ }
+ }
+ }
+
+ return new SortKey(Name, source, options, keyData);
+ }
+
+ private static unsafe bool IsSortable(char* text, int length)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length);
+ }
+
+ private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal
+ private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
+ private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
+ private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
+ private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
+ private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
+ private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
+ private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
+
+ private static int GetNativeCompareFlags(CompareOptions options)
+ {
+ // Use "linguistic casing" by default (load the culture's casing exception tables)
+ int nativeCompareFlags = NORM_LINGUISTIC_CASING;
+
+ if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
+ if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
+ if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
+ if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
+ if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
+ if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
+
+ // TODO: Can we try for GetNativeCompareFlags to never
+ // take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special
+ // in some places.
+ // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
+ if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
+
+ Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
+ CompareOptions.IgnoreKanaType |
+ CompareOptions.IgnoreNonSpace |
+ CompareOptions.IgnoreSymbols |
+ CompareOptions.IgnoreWidth |
+ CompareOptions.StringSort)) == 0) ||
+ (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
+
+ return nativeCompareFlags;
+ }
+
+ private unsafe SortVersion GetSortVersion()
+ {
+ Debug.Assert(!_invariantMode);
+
+ Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx();
+ Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion);
+ return new SortVersion(
+ nlsVersion.dwNLSVersion,
+ nlsVersion.dwEffectiveId == 0 ? LCID : nlsVersion.dwEffectiveId,
+ nlsVersion.guidCustomVersion);
+ }
+
+#if CORECLR
+ // 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);
+#endif
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.cs b/src/mscorlib/src/System/Globalization/CompareInfo.cs
index 6c2230b66b..285a81d906 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.cs
@@ -12,57 +12,28 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
- //
- // We pass all of the sorting calls to the native side, preferrably to the OS to do
- // the actual work.
- //
-
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Reflection;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Threading;
- using Microsoft.Win32;
- using System.Security;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- //
- // Options can be used during string comparison.
- //
- // Native implementation (COMNlsInfo.cpp & SortingTable.cpp) relies on the values of these,
- // If you change the values below, be sure to change the values in native part as well.
- //
-
-
-[Serializable]
+using System.Reflection;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+
+namespace System.Globalization
+{
[Flags]
+ [Serializable]
public enum CompareOptions
{
- None = 0x00000000,
- IgnoreCase = 0x00000001,
- IgnoreNonSpace = 0x00000002,
- IgnoreSymbols = 0x00000004,
- IgnoreKanaType = 0x00000008, // ignore kanatype
- IgnoreWidth = 0x00000010, // ignore width
- OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
- StringSort = 0x20000000, // use string sort method
- Ordinal = 0x40000000, // This flag can not be used with other flags.
-
- // StopOnNull = 0x10000000,
-
- // StopOnNull is defined in SortingTable.h, but we didn't enable this option here.
- // Do not use this value for other flags accidentally.
+ None = 0x00000000,
+ IgnoreCase = 0x00000001,
+ IgnoreNonSpace = 0x00000002,
+ IgnoreSymbols = 0x00000004,
+ IgnoreKanaType = 0x00000008, // ignore kanatype
+ IgnoreWidth = 0x00000010, // ignore width
+ OrdinalIgnoreCase = 0x10000000, // This flag can not be used with other flags.
+ StringSort = 0x20000000, // use string sort method
+ Ordinal = 0x40000000, // This flag can not be used with other flags.
}
-
[Serializable]
public partial class CompareInfo : IDeserializationCallback
{
@@ -81,6 +52,11 @@ namespace System.Globalization {
~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType);
+ // Mask used to check if we have the right flags.
+ private const CompareOptions ValidSortkeyCtorMaskOffFlags =
+ ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreNonSpace |
+ CompareOptions.IgnoreWidth | CompareOptions.IgnoreKanaType | CompareOptions.StringSort);
+
//
// CompareInfos have an interesting identity. They are attached to the locale that created them,
// ie: en-US would have an en-US sort. For haw-US (custom), then we serialize it as haw-US.
@@ -88,33 +64,21 @@ namespace System.Globalization {
// locale, which is what SCOMPAREINFO does.
[OptionalField(VersionAdded = 2)]
- private String m_name; // The name used to construct this CompareInfo
-
+ private string _name; // The name used to construct this CompareInfo
[NonSerialized]
- private String m_sortName; // The name that defines our behavior
+ private string _sortName; // The name that defines our behavior
- [NonSerialized]
- private IntPtr m_dataHandle;
+ [OptionalField(VersionAdded = 3)]
+ private SortVersion _sortVersion;
- [NonSerialized]
- private IntPtr m_handleOrigin;
+ // _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;
- ////////////////////////////////////////////////////////////////////////
- //
- // CompareInfo Constructor
- //
- //
- ////////////////////////////////////////////////////////////////////////
- // Constructs an instance that most closely corresponds to the NLS locale
- // identifier.
internal CompareInfo(CultureInfo culture)
{
- this.m_name = culture.m_name;
- this.m_sortName = culture.SortName;
-
- IntPtr handleOrigin;
- this.m_dataHandle = InternalInitSortHandle(m_sortName, out handleOrigin);
- this.m_handleOrigin = handleOrigin;
+ _name = culture._name;
+ InitSort(culture);
}
/*=================================GetCompareInfo==========================
@@ -122,49 +86,52 @@ namespace System.Globalization {
** Warning: The assembly versioning mechanism is dead!
**Returns: The CompareInfo for the specified culture.
**Arguments:
- ** culture the ID of the culture
+ ** culture the ID of the culture
** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if culture is invalid.
============================================================================*/
-#if FEATURE_USE_LCID
// Assembly constructor should be deprecated, we don't act on the assembly information any more
- public static CompareInfo GetCompareInfo(int culture, Assembly assembly){
+ public static CompareInfo GetCompareInfo(int culture, Assembly assembly)
+ {
// Parameter checking.
- if (assembly == null) {
+ if (assembly == null)
+ {
throw new ArgumentNullException(nameof(assembly));
}
- if (assembly!=typeof(Object).Module.Assembly) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OnlyMscorlib"));
+ if (assembly != typeof(Object).Module.Assembly)
+ {
+ throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
Contract.EndContractBlock();
return GetCompareInfo(culture);
}
-#endif
-
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo constructed from the data table in the specified assembly for the specified culture.
** The purpose of this method is to provide version for CompareInfo tables.
**Returns: The CompareInfo for the specified culture.
**Arguments:
- ** name the name of the culture
- ** assembly the assembly which contains the sorting table.
+ ** name the name of the culture
+ ** assembly the assembly which contains the sorting table.
**Exceptions:
** ArugmentNullException when the assembly is null
** ArgumentException if name is invalid.
============================================================================*/
// Assembly constructor should be deprecated, we don't act on the assembly information any more
- public static CompareInfo GetCompareInfo(String name, Assembly assembly){
- if (name == null || assembly == null) {
+ public static CompareInfo GetCompareInfo(string name, Assembly assembly)
+ {
+ if (name == null || assembly == null)
+ {
throw new ArgumentNullException(name == null ? nameof(name) : nameof(assembly));
}
Contract.EndContractBlock();
- if (assembly!=typeof(Object).Module.Assembly) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OnlyMscorlib"));
+ if (assembly != typeof(Object).Module.Assembly)
+ {
+ throw new ArgumentException(SR.Argument_OnlyMscorlib);
}
return GetCompareInfo(name);
@@ -179,20 +146,17 @@ namespace System.Globalization {
**Exceptions:
** ArgumentException if culture is invalid.
============================================================================*/
-
-#if FEATURE_USE_LCID
// People really shouldn't be calling LCID versions, no custom support
public static CompareInfo GetCompareInfo(int culture)
{
if (CultureData.IsCustomCultureId(culture))
{
// Customized culture cannot be created by the LCID.
- throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", nameof(culture)));
+ throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, nameof(culture));
}
return CultureInfo.GetCultureInfo(culture).CompareInfo;
}
-#endif
/*=================================GetCompareInfo==========================
**Action: Get the CompareInfo for the specified culture.
@@ -203,7 +167,7 @@ namespace System.Globalization {
** ArgumentException if name is invalid.
============================================================================*/
- public static CompareInfo GetCompareInfo(String name)
+ public static CompareInfo GetCompareInfo(string name)
{
if (name == null)
{
@@ -214,64 +178,51 @@ namespace System.Globalization {
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
- public static bool IsSortable(char ch) {
- return(IsSortable(ch.ToString()));
+ public static unsafe bool IsSortable(char ch)
+ {
+ if (GlobalizationMode.Invariant)
+ {
+ return true;
+ }
+ char *pChar = &ch;
+ return IsSortable(pChar, 1);
}
- public static bool IsSortable(String text) {
- if (text == null) {
+ public static unsafe bool IsSortable(string text)
+ {
+ if (text == null)
+ {
// A null param is invalid here.
throw new ArgumentNullException(nameof(text));
}
- if (0 == text.Length) {
+ if (text.Length == 0)
+ {
// A zero length string is not invalid, but it is also not sortable.
- return(false);
+ return (false);
}
- CompareInfo c = CultureInfo.InvariantCulture.CompareInfo;
-
- return (InternalIsSortable(c.m_dataHandle, c.m_handleOrigin, c.m_sortName, text, text.Length));
+ if (GlobalizationMode.Invariant)
+ {
+ return true;
+ }
+
+ fixed (char *pChar = text)
+ {
+ return IsSortable(pChar, text.Length);
+ }
}
-#region Serialization
- // the following fields are defined to keep the compatibility with Whidbey.
- // don't change/remove the names/types of these fields.
-#if FEATURE_USE_LCID
- [OptionalField(VersionAdded = 1)]
- private int win32LCID; // mapped sort culture id of this instance
- private int culture; // the culture ID used to create this instance.
-#endif
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
- this.m_name = null;
+ _name = null;
}
- private void OnDeserialized()
+ void IDeserializationCallback.OnDeserialization(Object sender)
{
- CultureInfo ci;
- // If we didn't have a name, use the LCID
- if (this.m_name == null)
- {
-#if FEATURE_USE_LCID
- // From whidbey, didn't have a name
- ci = CultureInfo.GetCultureInfo(this.culture);
- this.m_name = ci.m_name;
- this.m_sortName = ci.SortName;
-#endif
- }
- else
- {
- ci = CultureInfo.GetCultureInfo(m_name);
- this.m_sortName = ci.SortName;
- }
-
- IntPtr handleOrigin;
- this.m_dataHandle = InternalInitSortHandle(m_sortName, out handleOrigin);
- this.m_handleOrigin = handleOrigin;
-
+ OnDeserialized();
}
[OnDeserialized]
@@ -280,23 +231,16 @@ namespace System.Globalization {
OnDeserialized();
}
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-#if FEATURE_USE_LCID
- // This is merely for serialization compatibility with Whidbey/Orcas, it can go away when we don't want that compat any more.
- culture = CultureInfo.GetCultureInfo(this.Name).LCID; // This is the lcid of the constructing culture (still have to dereference to get target sort)
- Debug.Assert(m_name != null, "CompareInfo.OnSerializing - expected m_name to be set already");
-#endif
- }
-
- void IDeserializationCallback.OnDeserialization(Object sender)
+ private void OnDeserialized()
{
- OnDeserialized();
+ if (_name != null)
+ {
+ InitSort(CultureInfo.GetCultureInfo(_name));
+ }
}
-#endregion Serialization
-
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx) { }
///////////////////////////----- Name -----/////////////////////////////////
//
@@ -311,65 +255,20 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
- public virtual String Name
+ public virtual string Name
{
get
{
- Debug.Assert(m_name != null, "CompareInfo.Name Expected m_name to be set");
- return (m_sortName);
- }
- }
+ Debug.Assert(_name != null, "CompareInfo.Name Expected _name to be set");
+ if (_name == "zh-CHT" || _name == "zh-CHS")
+ {
+ return _name;
+ }
- // These flags are used in the native Win32. so we need to map the managed options to those flags
- private const int LINGUISTIC_IGNORECASE = 0x00000010; // linguistically appropriate 'ignore case'
- private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead)
- private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal.
- private const int LINGUISTIC_IGNOREDIACRITIC = 0x00000020; // linguistically appropriate 'ignore nonspace'
- private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead)
- private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols.
- private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character.
- private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols.
- private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal (handled by Comnlsinfo)
- internal const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing
-
-
- private const int RESERVED_FIND_ASCII_STRING = 0x20000000; // This flag used only to tell the sorting DLL can assume the string characters are in ASCII.
-
- [Pure]
- internal static int GetNativeCompareFlags(CompareOptions options)
- {
- // some NLS VM functions can handle COMPARE_OPTIONS_ORDINAL
- // in which case options should be simply cast to int instead of using this function
- // Does not look like the best approach to me but for now I am going to leave it as it is
- Debug.Assert(options != CompareOptions.OrdinalIgnoreCase, "[CompareInfo.GetNativeCompareFlags]CompareOptions.OrdinalIgnoreCase should be handled separately");
-
- // Use "linguistic casing" by default (load the culture's casing exception tables)
- int nativeCompareFlags = NORM_LINGUISTIC_CASING;
-
- if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; }
- if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; }
- if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; }
- if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; }
- if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; }
- if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; }
-
- // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag
- if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; }
-
- Debug.Assert(((options & ~(CompareOptions.IgnoreCase |
- CompareOptions.IgnoreKanaType |
- CompareOptions.IgnoreNonSpace |
- CompareOptions.IgnoreSymbols |
- CompareOptions.IgnoreWidth |
- CompareOptions.StringSort)) == 0) ||
- (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled");
-
- Debug.Assert((nativeCompareFlags & RESERVED_FIND_ASCII_STRING) == 0, "[CompareInfo.GetNativeCompareFlags] RESERVED_FIND_ASCII_STRING shouldn't be set here");
-
- return nativeCompareFlags;
+ return _sortName;
+ }
}
-
////////////////////////////////////////////////////////////////////////
//
// Compare
@@ -381,14 +280,13 @@ namespace System.Globalization {
//
////////////////////////////////////////////////////////////////////////
-
- public virtual int Compare(String string1, String string2)
+ public virtual int Compare(string string1, string string2)
{
return (Compare(string1, string2, CompareOptions.None));
}
- public unsafe virtual int Compare(String string1, String string2, CompareOptions options){
-
+ public unsafe virtual int Compare(string string1, string string2, CompareOptions options)
+ {
if (options == CompareOptions.OrdinalIgnoreCase)
{
return String.Compare(string1, string2, StringComparison.OrdinalIgnoreCase);
@@ -399,29 +297,41 @@ namespace System.Globalization {
{
if (options != CompareOptions.Ordinal)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"), nameof(options));
- }
+ throw new ArgumentException(SR.Argument_CompareOptionOrdinal, nameof(options));
+ }
+
return String.CompareOrdinal(string1, string2);
- }
+ }
if ((options & ValidCompareMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//Our paradigm is that null sorts less than any other string and
//that two nulls sort as equal.
- if (string1 == null) {
- if (string2 == null) {
+ if (string1 == null)
+ {
+ if (string2 == null)
+ {
return (0); // Equal
}
return (-1); // null < non-null
}
- if (string2 == null) {
+ if (string2 == null)
+ {
return (1); // non-null > null
}
- return InternalCompareString(m_dataHandle, m_handleOrigin, m_sortName, string1, 0, string1.Length, string2, 0, string2.Length, GetNativeCompareFlags(options));
+ if (_invariantMode)
+ {
+ if ((options & CompareOptions.IgnoreCase) != 0)
+ return CompareOrdinalIgnoreCase(string1, 0, string1.Length, string2, 0, string2.Length);
+
+ return String.CompareOrdinal(string1, string2);
+ }
+
+ return CompareString(string1, 0, string1.Length, string2, 0, string2.Length, options);
}
@@ -438,63 +348,63 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2)
+ public unsafe virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2)
{
return Compare(string1, offset1, length1, string2, offset2, length2, 0);
}
- public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2, CompareOptions options)
+ public virtual int Compare(string string1, int offset1, string string2, int offset2, CompareOptions options)
{
- return Compare(string1, offset1, string1 == null ? 0 : string1.Length-offset1,
- string2, offset2, string2 == null ? 0 : string2.Length-offset2, options);
+ return Compare(string1, offset1, string1 == null ? 0 : string1.Length - offset1,
+ string2, offset2, string2 == null ? 0 : string2.Length - offset2, options);
}
- public unsafe virtual int Compare(String string1, int offset1, String string2, int offset2)
+ public virtual int Compare(string string1, int offset1, string string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
- public unsafe virtual int Compare(String string1, int offset1, int length1, String string2, int offset2, int length2, CompareOptions options)
+ public virtual int Compare(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
- int result = String.Compare(string1, offset1, string2, offset2, length1<length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
+ int result = String.Compare(string1, offset1, string2, offset2, length1 < length2 ? length1 : length2, StringComparison.OrdinalIgnoreCase);
if ((length1 != length2) && result == 0)
- return (length1 > length2? 1: -1);
+ return (length1 > length2 ? 1 : -1);
return (result);
}
// Verify inputs
if (length1 < 0 || length2 < 0)
{
- throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException((length1 < 0) ? nameof(length1) : nameof(length2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 < 0 || offset2 < 0)
{
- throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException((offset1 < 0) ? nameof(offset1) : nameof(offset2), SR.ArgumentOutOfRange_NeedPosNum);
}
if (offset1 > (string1 == null ? 0 : string1.Length) - length1)
{
- throw new ArgumentOutOfRangeException(nameof(string1), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(string1), SR.ArgumentOutOfRange_OffsetLength);
}
if (offset2 > (string2 == null ? 0 : string2.Length) - length2)
{
- throw new ArgumentOutOfRangeException(nameof(string2), Environment.GetResourceString("ArgumentOutOfRange_OffsetLength"));
+ throw new ArgumentOutOfRangeException(nameof(string2), SR.ArgumentOutOfRange_OffsetLength);
}
if ((options & CompareOptions.Ordinal) != 0)
{
if (options != CompareOptions.Ordinal)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_CompareOptionOrdinal"),
+ throw new ArgumentException(SR.Argument_CompareOptionOrdinal,
nameof(options));
}
}
else if ((options & ValidCompareMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
//
@@ -515,12 +425,89 @@ namespace System.Globalization {
if (options == CompareOptions.Ordinal)
{
- return string.CompareOrdinalHelper(string1, offset1, length1, string2, offset2, length2);
+ return CompareOrdinal(string1, offset1, length1,
+ string2, offset2, length2);
+ }
+
+ if (_invariantMode)
+ {
+ if ((options & CompareOptions.IgnoreCase) != 0)
+ return CompareOrdinalIgnoreCase(string1, offset1, length1, string2, offset2, length2);
+
+ return CompareOrdinal(string1, offset1, length1, string2, offset2, length2);
+ }
+
+ return CompareString(string1, offset1, length1,
+ string2, offset2, length2,
+ options);
+ }
+
+ private static int CompareOrdinal(string string1, int offset1, int length1, string string2, int offset2, int length2)
+ {
+ int result = String.CompareOrdinal(string1, offset1, string2, offset2,
+ (length1 < length2 ? length1 : length2));
+ if ((length1 != length2) && result == 0)
+ {
+ return (length1 > length2 ? 1 : -1);
+ }
+ return (result);
+ }
+
+ //
+ // CompareOrdinalIgnoreCase compare two string ordinally with ignoring the case.
+ // it assumes the strings are Ascii string till we hit non Ascii character in strA or strB and then we continue the comparison by
+ // calling the OS.
+ //
+ internal static unsafe int CompareOrdinalIgnoreCase(string strA, int indexA, int lengthA, string strB, int indexB, int lengthB)
+ {
+ Debug.Assert(indexA + lengthA <= strA.Length);
+ Debug.Assert(indexB + lengthB <= strB.Length);
+
+ int length = Math.Min(lengthA, lengthB);
+ int range = length;
+
+ fixed (char* ap = strA) fixed (char* bp = strB)
+ {
+ char* a = ap + indexA;
+ char* b = bp + indexB;
+
+ // in InvariantMode we support all range and not only the ascii characters.
+ char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x80);
+
+ while (length != 0 && (*a <= maxChar) && (*b <= maxChar))
+ {
+ int charA = *a;
+ int charB = *b;
+
+ if (charA == charB)
+ {
+ a++; b++;
+ length--;
+ continue;
+ }
+
+ // uppercase both chars - notice that we need just one compare per char
+ if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20;
+ if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20;
+
+ // Return the (case-insensitive) difference between them.
+ if (charA != charB)
+ return charA - charB;
+
+ // Next char
+ a++; b++;
+ length--;
+ }
+
+ if (length == 0)
+ return lengthA - lengthB;
+
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ range -= length;
+
+ return CompareStringOrdinalIgnoreCase(a, lengthA - range, b, lengthB - range);
}
- return InternalCompareString(this.m_dataHandle, this.m_handleOrigin, this.m_sortName,
- string1, offset1, length1,
- string2, offset2, length2,
- GetNativeCompareFlags(options));
}
////////////////////////////////////////////////////////////////////////
@@ -531,22 +518,25 @@ namespace System.Globalization {
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
-
-
- public unsafe virtual bool IsPrefix(String source, String prefix, CompareOptions options)
+ public virtual bool IsPrefix(string source, string prefix, CompareOptions options)
{
- if (source == null || prefix == null) {
+ if (source == null || prefix == null)
+ {
throw new ArgumentNullException((source == null ? nameof(source) : nameof(prefix)),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
- int prefixLen = prefix.Length;
- if (prefixLen == 0)
+ if (prefix.Length == 0)
{
return (true);
}
+ if (source.Length == 0)
+ {
+ return false;
+ }
+
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
@@ -557,26 +547,24 @@ namespace System.Globalization {
return source.StartsWith(prefix, StringComparison.Ordinal);
}
- if ((options & ValidIndexMaskOffFlags) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ if ((options & ValidIndexMaskOffFlags) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
+ if (_invariantMode)
+ {
+ return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
+ }
- // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
- // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
-
- return (InternalFindNLSStringEx(
- m_dataHandle, m_handleOrigin, m_sortName,
- GetNativeCompareFlags(options) | Win32Native.FIND_STARTSWITH | ((source.IsAscii() && prefix.IsAscii()) ? RESERVED_FIND_ASCII_STRING : 0),
- source, source.Length, 0, prefix, prefix.Length) > -1);
+ return StartsWith(source, prefix, options);
}
- public virtual bool IsPrefix(String source, String prefix)
+ public virtual bool IsPrefix(string source, string prefix)
{
return (IsPrefix(source, prefix, 0));
}
-
////////////////////////////////////////////////////////////////////////
//
// IsSuffix
@@ -585,44 +573,50 @@ namespace System.Globalization {
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
-
-
- public unsafe virtual bool IsSuffix(String source, String suffix, CompareOptions options)
+ public virtual bool IsSuffix(string source, string suffix, CompareOptions options)
{
- if (source == null || suffix == null) {
+ if (source == null || suffix == null)
+ {
throw new ArgumentNullException((source == null ? nameof(source) : nameof(suffix)),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
- int suffixLen = suffix.Length;
- if (suffixLen == 0)
+ if (suffix.Length == 0)
{
return (true);
}
- if (options == CompareOptions.OrdinalIgnoreCase) {
+ if (source.Length == 0)
+ {
+ return false;
+ }
+
+ if (options == CompareOptions.OrdinalIgnoreCase)
+ {
return source.EndsWith(suffix, StringComparison.OrdinalIgnoreCase);
}
- if (options == CompareOptions.Ordinal) {
+ if (options == CompareOptions.Ordinal)
+ {
return source.EndsWith(suffix, StringComparison.Ordinal);
}
- if ((options & ValidIndexMaskOffFlags) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ if ((options & ValidIndexMaskOffFlags) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
+ }
+
+ if (_invariantMode)
+ {
+ return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
- // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
- // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
- return InternalFindNLSStringEx(
- m_dataHandle, m_handleOrigin, m_sortName,
- GetNativeCompareFlags(options) | Win32Native.FIND_ENDSWITH | ((source.IsAscii() && suffix.IsAscii()) ? RESERVED_FIND_ASCII_STRING : 0),
- source, source.Length, source.Length - 1, suffix, suffix.Length) >= 0;
+ return EndsWith(source, suffix, options);
}
- public virtual bool IsSuffix(String source, String suffix)
+ public virtual bool IsSuffix(string source, string suffix)
{
return (IsSuffix(source, suffix, 0));
}
@@ -641,9 +635,9 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public unsafe virtual int IndexOf(String source, char value)
+ public virtual int IndexOf(string source, char value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -651,9 +645,9 @@ namespace System.Globalization {
}
- public unsafe virtual int IndexOf(String source, String value)
+ public virtual int IndexOf(string source, string value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -661,9 +655,9 @@ namespace System.Globalization {
}
- public unsafe virtual int IndexOf(String source, char value, CompareOptions options)
+ public virtual int IndexOf(string source, char value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -671,17 +665,16 @@ namespace System.Globalization {
}
- public unsafe virtual int IndexOf(String source, String value, CompareOptions options)
+ public virtual int IndexOf(string source, string value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
return IndexOf(source, value, 0, source.Length, options);
}
-
- public unsafe virtual int IndexOf(String source, char value, int startIndex)
+ public virtual int IndexOf(string source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
@@ -690,8 +683,7 @@ namespace System.Globalization {
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
-
- public unsafe virtual int IndexOf(String source, String value, int startIndex)
+ public virtual int IndexOf(string source, string value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
@@ -700,8 +692,7 @@ namespace System.Globalization {
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
-
- public unsafe virtual int IndexOf(String source, char value, int startIndex, CompareOptions options)
+ public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
@@ -711,7 +702,7 @@ namespace System.Globalization {
}
- public unsafe virtual int IndexOf(String source, String value, int startIndex, CompareOptions options)
+ public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
@@ -721,28 +712,28 @@ namespace System.Globalization {
}
- public unsafe virtual int IndexOf(String source, char value, int startIndex, int count)
+ public virtual int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
- public unsafe virtual int IndexOf(String source, String value, int startIndex, int count)
+ public virtual int IndexOf(string source, string value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
- public unsafe virtual int IndexOf(String source, char value, int startIndex, int count, CompareOptions options)
+ public unsafe virtual int IndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
throw new ArgumentNullException(nameof(source));
if (startIndex < 0 || startIndex > source.Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > source.Length - count)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
Contract.EndContractBlock();
if (options == CompareOptions.OrdinalIgnoreCase)
@@ -753,18 +744,16 @@ namespace System.Globalization {
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
-
- // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
- // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
- return InternalFindNLSStringEx(
- m_dataHandle, m_handleOrigin, m_sortName,
- GetNativeCompareFlags(options) | Win32Native.FIND_FROMSTART | ((source.IsAscii() && (value <= '\x007f')) ? RESERVED_FIND_ASCII_STRING : 0),
- source, count, startIndex, new String(value, 1), 1);
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
+
+ if (_invariantMode)
+ return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
+
+ return IndexOfCore(source, new string(value, 1), startIndex, count, options, null);
}
- public unsafe virtual int IndexOf(String source, String value, int startIndex, int count, CompareOptions options)
+ public unsafe virtual int IndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Validate inputs
if (source == null)
@@ -774,7 +763,7 @@ namespace System.Globalization {
if (startIndex > source.Length)
{
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
@@ -791,28 +780,36 @@ namespace System.Globalization {
if (startIndex < 0)
{
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
if (count < 0 || startIndex > source.Length - count)
- throw new ArgumentOutOfRangeException(nameof(count),Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
- return source.IndexOf(value, startIndex, count, StringComparison.OrdinalIgnoreCase);
+ return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Validate CompareOptions
// Ordinal can't be selected with other flags
if ((options & ValidIndexMaskOffFlags) != 0 && (options != CompareOptions.Ordinal))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
-
- // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
- // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
- return InternalFindNLSStringEx(
- m_dataHandle, m_handleOrigin, m_sortName,
- GetNativeCompareFlags(options) | Win32Native.FIND_FROMSTART | ((source.IsAscii() && value.IsAscii()) ? RESERVED_FIND_ASCII_STRING : 0),
- source, count, startIndex, value, value.Length);
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
+
+ if (_invariantMode)
+ return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
+
+ return IndexOfCore(source, value, startIndex, count, options, null);
+ }
+
+ internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ if (_invariantMode)
+ {
+ return InvariantIndexOf(source, value, startIndex, count, ignoreCase);
+ }
+
+ return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
@@ -829,21 +826,20 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public unsafe virtual int LastIndexOf(String source, char value)
+ public virtual int LastIndexOf(String source, char value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
- return LastIndexOf(source, value, source.Length - 1,
- source.Length, CompareOptions.None);
+ return LastIndexOf(source, value, source.Length - 1, source.Length, CompareOptions.None);
}
- public virtual int LastIndexOf(String source, String value)
+ public virtual int LastIndexOf(string source, string value)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -853,9 +849,9 @@ namespace System.Globalization {
}
- public virtual int LastIndexOf(String source, char value, CompareOptions options)
+ public virtual int LastIndexOf(string source, char value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -864,58 +860,55 @@ namespace System.Globalization {
source.Length, options);
}
- public unsafe virtual int LastIndexOf(String source, String value, CompareOptions options)
+ public virtual int LastIndexOf(string source, string value, CompareOptions options)
{
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
// Can't start at negative index, so make sure we check for the length == 0 case.
- return LastIndexOf(source, value, source.Length - 1,
- source.Length, options);
+ return LastIndexOf(source, value, source.Length - 1, source.Length, options);
}
-
- public unsafe virtual int LastIndexOf(String source, char value, int startIndex)
+ public virtual int LastIndexOf(string source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
- public unsafe virtual int LastIndexOf(String source, String value, int startIndex)
+ public virtual int LastIndexOf(string source, string value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
-
- public unsafe virtual int LastIndexOf(String source, char value, int startIndex, CompareOptions options)
+ public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
- public unsafe virtual int LastIndexOf(String source, String value, int startIndex, CompareOptions options)
+ public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
- public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count)
+ public virtual int LastIndexOf(string source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
- public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count)
+ public virtual int LastIndexOf(string source, string value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
- public unsafe virtual int LastIndexOf(String source, char value, int startIndex, int count, CompareOptions options)
+ public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
- if (source==null)
+ if (source == null)
throw new ArgumentNullException(nameof(source));
Contract.EndContractBlock();
@@ -924,7 +917,7 @@ namespace System.Globalization {
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
@@ -932,7 +925,7 @@ namespace System.Globalization {
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
@@ -944,23 +937,21 @@ namespace System.Globalization {
// 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
return source.LastIndexOf(value.ToString(), startIndex, count, StringComparison.OrdinalIgnoreCase);
}
- // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
- // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
- return InternalFindNLSStringEx(
- m_dataHandle, m_handleOrigin, m_sortName,
- GetNativeCompareFlags(options) | Win32Native.FIND_FROMEND | ((source.IsAscii() && (value <= '\x007f')) ? RESERVED_FIND_ASCII_STRING : 0),
- source, count, startIndex, new String(value, 1), 1);
+ if (_invariantMode)
+ return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
+
+ return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
- public unsafe virtual int LastIndexOf(String source, String value, int startIndex, int count, CompareOptions options)
+ public virtual int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
@@ -974,7 +965,7 @@ namespace System.Globalization {
if ((options & ValidIndexMaskOffFlags) != 0 &&
(options != CompareOptions.Ordinal) &&
(options != CompareOptions.OrdinalIgnoreCase))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
// Special case for 0 length input strings
if (source.Length == 0 && (startIndex == -1 || startIndex == 0))
@@ -982,7 +973,7 @@ namespace System.Globalization {
// Make sure we're not out of range
if (startIndex < 0 || startIndex > source.Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
// Make sure that we allow startIndex == source.Length
if (startIndex == source.Length)
@@ -998,21 +989,28 @@ namespace System.Globalization {
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
if (options == CompareOptions.OrdinalIgnoreCase)
{
- return source.LastIndexOf(value, startIndex, count, StringComparison.OrdinalIgnoreCase);
+ return LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
- // to let the sorting DLL do the call optimization in case of Ascii strings, we check if the strings are in Ascii and then send the flag RESERVED_FIND_ASCII_STRING to
- // the sorting DLL API SortFindString so sorting DLL don't have to check if the string is Ascii with every call to SortFindString.
- return InternalFindNLSStringEx(
- m_dataHandle, m_handleOrigin, m_sortName,
- GetNativeCompareFlags(options) | Win32Native.FIND_FROMEND | ((source.IsAscii() && value.IsAscii()) ? RESERVED_FIND_ASCII_STRING : 0),
- source, count, startIndex, value, value.Length);
+ if (_invariantMode)
+ return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
+
+ return LastIndexOfCore(source, value, startIndex, count, options);
}
+ internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
+ {
+ if (_invariantMode)
+ {
+ return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase);
+ }
+
+ return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
+ }
////////////////////////////////////////////////////////////////////////
//
@@ -1021,74 +1019,23 @@ namespace System.Globalization {
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
- public unsafe virtual SortKey GetSortKey(String source, CompareOptions options)
+ public virtual SortKey GetSortKey(string source, CompareOptions options)
{
+ if (_invariantMode)
+ return InvariantCreateSortKey(source, options);
+
return CreateSortKey(source, options);
}
- public unsafe virtual SortKey GetSortKey(String source)
+ public virtual SortKey GetSortKey(string source)
{
- return CreateSortKey(source, CompareOptions.None);
- }
+ if (_invariantMode)
+ return InvariantCreateSortKey(source, CompareOptions.None);
- private SortKey CreateSortKey(String source, CompareOptions options)
- {
- if (source==null) { throw new ArgumentNullException(nameof(source)); }
- Contract.EndContractBlock();
-
- // Mask used to check if we have the right flags.
- const CompareOptions ValidSortkeyCtorMaskOffFlags = ~(CompareOptions.IgnoreCase |
- CompareOptions.IgnoreSymbols |
- CompareOptions.IgnoreNonSpace |
- CompareOptions.IgnoreWidth |
- CompareOptions.IgnoreKanaType |
- CompareOptions.StringSort);
-
- if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
- }
- byte[] keyData = null;
- // The OS doesn't have quite the same behavior so we have to test for empty inputs
- if (String.IsNullOrEmpty(source))
- {
- // Empty strings get an empty sort key
- keyData = EmptyArray<Byte>.Value;
- // Fake value to test though so we can verify our flags
- source = "\x0000";
- }
-
- int flags = GetNativeCompareFlags(options);
-
- // Go ahead and call the OS
- // First get the count
- int length = InternalGetSortKey(m_dataHandle, m_handleOrigin, m_sortName, flags, source, source.Length, null, 0);
-
- // If there was an error, return an error
- if (length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(source));
- }
-
- // If input was empty, return the empty byte[] we made earlier and skip this
- if (keyData == null)
- {
- // Make an appropriate byte array
- keyData = new byte[length];
-
- // Fill up the array
- length = InternalGetSortKey(m_dataHandle, m_handleOrigin, m_sortName, flags, source, source.Length, keyData, keyData.Length);
- }
- else
- {
- source = String.Empty; // back to original
- }
-
- return new SortKey(Name, source, options, keyData);
+ return CreateSortKey(source, CompareOptions.None);
}
-
////////////////////////////////////////////////////////////////////////
//
// Equals
@@ -1129,34 +1076,6 @@ namespace System.Globalization {
return (this.Name.GetHashCode());
}
- //
- // return hash value for the string according to the input CompareOptions
- //
-
- public virtual int GetHashCode(string source, CompareOptions options)
- {
- if (source == null)
- {
- throw new ArgumentNullException(nameof(source));
- }
-
- if (options == CompareOptions.Ordinal)
- {
- return source.GetHashCode();
- }
-
- if (options == CompareOptions.OrdinalIgnoreCase)
- {
- return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
- }
-
- //
- // GetHashCodeOfString does more parameters validation. basically will throw when
- // having Ordinal, OrdinalIgnoreCase and StringSort
- //
-
- return GetHashCodeOfString(source, options, false, 0);
- }
////////////////////////////////////////////////////////////////////////
//
@@ -1184,33 +1103,46 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
internal int GetHashCodeOfString(string source, CompareOptions options)
{
- return GetHashCodeOfString(source, options, false, 0);
- }
-
- internal int GetHashCodeOfString(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
- {
//
// Parameter validation
//
- if(null == source)
+ if (null == source)
{
throw new ArgumentNullException(nameof(source));
}
if ((options & ValidHashCodeOfStringMaskOffFlags) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag"), nameof(options));
+ throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
Contract.EndContractBlock();
- if(0 == source.Length)
+ return GetHashCodeOfStringCore(source, options);
+ }
+
+ public virtual int GetHashCode(string source, CompareOptions options)
+ {
+ if (source == null)
+ {
+ throw new ArgumentNullException(nameof(source));
+ }
+
+ if (options == CompareOptions.Ordinal)
{
- return(0);
+ return source.GetHashCode();
}
+ if (options == CompareOptions.OrdinalIgnoreCase)
+ {
+ return TextInfo.GetHashCodeOrdinalIgnoreCase(source);
+ }
+
+ //
+ // GetHashCodeOfString does more parameters validation. basically will throw when
+ // having Ordinal, OrdinalIgnoreCase and StringSort
//
- ////////////////////////////////////////////////////////////////////////
- return (InternalGetGlobalizedHashCode(m_dataHandle, m_handleOrigin, this.m_sortName, source, source.Length, GetNativeCompareFlags(options), forceRandomizedHashing, additionalEntropy));
+
+ return GetHashCodeOfString(source, options);
}
////////////////////////////////////////////////////////////////////////
@@ -1221,82 +1153,41 @@ namespace System.Globalization {
// CompareInfo.
//
////////////////////////////////////////////////////////////////////////
-
-
- public override String ToString()
+ public override string ToString()
{
return ("CompareInfo - " + this.Name);
}
-#if FEATURE_USE_LCID
- public int LCID
+ public SortVersion Version
{
get
{
- return CultureInfo.GetCultureInfo(this.Name).LCID;
- }
- }
-#endif
+ if (_sortVersion == null)
+ {
+ if (_invariantMode)
+ {
+ _sortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
+ (byte) (CultureInfo.LOCALE_INVARIANT >> 24),
+ (byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
+ (byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
+ (byte) (CultureInfo.LOCALE_INVARIANT & 0xFF)));
+ }
+ else
+ {
+ _sortVersion = GetSortVersion();
+ }
+ }
- internal static IntPtr InternalInitSortHandle(String localeName, out IntPtr handleOrigin)
- {
- return NativeInternalInitSortHandle(localeName, out handleOrigin);
+ return _sortVersion;
+ }
}
- [OptionalField(VersionAdded = 3)]
- private SortVersion m_SortVersion;
-
- public SortVersion Version
+ public int LCID
{
get
{
- if(m_SortVersion == null)
- {
- Win32Native.NlsVersionInfoEx v = new Win32Native.NlsVersionInfoEx();
- v.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Win32Native.NlsVersionInfoEx));
- InternalGetNlsVersionEx(m_dataHandle, m_handleOrigin, m_sortName, ref v);
- m_SortVersion = new SortVersion(v.dwNLSVersion, (v.dwEffectiveId != 0) ? v.dwEffectiveId : LCID, v.guidCustomVersion);
- }
-
- return m_SortVersion;
+ return CultureInfo.GetCultureInfo(Name).LCID;
}
}
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool InternalGetNlsVersionEx(IntPtr handle, IntPtr handleOrigin, String localeName, ref Win32Native.NlsVersionInfoEx lpNlsVersionInformation);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern IntPtr NativeInternalInitSortHandle(String localeName, out IntPtr handleOrigin);
-
- // 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, IntPtr handleOrigin, string localeName, string source, int length, int dwFlags, bool forceRandomizedHashing, long additionalEntropy);
-
- // Use native API calls to see if this string is entirely defined -- COMNlsInfo::InternalIsSortable
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool InternalIsSortable(IntPtr handle, IntPtr handleOrigin, String localeName, String source, int length);
-
- // Compare a string using the native API calls -- COMNlsInfo::InternalCompareString
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern int InternalCompareString(IntPtr handle, IntPtr handleOrigin, String localeName, String string1, int offset1, int length1,
- String string2, int offset2, int length2, int flags);
-
- // InternalFindNLSStringEx parameters is not exactly matching kernel32::FindNLSStringEx parameters.
- // Call through to NewApis::FindNLSStringEx so we can get the right behavior
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern int InternalFindNLSStringEx(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, int startIndex, string target, int targetCount);
-
- // Call through to NewAPis::LCMapStringEx so we can get appropriate behavior for all platforms
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern int InternalGetSortKey(IntPtr handle, IntPtr handleOrigin, String localeName, int flags, String source, int sourceCount, byte[] target, int targetCount);
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.Unix.cs b/src/mscorlib/src/System/Globalization/CultureData.Unix.cs
new file mode 100644
index 0000000000..4f685de580
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CultureData.Unix.cs
@@ -0,0 +1,431 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+
+namespace System.Globalization
+{
+ internal partial class CultureData
+ {
+ // ICU constants
+ const int ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY = 100; // max size of keyword or value
+ const int ICU_ULOC_FULLNAME_CAPACITY = 157; // max size of locale name
+ const string ICU_COLLATION_KEYWORD = "@collation=";
+
+
+ /// <summary>
+ /// This method uses the sRealName field (which is initialized by the constructor before this is called) to
+ /// initialize the rest of the state of CultureData based on the underlying OS globalization library.
+ /// </summary>
+ private unsafe bool InitCultureData()
+ {
+ Debug.Assert(_sRealName != null);
+
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ string alternateSortName = string.Empty;
+ string realNameBuffer = _sRealName;
+
+ // Basic validation
+ if (realNameBuffer.Contains("@"))
+ {
+ return false; // don't allow ICU variants to come in directly
+ }
+
+ // Replace _ (alternate sort) with @collation= for ICU
+ int index = realNameBuffer.IndexOf('_');
+ if (index > 0)
+ {
+ if (index >= (realNameBuffer.Length - 1) // must have characters after _
+ || realNameBuffer.Substring(index + 1).Contains("_")) // only one _ allowed
+ {
+ return false; // fail
+ }
+ alternateSortName = realNameBuffer.Substring(index + 1);
+ realNameBuffer = realNameBuffer.Substring(0, index) + ICU_COLLATION_KEYWORD + alternateSortName;
+ }
+
+ // Get the locale name from ICU
+ if (!GetLocaleName(realNameBuffer, out _sWindowsName))
+ {
+ return false; // fail
+ }
+
+ // Replace the ICU collation keyword with an _
+ index = _sWindowsName.IndexOf(ICU_COLLATION_KEYWORD, StringComparison.Ordinal);
+ if (index >= 0)
+ {
+ _sName = _sWindowsName.Substring(0, index) + "_" + alternateSortName;
+ }
+ else
+ {
+ _sName = _sWindowsName;
+ }
+ _sRealName = _sName;
+
+ _iLanguage = this.ILANGUAGE;
+ if (_iLanguage == 0)
+ {
+ _iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
+ }
+
+ _bNeutral = (this.SISO3166CTRYNAME.Length == 0);
+
+ _sSpecificCulture = _bNeutral ? LocaleData.GetSpecificCultureName(_sRealName) : _sRealName;
+
+ // Remove the sort from sName unless custom culture
+ if (index>0 && !_bNeutral && !IsCustomCultureId(_iLanguage))
+ {
+ _sName = _sWindowsName.Substring(0, index);
+ }
+ return true;
+ }
+
+ internal static bool GetLocaleName(string localeName, out string windowsName)
+ {
+ // Get the locale name from ICU
+ StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
+ if (!Interop.GlobalizationInterop.GetLocaleName(localeName, sb, sb.Capacity))
+ {
+ StringBuilderCache.Release(sb);
+ windowsName = null;
+ return false; // fail
+ }
+
+ // Success - use the locale name returned which may be different than realNameBuffer (casing)
+ windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
+ return true;
+ }
+
+ internal static bool GetDefaultLocaleName(out string windowsName)
+ {
+ // Get the default (system) locale name from ICU
+ StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
+ if (!Interop.GlobalizationInterop.GetDefaultLocaleName(sb, sb.Capacity))
+ {
+ StringBuilderCache.Release(sb);
+ windowsName = null;
+ return false; // fail
+ }
+
+ // Success - use the locale name returned which may be different than realNameBuffer (casing)
+ windowsName = StringBuilderCache.GetStringAndRelease(sb); // the name passed to subsequent ICU calls
+ return true;
+ }
+
+ private string GetLocaleInfo(LocaleStringData type)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo] Expected _sWindowsName to be populated already");
+ return GetLocaleInfo(_sWindowsName, type);
+ }
+
+ // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
+ // "windows" name, which can be specific for downlevel (< windows 7) os's.
+ private string GetLocaleInfo(string localeName, LocaleStringData type)
+ {
+ Debug.Assert(localeName != null, "[CultureData.GetLocaleInfo] Expected localeName to be not be null");
+
+ switch (type)
+ {
+ case LocaleStringData.NegativeInfinitySymbol:
+ // not an equivalent in ICU; prefix the PositiveInfinitySymbol with NegativeSign
+ return GetLocaleInfo(localeName, LocaleStringData.NegativeSign) +
+ GetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol);
+ }
+
+ StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
+
+ bool result = Interop.GlobalizationInterop.GetLocaleInfoString(localeName, (uint)type, sb, sb.Capacity);
+ if (!result)
+ {
+ // Failed, just use empty string
+ StringBuilderCache.Release(sb);
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleStringData)] Failed");
+ return String.Empty;
+ }
+ return StringBuilderCache.GetStringAndRelease(sb);
+ }
+
+ private int GetLocaleInfo(LocaleNumberData type)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleNumberData)] Expected _sWindowsName to be populated already");
+
+ switch (type)
+ {
+ case LocaleNumberData.CalendarType:
+ // returning 0 will cause the first supported calendar to be returned, which is the preferred calendar
+ return 0;
+ }
+
+
+ int value = 0;
+ bool result = Interop.GlobalizationInterop.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value);
+ if (!result)
+ {
+ // Failed, just use 0
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleNumberData)] failed");
+ }
+
+ return value;
+ }
+
+ private int[] GetLocaleInfo(LocaleGroupingData type)
+ {
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetLocaleInfo(LocaleGroupingData)] Expected _sWindowsName to be populated already");
+
+ int primaryGroupingSize = 0;
+ int secondaryGroupingSize = 0;
+ bool result = Interop.GlobalizationInterop.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupingSize, ref secondaryGroupingSize);
+ if (!result)
+ {
+ Debug.Assert(false, "[CultureData.GetLocaleInfo(LocaleGroupingData type)] failed");
+ }
+
+ if (secondaryGroupingSize == 0)
+ {
+ return new int[] { primaryGroupingSize };
+ }
+
+ return new int[] { primaryGroupingSize, secondaryGroupingSize };
+ }
+
+ private string GetTimeFormatString()
+ {
+ return GetTimeFormatString(false);
+ }
+
+ private string GetTimeFormatString(bool shortFormat)
+ {
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetTimeFormatString(bool shortFormat)] Expected _sWindowsName to be populated already");
+
+ StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_KEYWORD_AND_VALUES_CAPACITY);
+
+ bool result = Interop.GlobalizationInterop.GetLocaleTimeFormat(_sWindowsName, shortFormat, sb, sb.Capacity);
+ if (!result)
+ {
+ // Failed, just use empty string
+ StringBuilderCache.Release(sb);
+ Debug.Assert(false, "[CultureData.GetTimeFormatString(bool shortFormat)] Failed");
+ return String.Empty;
+ }
+
+ return ConvertIcuTimeFormatString(StringBuilderCache.GetStringAndRelease(sb));
+ }
+
+ private int GetFirstDayOfWeek()
+ {
+ return this.GetLocaleInfo(LocaleNumberData.FirstDayOfWeek);
+ }
+
+ private String[] GetTimeFormats()
+ {
+ string format = GetTimeFormatString(false);
+ return new string[] { format };
+ }
+
+ private String[] GetShortTimeFormats()
+ {
+ string format = GetTimeFormatString(true);
+ return new string[] { format };
+ }
+
+ private static CultureData GetCultureDataFromRegionName(String regionName)
+ {
+ // no support to lookup by region name, other than the hard-coded list in CultureData
+ return null;
+ }
+
+ private static string GetLanguageDisplayName(string cultureName)
+ {
+ return new CultureInfo(cultureName)._cultureData.GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
+ }
+
+ private static string GetRegionDisplayName(string isoCountryCode)
+ {
+ // use the fallback which is to return NativeName
+ return null;
+ }
+
+ private static CultureInfo GetUserDefaultCulture()
+ {
+ return CultureInfo.GetUserDefaultCulture();
+ }
+
+ private static string ConvertIcuTimeFormatString(string icuFormatString)
+ {
+ StringBuilder sb = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
+ bool amPmAdded = false;
+
+ for (int i = 0; i < icuFormatString.Length; i++)
+ {
+ switch(icuFormatString[i])
+ {
+ case ':':
+ case '.':
+ case 'H':
+ case 'h':
+ case 'm':
+ case 's':
+ sb.Append(icuFormatString[i]);
+ break;
+
+ case ' ':
+ case '\u00A0':
+ // Convert nonbreaking spaces into regular spaces
+ sb.Append(' ');
+ break;
+
+ case 'a': // AM/PM
+ if (!amPmAdded)
+ {
+ amPmAdded = true;
+ sb.Append("tt");
+ }
+ break;
+
+ }
+ }
+
+ return StringBuilderCache.GetStringAndRelease(sb);
+ }
+
+ private static string LCIDToLocaleName(int culture)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ return LocaleData.LCIDToLocaleName(culture);
+ }
+
+ private static int LocaleNameToLCID(string cultureName)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ int lcid = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.Lcid);
+ return lcid == -1 ? CultureInfo.LOCALE_CUSTOM_UNSPECIFIED : lcid;
+ }
+
+ private static int GetAnsiCodePage(string cultureName)
+ {
+ int ansiCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.AnsiCodePage);
+ return ansiCodePage == -1 ? CultureData.Invariant.IDEFAULTANSICODEPAGE : ansiCodePage;
+ }
+
+ private static int GetOemCodePage(string cultureName)
+ {
+ int oemCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.OemCodePage);
+ return oemCodePage == -1 ? CultureData.Invariant.IDEFAULTOEMCODEPAGE : oemCodePage;
+ }
+
+ private static int GetMacCodePage(string cultureName)
+ {
+ int macCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.MacCodePage);
+ return macCodePage == -1 ? CultureData.Invariant.IDEFAULTMACCODEPAGE : macCodePage;
+ }
+
+ private static int GetEbcdicCodePage(string cultureName)
+ {
+ int ebcdicCodePage = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.EbcdicCodePage);
+ return ebcdicCodePage == -1 ? CultureData.Invariant.IDEFAULTEBCDICCODEPAGE : ebcdicCodePage;
+ }
+
+ private static int GetGeoId(string cultureName)
+ {
+ int geoId = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.GeoId);
+ return geoId == -1 ? CultureData.Invariant.IGEOID : geoId;
+ }
+
+ private static int GetDigitSubstitution(string cultureName)
+ {
+ int digitSubstitution = LocaleData.GetLocaleDataNumericPart(cultureName, LocaleDataParts.DigitSubstitution);
+ return digitSubstitution == -1 ? (int) DigitShapes.None : digitSubstitution;
+ }
+
+ private static string GetThreeLetterWindowsLanguageName(string cultureName)
+ {
+ string langName = LocaleData.GetThreeLetterWindowsLangageName(cultureName);
+ return langName == null ? "ZZZ" /* default lang name */ : langName;
+ }
+
+ private static CultureInfo[] EnumCultures(CultureTypes types)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0)
+ {
+ return Array.Empty<CultureInfo>();
+ }
+
+ int bufferLength = Interop.GlobalizationInterop.GetLocales(null, 0);
+ if (bufferLength <= 0)
+ {
+ return Array.Empty<CultureInfo>();
+ }
+
+ Char [] chars = new Char[bufferLength];
+
+ bufferLength = Interop.GlobalizationInterop.GetLocales(chars, bufferLength);
+ if (bufferLength <= 0)
+ {
+ return Array.Empty<CultureInfo>();
+ }
+
+ bool enumNeutrals = (types & CultureTypes.NeutralCultures) != 0;
+ bool enumSpecificss = (types & CultureTypes.SpecificCultures) != 0;
+
+ List<CultureInfo> list = new List<CultureInfo>();
+ if (enumNeutrals)
+ {
+ list.Add(CultureInfo.InvariantCulture);
+ }
+
+ int index = 0;
+ while (index < bufferLength)
+ {
+ int length = (int) chars[index++];
+ if (index + length <= bufferLength)
+ {
+ CultureInfo ci = CultureInfo.GetCultureInfo(new String(chars, index, length));
+ if ((enumNeutrals && ci.IsNeutralCulture) || (enumSpecificss && !ci.IsNeutralCulture))
+ {
+ list.Add(ci);
+ }
+ }
+
+ index += length;
+ }
+
+ return list.ToArray();
+ }
+
+ private static string GetConsoleFallbackName(string cultureName)
+ {
+ return LocaleData.GetConsoleUICulture(cultureName);
+ }
+
+ internal bool IsFramework // not applicable on Linux based systems
+ {
+ get { return false; }
+ }
+
+ internal bool IsWin32Installed // not applicable on Linux based systems
+ {
+ get { return false; }
+ }
+
+ internal bool IsReplacementCulture // not applicable on Linux based systems
+ {
+ get { return false; }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
new file mode 100644
index 0000000000..6d2678b550
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
@@ -0,0 +1,830 @@
+// 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.Diagnostics;
+using System.Runtime.InteropServices;
+using System.Text;
+
+#if ENABLE_WINRT
+using Internal.Runtime.Augments;
+#endif
+
+namespace System.Globalization
+{
+#if CORECLR
+ using StringList = List<string>;
+#else
+ using StringList = LowLevelList<string>;
+#endif
+
+ internal partial class CultureData
+ {
+ private const uint LOCALE_NOUSEROVERRIDE = 0x80000000;
+ private const uint LOCALE_RETURN_NUMBER = 0x20000000;
+ private const uint LOCALE_SISO3166CTRYNAME = 0x0000005A;
+
+ private const uint TIME_NOSECONDS = 0x00000002;
+
+ /// <summary>
+ /// Check with the OS to see if this is a valid culture.
+ /// If so we populate a limited number of fields. If its not valid we return false.
+ ///
+ /// The fields we populate:
+ ///
+ /// sWindowsName -- The name that windows thinks this culture is, ie:
+ /// en-US if you pass in en-US
+ /// de-DE_phoneb if you pass in de-DE_phoneb
+ /// fj-FJ if you pass in fj (neutral, on a pre-Windows 7 machine)
+ /// fj if you pass in fj (neutral, post-Windows 7 machine)
+ ///
+ /// sRealName -- The name you used to construct the culture, in pretty form
+ /// en-US if you pass in EN-us
+ /// en if you pass in en
+ /// de-DE_phoneb if you pass in de-DE_phoneb
+ ///
+ /// sSpecificCulture -- The specific culture for this culture
+ /// en-US for en-US
+ /// en-US for en
+ /// de-DE_phoneb for alt sort
+ /// fj-FJ for fj (neutral)
+ ///
+ /// sName -- The IETF name of this culture (ie: no sort info, could be neutral)
+ /// en-US if you pass in en-US
+ /// en if you pass in en
+ /// de-DE if you pass in de-DE_phoneb
+ ///
+ /// bNeutral -- TRUE if it is a neutral locale
+ ///
+ /// For a neutral we just populate the neutral name, but we leave the windows name pointing to the
+ /// windows locale that's going to provide data for us.
+ /// </summary>
+ private unsafe bool InitCultureData()
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ const uint LOCALE_ILANGUAGE = 0x00000001;
+ const uint LOCALE_INEUTRAL = 0x00000071;
+ const uint LOCALE_SNAME = 0x0000005c;
+
+ int result;
+ string realNameBuffer = _sRealName;
+ char* pBuffer = stackalloc char[LOCALE_NAME_MAX_LENGTH];
+
+ result = GetLocaleInfoEx(realNameBuffer, LOCALE_SNAME, pBuffer, LOCALE_NAME_MAX_LENGTH);
+
+ // Did it fail?
+ if (result == 0)
+ {
+ return false;
+ }
+
+ // It worked, note that the name is the locale name, so use that (even for neutrals)
+ // We need to clean up our "real" name, which should look like the windows name right now
+ // so overwrite the input with the cleaned up name
+ _sRealName = new String(pBuffer, 0, result - 1);
+ realNameBuffer = _sRealName;
+
+ // Check for neutrality, don't expect to fail
+ // (buffer has our name in it, so we don't have to do the gc. stuff)
+
+ result = GetLocaleInfoEx(realNameBuffer, LOCALE_INEUTRAL | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
+ if (result == 0)
+ {
+ return false;
+ }
+
+ // Remember our neutrality
+ _bNeutral = *((uint*)pBuffer) != 0;
+
+ // Note: Parents will be set dynamically
+
+ // Start by assuming the windows name will be the same as the specific name since windows knows
+ // about specifics on all versions. Only for downlevel Neutral locales does this have to change.
+ _sWindowsName = realNameBuffer;
+
+ // Neutrals and non-neutrals are slightly different
+ if (_bNeutral)
+ {
+ // Neutral Locale
+
+ // IETF name looks like neutral name
+ _sName = realNameBuffer;
+
+ // Specific locale name is whatever ResolveLocaleName (win7+) returns.
+ // (Buffer has our name in it, and we can recycle that because windows resolves it before writing to the buffer)
+ result = Interop.Kernel32.ResolveLocaleName(realNameBuffer, pBuffer, LOCALE_NAME_MAX_LENGTH);
+
+ // 0 is failure, 1 is invariant (""), which we expect
+ if (result < 1)
+ {
+ return false;
+ }
+ // We found a locale name, so use it.
+ // In vista this should look like a sort name (de-DE_phoneb) or a specific culture (en-US) and be in the "pretty" form
+ _sSpecificCulture = new String(pBuffer, 0, result - 1);
+ }
+ else
+ {
+ // Specific Locale
+
+ // Specific culture's the same as the locale name since we know its not neutral
+ // On mac we'll use this as well, even for neutrals. There's no obvious specific
+ // culture to use and this isn't exposed, but behaviorally this is correct on mac.
+ // Note that specifics include the sort name (de-DE_phoneb)
+ _sSpecificCulture = realNameBuffer;
+
+ _sName = realNameBuffer;
+
+ // We need the IETF name (sname)
+ // If we aren't an alt sort locale then this is the same as the windows name.
+ // If we are an alt sort locale then this is the same as the part before the _ in the windows name
+ // This is for like de-DE_phoneb and es-ES_tradnl that hsouldn't have the _ part
+
+ result = GetLocaleInfoEx(realNameBuffer, LOCALE_ILANGUAGE | LOCALE_RETURN_NUMBER, pBuffer, sizeof(int) / sizeof(char));
+ if (result == 0)
+ {
+ return false;
+ }
+
+ _iLanguage = *((int*)pBuffer);
+
+ if (!IsCustomCultureId(_iLanguage))
+ {
+ // not custom locale
+ int index = realNameBuffer.IndexOf('_');
+ if (index > 0 && index < realNameBuffer.Length)
+ {
+ _sName = realNameBuffer.Substring(0, index);
+ }
+ }
+ }
+
+ // It succeeded.
+ return true;
+ }
+
+ // Wrappers around the GetLocaleInfoEx APIs which handle marshalling the returned
+ // data as either and Int or String.
+ internal static unsafe String GetLocaleInfoEx(String localeName, uint field)
+ {
+ // REVIEW: Determine the maximum size for the buffer
+ const int BUFFER_SIZE = 530;
+
+ char* pBuffer = stackalloc char[BUFFER_SIZE];
+ int resultCode = GetLocaleInfoEx(localeName, field, pBuffer, BUFFER_SIZE);
+ if (resultCode > 0)
+ {
+ return new String(pBuffer);
+ }
+
+ return "";
+ }
+
+ internal static unsafe int GetLocaleInfoExInt(String localeName, uint field)
+ {
+ const uint LOCALE_RETURN_NUMBER = 0x20000000;
+ field |= LOCALE_RETURN_NUMBER;
+ int value = 0;
+ GetLocaleInfoEx(localeName, field, (char*) &value, sizeof(int));
+ return value;
+ }
+
+ internal static unsafe int GetLocaleInfoEx(string lpLocaleName, uint lcType, char* lpLCData, int cchData)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, (IntPtr)lpLCData, cchData);
+ }
+
+ private string GetLocaleInfo(LocaleStringData type)
+ {
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected _sWindowsName to be populated by already");
+ return GetLocaleInfo(_sWindowsName, type);
+ }
+
+ // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
+ // "windows" name, which can be specific for downlevel (< windows 7) os's.
+ private string GetLocaleInfo(string localeName, LocaleStringData type)
+ {
+ uint lctype = (uint)type;
+
+ return GetLocaleInfoFromLCType(localeName, lctype, UseUserOverride);
+ }
+
+ private int GetLocaleInfo(LocaleNumberData type)
+ {
+ uint lctype = (uint)type;
+
+ // Fix lctype if we don't want overrides
+ if (!UseUserOverride)
+ {
+ lctype |= LOCALE_NOUSEROVERRIDE;
+ }
+
+ // Ask OS for data, note that we presume it returns success, so we have to know that
+ // sWindowsName is valid before calling.
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+ return GetLocaleInfoExInt(_sWindowsName, lctype);
+ }
+
+ private int[] GetLocaleInfo(LocaleGroupingData type)
+ {
+ return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sWindowsName, (uint)type, UseUserOverride));
+ }
+
+ private string GetTimeFormatString()
+ {
+ const uint LOCALE_STIMEFORMAT = 0x00001003;
+
+ return ReescapeWin32String(GetLocaleInfoFromLCType(_sWindowsName, LOCALE_STIMEFORMAT, UseUserOverride));
+ }
+
+ private int GetFirstDayOfWeek()
+ {
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected _sWindowsName to be populated by already");
+
+ const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C;
+
+ int result = GetLocaleInfoExInt(_sWindowsName, LOCALE_IFIRSTDAYOFWEEK | (!UseUserOverride ? LOCALE_NOUSEROVERRIDE : 0));
+
+ // Win32 and .NET disagree on the numbering for days of the week, so we have to convert.
+ return ConvertFirstDayOfWeekMonToSun(result);
+ }
+
+ private String[] GetTimeFormats()
+ {
+ // Note that this gets overrides for us all the time
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected _sWindowsName to be populated by already");
+ String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, 0, UseUserOverride));
+
+ return result;
+ }
+
+ private String[] GetShortTimeFormats()
+ {
+ // Note that this gets overrides for us all the time
+ Debug.Assert(_sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected _sWindowsName to be populated by already");
+ String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, TIME_NOSECONDS, UseUserOverride));
+
+ return result;
+ }
+
+ // Enumerate all system cultures and then try to find out which culture has
+ // region name match the requested region name
+ private static CultureData GetCultureDataFromRegionName(String regionName)
+ {
+ Debug.Assert(regionName != null);
+
+ const uint LOCALE_SUPPLEMENTAL = 0x00000002;
+ const uint LOCALE_SPECIFICDATA = 0x00000020;
+
+ EnumLocaleData context = new EnumLocaleData();
+ context.cultureName = null;
+ context.regionName = regionName;
+
+ GCHandle contextHandle = GCHandle.Alloc(context);
+ try
+ {
+#if CORECLR
+ Interop.Kernel32.EnumSystemLocalesEx(EnumSystemLocalesProc, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero);
+#else
+ IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumSystemLocalesProc);
+ Interop.Kernel32.EnumSystemLocalesEx(callback, LOCALE_SPECIFICDATA | LOCALE_SUPPLEMENTAL, (IntPtr)contextHandle, IntPtr.Zero);
+#endif
+ }
+ finally
+ {
+ contextHandle.Free();
+ }
+
+ if (context.cultureName != null)
+ {
+ // we got a matched culture
+ return GetCultureData(context.cultureName, true);
+ }
+
+ return null;
+ }
+
+ private string GetLanguageDisplayName(string cultureName)
+ {
+#if ENABLE_WINRT
+ return WinRTInterop.Callbacks.GetLanguageDisplayName(cultureName);
+#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 SNATIVEDISPLAYNAME;
+ }
+ else
+ {
+ return GetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName);
+ }
+#endif // ENABLE_WINRT
+ }
+
+ private string GetRegionDisplayName(string isoCountryCode)
+ {
+#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
+ {
+ return GetLocaleInfo(LocaleStringData.LocalizedCountryName);
+ }
+#endif // ENABLE_WINRT
+ }
+
+ private static CultureInfo GetUserDefaultCulture()
+ {
+#if ENABLE_WINRT
+ return (CultureInfo)WinRTInterop.Callbacks.GetUserDefaultCulture();
+#else
+ return CultureInfo.GetUserDefaultCulture();
+#endif // ENABLE_WINRT
+ }
+
+ // PAL methods end here.
+
+ private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOveride)
+ {
+ Debug.Assert(localeName != null, "[CultureData.GetLocaleInfoFromLCType] Expected localeName to be not be null");
+
+ // Fix lctype if we don't want overrides
+ if (!useUserOveride)
+ {
+ lctype |= LOCALE_NOUSEROVERRIDE;
+ }
+
+ // Ask OS for data
+ string result = GetLocaleInfoEx(localeName, lctype);
+ if (result == null)
+ {
+ // Failed, just use empty string
+ result = String.Empty;
+ }
+
+ return result;
+ }
+
+ ////////////////////////////////////////////////////////////////////////////
+ //
+ // Reescape a Win32 style quote string as a NLS+ style quoted string
+ //
+ // This is also the escaping style used by custom culture data files
+ //
+ // NLS+ uses \ to escape the next character, whether in a quoted string or
+ // not, so we always have to change \ to \\.
+ //
+ // NLS+ uses \' to escape a quote inside a quoted string so we have to change
+ // '' to \' (if inside a quoted string)
+ //
+ // We don't build the stringbuilder unless we find something to change
+ ////////////////////////////////////////////////////////////////////////////
+ internal static String ReescapeWin32String(String str)
+ {
+ // If we don't have data, then don't try anything
+ if (str == null)
+ return null;
+
+ StringBuilder result = null;
+
+ bool inQuote = false;
+ for (int i = 0; i < str.Length; i++)
+ {
+ // Look for quote
+ if (str[i] == '\'')
+ {
+ // Already in quote?
+ if (inQuote)
+ {
+ // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
+ if (i + 1 < str.Length && str[i + 1] == '\'')
+ {
+ // Found another ', so we have ''. Need to add \' instead.
+ // 1st make sure we have our stringbuilder
+ if (result == null)
+ result = new StringBuilder(str, 0, i, str.Length * 2);
+
+ // Append a \' and keep going (so we don't turn off quote mode)
+ result.Append("\\'");
+ i++;
+ continue;
+ }
+
+ // Turning off quote mode, fall through to add it
+ inQuote = false;
+ }
+ else
+ {
+ // Found beginning quote, fall through to add it
+ inQuote = true;
+ }
+ }
+ // Is there a single \ character?
+ else if (str[i] == '\\')
+ {
+ // Found a \, need to change it to \\
+ // 1st make sure we have our stringbuilder
+ if (result == null)
+ result = new StringBuilder(str, 0, i, str.Length * 2);
+
+ // Append our \\ to the string & continue
+ result.Append("\\\\");
+ continue;
+ }
+
+ // If we have a builder we need to add our character
+ if (result != null)
+ result.Append(str[i]);
+ }
+
+ // Unchanged string? , just return input string
+ if (result == null)
+ return str;
+
+ // String changed, need to use the builder
+ return result.ToString();
+ }
+
+ internal static String[] ReescapeWin32Strings(String[] array)
+ {
+ if (array != null)
+ {
+ for (int i = 0; i < array.Length; i++)
+ {
+ array[i] = ReescapeWin32String(array[i]);
+ }
+ }
+
+ return array;
+ }
+
+ // If we get a group from windows, then its in 3;0 format with the 0 backwards
+ // of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa)
+ // EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning.
+ private static int[] ConvertWin32GroupString(String win32Str)
+ {
+ // None of these cases make any sense
+ if (win32Str == null || win32Str.Length == 0)
+ {
+ return (new int[] { 3 });
+ }
+
+ if (win32Str[0] == '0')
+ {
+ return (new int[] { 0 });
+ }
+
+ // Since its in n;n;n;n;n format, we can always get the length quickly
+ int[] values;
+ if (win32Str[win32Str.Length - 1] == '0')
+ {
+ // Trailing 0 gets dropped. 1;0 -> 1
+ values = new int[(win32Str.Length / 2)];
+ }
+ else
+ {
+ // Need extra space for trailing zero 1 -> 1;0
+ values = new int[(win32Str.Length / 2) + 2];
+ values[values.Length - 1] = 0;
+ }
+
+ int i;
+ int j;
+ for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
+ {
+ // Note that this # shouldn't ever be zero, 'cause 0 is only at end
+ // But we'll test because its registry that could be anything
+ if (win32Str[i] < '1' || win32Str[i] > '9')
+ return new int[] { 3 };
+
+ values[j] = (int)(win32Str[i] - '0');
+ }
+
+ return (values);
+ }
+
+ private static int ConvertFirstDayOfWeekMonToSun(int iTemp)
+ {
+ // Convert Mon-Sun to Sun-Sat format
+ iTemp++;
+ if (iTemp > 6)
+ {
+ // Wrap Sunday and convert invalid data to Sunday
+ iTemp = 0;
+ }
+ return iTemp;
+ }
+
+
+ // Context for EnumCalendarInfoExEx callback.
+ private class EnumLocaleData
+ {
+ public string regionName;
+ public string cultureName;
+ }
+
+ // EnumSystemLocaleEx callback.
+#if !CORECLR
+ [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+#endif
+ private static unsafe Interop.BOOL EnumSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle)
+ {
+ EnumLocaleData context = (EnumLocaleData)((GCHandle)contextHandle).Target;
+ try
+ {
+ string cultureName = new string((char*)lpLocaleString);
+ string regionName = GetLocaleInfoEx(cultureName, LOCALE_SISO3166CTRYNAME);
+ if (regionName != null && regionName.Equals(context.regionName, StringComparison.OrdinalIgnoreCase))
+ {
+ context.cultureName = cultureName;
+ return Interop.BOOL.FALSE; // we found a match, then stop the enumeration
+ }
+
+ return Interop.BOOL.TRUE;
+ }
+ catch (Exception)
+ {
+ return Interop.BOOL.FALSE;
+ }
+ }
+
+ // EnumSystemLocaleEx callback.
+#if !CORECLR
+ [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+#endif
+ private static unsafe Interop.BOOL EnumAllSystemLocalesProc(IntPtr lpLocaleString, uint flags, IntPtr contextHandle)
+ {
+ EnumData context = (EnumData)((GCHandle)contextHandle).Target;
+ try
+ {
+ context.strings.Add(new string((char*)lpLocaleString));
+ return Interop.BOOL.TRUE;
+ }
+ catch (Exception)
+ {
+ return Interop.BOOL.FALSE;
+ }
+ }
+
+ // Context for EnumTimeFormatsEx callback.
+ private class EnumData
+ {
+ public StringList strings;
+ }
+
+ // EnumTimeFormatsEx callback itself.
+#if !CORECLR
+ [NativeCallable(CallingConvention = CallingConvention.StdCall)]
+#endif
+ private static unsafe Interop.BOOL EnumTimeCallback(IntPtr lpTimeFormatString, IntPtr lParam)
+ {
+ EnumData context = (EnumData)((GCHandle)lParam).Target;
+
+ try
+ {
+ context.strings.Add(new string((char*)lpTimeFormatString));
+ return Interop.BOOL.TRUE;
+ }
+ catch (Exception)
+ {
+ return Interop.BOOL.FALSE;
+ }
+ }
+
+ private static unsafe String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride)
+ {
+ const uint LOCALE_SSHORTTIME = 0x00000079;
+ const uint LOCALE_STIMEFORMAT = 0x00001003;
+
+ EnumData data = new EnumData();
+ data.strings = new StringList();
+ GCHandle dataHandle = GCHandle.Alloc(data);
+ try
+ {
+#if CORECLR
+ Interop.Kernel32.EnumTimeFormatsEx(EnumTimeCallback, localeName, (uint)dwFlags, (IntPtr)dataHandle);
+#else
+ // Now call the enumeration API. Work is done by our callback function
+ IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, IntPtr, Interop.BOOL>>(EnumTimeCallback);
+ Interop.Kernel32.EnumTimeFormatsEx(callback, localeName, (uint)dwFlags, (IntPtr)dataHandle);
+#endif
+ }
+ finally
+ {
+ dataHandle.Free();
+ }
+
+ if (data.strings.Count > 0)
+ {
+ // Now we need to allocate our stringarray and populate it
+ string[] results = data.strings.ToArray();
+
+ if (!useUserOverride && data.strings.Count > 1)
+ {
+ // Since there is no "NoUserOverride" aware EnumTimeFormatsEx, we always get an override
+ // The override is the first entry if it is overriden.
+ // We can check if we have overrides by checking the GetLocaleInfo with no override
+ // If we do have an override, we don't know if it is a user defined override or if the
+ // user has just selected one of the predefined formats so we can't just remove it
+ // but we can move it down.
+ uint lcType = (dwFlags == TIME_NOSECONDS) ? LOCALE_SSHORTTIME : LOCALE_STIMEFORMAT;
+ string timeFormatNoUserOverride = GetLocaleInfoFromLCType(localeName, lcType, useUserOverride);
+ if (timeFormatNoUserOverride != "")
+ {
+ string firstTimeFormat = results[0];
+ if (timeFormatNoUserOverride != firstTimeFormat)
+ {
+ results[0] = results[1];
+ results[1] = firstTimeFormat;
+ }
+ }
+ }
+
+ return results;
+ }
+
+ return null;
+ }
+
+ private static int LocaleNameToLCID(string cultureName)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ return Interop.Kernel32.LocaleNameToLCID(cultureName, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES);
+ }
+
+ private static unsafe string LCIDToLocaleName(int culture)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ char *pBuffer = stackalloc char[Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1]; // +1 for the null termination
+ int length = Interop.Kernel32.LCIDToLocaleName(culture, pBuffer, Interop.Kernel32.LOCALE_NAME_MAX_LENGTH + 1, Interop.Kernel32.LOCALE_ALLOW_NEUTRAL_NAMES);
+
+ if (length > 0)
+ {
+ return new String(pBuffer);
+ }
+
+ return null;
+ }
+
+ private int GetAnsiCodePage(string cultureName)
+ {
+ return GetLocaleInfo(LocaleNumberData.AnsiCodePage);
+ }
+
+ private int GetOemCodePage(string cultureName)
+ {
+ return GetLocaleInfo(LocaleNumberData.OemCodePage);
+ }
+
+ private int GetMacCodePage(string cultureName)
+ {
+ return GetLocaleInfo(LocaleNumberData.MacCodePage);
+ }
+
+ private int GetEbcdicCodePage(string cultureName)
+ {
+ return GetLocaleInfo(LocaleNumberData.EbcdicCodePage);
+ }
+
+ private int GetGeoId(string cultureName)
+ {
+ return GetLocaleInfo(LocaleNumberData.GeoId);
+ }
+
+ private int GetDigitSubstitution(string cultureName)
+ {
+ return GetLocaleInfo(LocaleNumberData.DigitSubstitution);
+ }
+
+ private string GetThreeLetterWindowsLanguageName(string cultureName)
+ {
+ return GetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName);
+ }
+
+ private static CultureInfo[] EnumCultures(CultureTypes types)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ uint flags = 0;
+
+#pragma warning disable 618
+ if ((types & (CultureTypes.FrameworkCultures | CultureTypes.InstalledWin32Cultures | CultureTypes.ReplacementCultures)) != 0)
+ {
+ flags |= Interop.Kernel32.LOCALE_NEUTRALDATA | Interop.Kernel32.LOCALE_SPECIFICDATA;
+ }
+#pragma warning restore 618
+
+ if ((types & CultureTypes.NeutralCultures) != 0)
+ {
+ flags |= Interop.Kernel32.LOCALE_NEUTRALDATA;
+ }
+
+ if ((types & CultureTypes.SpecificCultures) != 0)
+ {
+ flags |= Interop.Kernel32.LOCALE_SPECIFICDATA;
+ }
+
+ if ((types & CultureTypes.UserCustomCulture) != 0)
+ {
+ flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL;
+ }
+
+ if ((types & CultureTypes.ReplacementCultures) != 0)
+ {
+ flags |= Interop.Kernel32.LOCALE_SUPPLEMENTAL;
+ }
+
+ EnumData context = new EnumData();
+ context.strings = new StringList();
+ GCHandle contextHandle = GCHandle.Alloc(context);
+ try
+ {
+#if CORECLR
+ Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, flags, (IntPtr)contextHandle, IntPtr.Zero);
+#else
+ IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumAllSystemLocalesProc);
+ Interop.Kernel32.EnumSystemLocalesEx(callback, flags, (IntPtr)contextHandle, IntPtr.Zero);
+#endif
+ }
+ finally
+ {
+ contextHandle.Free();
+ }
+
+ CultureInfo [] cultures = new CultureInfo[context.strings.Count];
+ for (int i = 0; i < cultures.Length; i++)
+ {
+ cultures[i] = new CultureInfo(context.strings[i]);
+ }
+
+ return cultures;
+ }
+
+ private string GetConsoleFallbackName(string cultureName)
+ {
+ return GetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName);
+ }
+
+ internal bool IsFramework
+ {
+ get { return false; }
+ }
+
+ internal bool IsWin32Installed
+ {
+ get { return true; }
+ }
+
+ internal bool IsReplacementCulture
+ {
+ get
+ {
+ EnumData context = new EnumData();
+ context.strings = new StringList();
+ GCHandle contextHandle = GCHandle.Alloc(context);
+ try
+ {
+#if CORECLR
+ Interop.Kernel32.EnumSystemLocalesEx(EnumAllSystemLocalesProc, Interop.Kernel32.LOCALE_REPLACEMENT, (IntPtr)contextHandle, IntPtr.Zero);
+#else
+ IntPtr callback = AddrofIntrinsics.AddrOf<Func<IntPtr, uint, IntPtr, Interop.BOOL>>(EnumAllSystemLocalesProc);
+ Interop.Kernel32.EnumSystemLocalesEx(callback, Interop.Kernel32.LOCALE_REPLACEMENT, (IntPtr)contextHandle, IntPtr.Zero);
+#endif
+ }
+ finally
+ {
+ contextHandle.Free();
+ }
+
+ for (int i=0; i<context.strings.Count; i++)
+ {
+ if (String.Compare(context.strings[i], _sWindowsName, StringComparison.OrdinalIgnoreCase) == 0)
+ return true;
+ }
+
+ return false;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs
index a93b7d43bb..0dcebf484b 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.cs
@@ -2,20 +2,23 @@
// 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.Diagnostics;
+using System.Text;
+using System.Threading;
+
namespace System.Globalization
{
-
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Security;
+#if CORECLR
+ using StringStringDictionary = Dictionary<string, string>;
+ using StringCultureDataDictionary = Dictionary<string, CultureData>;
+ using LcidToCultureNameDictionary = Dictionary<int, string>;
+ using Lock = Object;
+#else
+ using StringStringDictionary = LowLevelDictionary<string, string>;
+ using StringCultureDataDictionary = LowLevelDictionary<string, CultureData>;
+ using LcidToCultureNameDictionary = LowLevelDictionary<int, string>;
+#endif
//
// List of culture data
@@ -48,504 +51,263 @@ namespace System.Globalization
// en if you pass in en
// de-DE if you pass in de-DE_phoneb
//
-
- // StructLayout is needed here otherwise compiler can re-arrange the fields.
- // We have to keep this in-sync with the definition in comnlsinfo.h
- //
- // WARNING WARNING WARNING
- //
- // WARNING: Anything changed here also needs to be updated on the native side (object.h see type CultureDataBaseObject)
- // WARNING: The type loader will rearrange class member offsets so the mscorwks!CultureDataBaseObject
- // WARNING: must be manually structured to match the true loaded class layout
- //
- [FriendAccessAllowed]
- internal class CultureData
+ internal partial class CultureData
{
- const int undef = -1;
+ private const int LOCALE_NAME_MAX_LENGTH = 85;
+ private const int undef = -1;
// Override flag
- private String sRealName; // Name you passed in (ie: en-US, en, or de-DE_phoneb)
- private String sWindowsName; // Name OS thinks the object is (ie: de-DE_phoneb, or en-US (even if en was passed in))
+ private String _sRealName; // Name you passed in (ie: en-US, en, or de-DE_phoneb)
+ private String _sWindowsName; // Name OS thinks the object is (ie: de-DE_phoneb, or en-US (even if en was passed in))
// Identity
- private String sName; // locale name (ie: en-us, NO sort info, but could be neutral)
- private String sParent; // Parent name (which may be a custom locale/culture)
- private String sLocalizedDisplayName; // Localized pretty name for this locale
- private String sEnglishDisplayName; // English pretty name for this locale
- private String sNativeDisplayName; // Native pretty name for this locale
- private String sSpecificCulture; // The culture name to be used in CultureInfo.CreateSpecificCulture(), en-US form if neutral, sort name if sort
+ private String _sName; // locale name (ie: en-us, NO sort info, but could be neutral)
+ private String _sParent; // Parent name (which may be a custom locale/culture)
+ private String _sLocalizedDisplayName; // Localized pretty name for this locale
+ private String _sEnglishDisplayName; // English pretty name for this locale
+ private String _sNativeDisplayName; // Native pretty name for this locale
+ private String _sSpecificCulture; // The culture name to be used in CultureInfo.CreateSpecificCulture(), en-US form if neutral, sort name if sort
// Language
- private String sISO639Language; // ISO 639 Language Name
- private String sLocalizedLanguage; // Localized name for this language
- private String sEnglishLanguage; // English name for this language
- private String sNativeLanguage; // Native name of this language
+ private String _sISO639Language; // ISO 639 Language Name
+ private String _sISO639Language2; // ISO 639 Language Name
+ private String _sLocalizedLanguage; // Localized name for this language
+ private String _sEnglishLanguage; // English name for this language
+ private String _sNativeLanguage; // Native name of this language
+ private String _sAbbrevLang; // abbreviated language name (Windows Language Name) ex: ENU
+ private string _sConsoleFallbackName; // The culture name for the console fallback UI culture
+ private int _iInputLanguageHandle=undef;// input language handle
// Region
- private String sRegionName; // (RegionInfo)
- private int iGeoId = undef; // GeoId
- private String sLocalizedCountry; // localized country name
- private String sEnglishCountry; // english country name (RegionInfo)
- private String sNativeCountry; // native country name
- private String sISO3166CountryName; // ISO 3166 (RegionInfo), ie: US
+ private String _sRegionName; // (RegionInfo)
+ private String _sLocalizedCountry; // localized country name
+ private String _sEnglishCountry; // english country name (RegionInfo)
+ private String _sNativeCountry; // native country name
+ private String _sISO3166CountryName; // ISO 3166 (RegionInfo), ie: US
+ private String _sISO3166CountryName2; // 3 char ISO 3166 country name 2 2(RegionInfo) ex: USA (ISO)
+ private int _iGeoId = undef; // GeoId
// Numbers
- private String sPositiveSign; // (user can override) positive sign
- private String sNegativeSign; // (user can override) negative sign
- private String[] saNativeDigits; // (user can override) native characters for digits 0-9
+ private String _sPositiveSign; // (user can override) positive sign
+ private String _sNegativeSign; // (user can override) negative sign
// (nfi populates these 5, don't have to be = undef)
- private int iDigitSubstitution; // (user can override) Digit substitution 0=context, 1=none/arabic, 2=Native/national (2 seems to be unused)
- private int iLeadingZeros; // (user can override) leading zeros 0 = no leading zeros, 1 = leading zeros
- private int iDigits; // (user can override) number of fractional digits
- private int iNegativeNumber; // (user can override) negative number format
- private int[] waGrouping; // (user can override) grouping of digits
- private String sDecimalSeparator; // (user can override) decimal separator
- private String sThousandSeparator; // (user can override) thousands separator
- private String sNaN; // Not a Number
- private String sPositiveInfinity; // + Infinity
- private String sNegativeInfinity; // - Infinity
+ private int _iDigits; // (user can override) number of fractional digits
+ private int _iNegativeNumber; // (user can override) negative number format
+ private int[] _waGrouping; // (user can override) grouping of digits
+ private String _sDecimalSeparator; // (user can override) decimal separator
+ private String _sThousandSeparator; // (user can override) thousands separator
+ private String _sNaN; // Not a Number
+ private String _sPositiveInfinity; // + Infinity
+ private String _sNegativeInfinity; // - Infinity
// Percent
- private int iNegativePercent = undef; // Negative Percent (0-3)
- private int iPositivePercent = undef; // Positive Percent (0-11)
- private String sPercent; // Percent (%) symbol
- private String sPerMille; // PerMille (‰) symbol
+ private int _iNegativePercent = undef; // Negative Percent (0-3)
+ private int _iPositivePercent = undef; // Positive Percent (0-11)
+ private String _sPercent; // Percent (%) symbol
+ private String _sPerMille; // PerMille symbol
// Currency
- private String sCurrency; // (user can override) local monetary symbol
- private String sIntlMonetarySymbol; // international monetary symbol (RegionInfo)
- private String sEnglishCurrency; // English name for this currency
- private String sNativeCurrency; // Native name for this currency
+ private String _sCurrency; // (user can override) local monetary symbol
+ private String _sIntlMonetarySymbol; // international monetary symbol (RegionInfo)
+ private String _sEnglishCurrency; // English name for this currency
+ private String _sNativeCurrency; // Native name for this currency
// (nfi populates these 4, don't have to be = undef)
- private int iCurrencyDigits; // (user can override) # local monetary fractional digits
- private int iCurrency; // (user can override) positive currency format
- private int iNegativeCurrency; // (user can override) negative currency format
- private int[] waMonetaryGrouping; // (user can override) monetary grouping of digits
- private String sMonetaryDecimal; // (user can override) monetary decimal separator
- private String sMonetaryThousand; // (user can override) monetary thousands separator
+ private int _iCurrencyDigits; // (user can override) # local monetary fractional digits
+ private int _iCurrency; // (user can override) positive currency format
+ private int _iNegativeCurrency; // (user can override) negative currency format
+ private int[] _waMonetaryGrouping; // (user can override) monetary grouping of digits
+ private String _sMonetaryDecimal; // (user can override) monetary decimal separator
+ private String _sMonetaryThousand; // (user can override) monetary thousands separator
// Misc
- private int iMeasure = undef; // (user can override) system of measurement 0=metric, 1=US (RegionInfo)
- private String sListSeparator; // (user can override) list separator
- // private int iPaperSize ; // default paper size (RegionInfo)
+ private int _iMeasure = undef; // (user can override) system of measurement 0=metric, 1=US (RegionInfo)
+ private String _sListSeparator; // (user can override) list separator
// Time
- private String sAM1159; // (user can override) AM designator
- private String sPM2359; // (user can override) PM designator
- private String sTimeSeparator;
- private volatile String[] saLongTimes; // (user can override) time format
- private volatile String[] saShortTimes; // short time format
- private volatile String[] saDurationFormats; // time duration format
+ private String _sAM1159; // (user can override) AM designator
+ private String _sPM2359; // (user can override) PM designator
+ private String _sTimeSeparator;
+ private volatile String[] _saLongTimes; // (user can override) time format
+ private volatile String[] _saShortTimes; // short time format
+ private volatile String[] _saDurationFormats; // time duration format
// Calendar specific data
- private int iFirstDayOfWeek = undef; // (user can override) first day of week (gregorian really)
- private int iFirstWeekOfYear = undef; // (user can override) first week of year (gregorian really)
- private volatile int[] waCalendars; // all available calendar type(s). The first one is the default calendar
+ private int _iFirstDayOfWeek = undef; // (user can override) first day of week (gregorian really)
+ private int _iFirstWeekOfYear = undef; // (user can override) first week of year (gregorian really)
+ private volatile CalendarId[] _waCalendars; // all available calendar type(s). The first one is the default calendar
// Store for specific data about each calendar
- private CalendarData[] calendars; // Store for specific calendar data
+ private CalendarData[] _calendars; // Store for specific calendar data
// Text information
- private int iReadingLayout = undef; // Reading layout data
+ private int _iReadingLayout = undef; // Reading layout data
// 0 - Left to right (eg en-US)
// 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
- private String sTextInfo; // Text info name to use for custom
- private String sCompareInfo; // Compare info name (including sorting key) to use if custom
- private String sScripts; // Typical Scripts for this locale (latn;cyrl; etc)
-
- private int iDefaultAnsiCodePage = undef; // default ansi code page ID (ACP)
- private int iDefaultOemCodePage = undef; // default oem code page ID (OCP or OEM)
- private int iDefaultMacCodePage = undef; // default macintosh code page
- private int iDefaultEbcdicCodePage = undef; // default EBCDIC code page
-
- // These are desktop only, not coreclr
- private int iLanguage; // locale ID (0409) - NO sort information
- private String sAbbrevLang; // abbreviated language name (Windows Language Name) ex: ENU
- private String sAbbrevCountry; // abbreviated country name (RegionInfo) (Windows Region Name) ex: USA
- private String sISO639Language2; // 3 char ISO 639 lang name 2 ex: eng
- private String sISO3166CountryName2; // 3 char ISO 3166 country name 2 2(RegionInfo) ex: USA (ISO)
- private int iInputLanguageHandle=undef;// input language handle
- private String sConsoleFallbackName; // The culture name for the console fallback UI culture
- private String sKeyboardsToInstall; // Keyboard installation string.
- private String fontSignature; // Font signature (16 WORDS)
-
- // The bools all need to be in one spot
- private bool bUseOverrides; // use user overrides?
- private bool bNeutral; // Flags for the culture (ie: neutral or not right now)
- private bool bWin32Installed; // Flags indicate if the culture is Win32 installed
- private bool bFramework; // Flags for indicate if the culture is one of Whidbey cultures
+ // CoreCLR depends on this even though its not exposed publicly.
+
+ private int _iDefaultAnsiCodePage = undef; // default ansi code page ID (ACP)
+ private int _iDefaultOemCodePage = undef; // default oem code page ID (OCP or OEM)
+ private int _iDefaultMacCodePage = undef; // default macintosh code page
+ private int _iDefaultEbcdicCodePage = undef; // default EBCDIC code page
+
+ private int _iLanguage; // locale ID (0409) - NO sort information
+ private bool _bUseOverrides; // use user overrides?
+ private bool _bNeutral; // Flags for the culture (ie: neutral or not right now)
// Region Name to Culture Name mapping table
// (In future would be nice to be in registry or something)
- //Using a property so we avoid creating the dictionary untill we need it
- private static Dictionary<string, string> RegionNames
+ //Using a property so we avoid creating the dictionary until we need it
+ private static StringStringDictionary RegionNames
{
- get
+ get
{
if (s_RegionNames == null)
{
- var regionNames = new Dictionary<string, string> {
- { "029", "en-029" },
- { "AE", "ar-AE" },
- { "AF", "prs-AF" },
- { "AL", "sq-AL" },
- { "AM", "hy-AM" },
- { "AR", "es-AR" },
- { "AT", "de-AT" },
- { "AU", "en-AU" },
- { "AZ", "az-Cyrl-AZ" },
- { "BA", "bs-Latn-BA" },
- { "BD", "bn-BD" },
- { "BE", "nl-BE" },
- { "BG", "bg-BG" },
- { "BH", "ar-BH" },
- { "BN", "ms-BN" },
- { "BO", "es-BO" },
- { "BR", "pt-BR" },
- { "BY", "be-BY" },
- { "BZ", "en-BZ" },
- { "CA", "en-CA" },
- { "CH", "it-CH" },
- { "CL", "es-CL" },
- { "CN", "zh-CN" },
- { "CO", "es-CO" },
- { "CR", "es-CR" },
- { "CS", "sr-Cyrl-CS" },
- { "CZ", "cs-CZ" },
- { "DE", "de-DE" },
- { "DK", "da-DK" },
- { "DO", "es-DO" },
- { "DZ", "ar-DZ" },
- { "EC", "es-EC" },
- { "EE", "et-EE" },
- { "EG", "ar-EG" },
- { "ES", "es-ES" },
- { "ET", "am-ET" },
- { "FI", "fi-FI" },
- { "FO", "fo-FO" },
- { "FR", "fr-FR" },
- { "GB", "en-GB" },
- { "GE", "ka-GE" },
- { "GL", "kl-GL" },
- { "GR", "el-GR" },
- { "GT", "es-GT" },
- { "HK", "zh-HK" },
- { "HN", "es-HN" },
- { "HR", "hr-HR" },
- { "HU", "hu-HU" },
- { "ID", "id-ID" },
- { "IE", "en-IE" },
- { "IL", "he-IL" },
- { "IN", "hi-IN" },
- { "IQ", "ar-IQ" },
- { "IR", "fa-IR" },
- { "IS", "is-IS" },
- { "IT", "it-IT" },
- { "IV", "" },
- { "JM", "en-JM" },
- { "JO", "ar-JO" },
- { "JP", "ja-JP" },
- { "KE", "sw-KE" },
- { "KG", "ky-KG" },
- { "KH", "km-KH" },
- { "KR", "ko-KR" },
- { "KW", "ar-KW" },
- { "KZ", "kk-KZ" },
- { "LA", "lo-LA" },
- { "LB", "ar-LB" },
- { "LI", "de-LI" },
- { "LK", "si-LK" },
- { "LT", "lt-LT" },
- { "LU", "lb-LU" },
- { "LV", "lv-LV" },
- { "LY", "ar-LY" },
- { "MA", "ar-MA" },
- { "MC", "fr-MC" },
- { "ME", "sr-Latn-ME" },
- { "MK", "mk-MK" },
- { "MN", "mn-MN" },
- { "MO", "zh-MO" },
- { "MT", "mt-MT" },
- { "MV", "dv-MV" },
- { "MX", "es-MX" },
- { "MY", "ms-MY" },
- { "NG", "ig-NG" },
- { "NI", "es-NI" },
- { "NL", "nl-NL" },
- { "NO", "nn-NO" },
- { "NP", "ne-NP" },
- { "NZ", "en-NZ" },
- { "OM", "ar-OM" },
- { "PA", "es-PA" },
- { "PE", "es-PE" },
- { "PH", "en-PH" },
- { "PK", "ur-PK" },
- { "PL", "pl-PL" },
- { "PR", "es-PR" },
- { "PT", "pt-PT" },
- { "PY", "es-PY" },
- { "QA", "ar-QA" },
- { "RO", "ro-RO" },
- { "RS", "sr-Latn-RS" },
- { "RU", "ru-RU" },
- { "RW", "rw-RW" },
- { "SA", "ar-SA" },
- { "SE", "sv-SE" },
- { "SG", "zh-SG" },
- { "SI", "sl-SI" },
- { "SK", "sk-SK" },
- { "SN", "wo-SN" },
- { "SV", "es-SV" },
- { "SY", "ar-SY" },
- { "TH", "th-TH" },
- { "TJ", "tg-Cyrl-TJ" },
- { "TM", "tk-TM" },
- { "TN", "ar-TN" },
- { "TR", "tr-TR" },
- { "TT", "en-TT" },
- { "TW", "zh-TW" },
- { "UA", "uk-UA" },
- { "US", "en-US" },
- { "UY", "es-UY" },
- { "UZ", "uz-Cyrl-UZ" },
- { "VE", "es-VE" },
- { "VN", "vi-VN" },
- { "YE", "ar-YE" },
- { "ZA", "af-ZA" },
- { "ZW", "en-ZW" }
- };
- s_RegionNames = regionNames;
- }
- return s_RegionNames;
- }
- }
- private volatile static Dictionary<string, string> s_RegionNames;
-
- /////////////////////////////////////////////////////////////////////////
- // Build our invariant information
- //
- // We need an invariant instance, which we build hard-coded
- /////////////////////////////////////////////////////////////////////////
- internal static CultureData Invariant
- {
- get
- {
- if (s_Invariant == null)
- {
- // Make a new culturedata
- CultureData invariant = new CultureData();
-
- // Call the native code to get the value of bWin32Installed.
- // For versions <= Vista, we set this to false for compatibility with v2.
- // For Windows 7, the flag is true.
- invariant.bUseOverrides = false;
- invariant.sRealName = "";
-
- // Ask the native code to fill it out for us, we only need the field IsWin32Installed
- nativeInitCultureData(invariant);
-
- // Basics
- // Note that we override the resources since this IS NOT supposed to change (by definition)
- invariant.bUseOverrides = false;
- invariant.sRealName = ""; // Name you passed in (ie: en-US, en, or de-DE_phoneb)
- invariant.sWindowsName = ""; // Name OS thinks the object is (ie: de-DE_phoneb, or en-US (even if en was passed in))
-
- // Identity
- invariant.sName = ""; // locale name (ie: en-us)
- invariant.sParent = ""; // Parent name (which may be a custom locale/culture)
- invariant.bNeutral = false; // Flags for the culture (ie: neutral or not right now)
- // Don't set invariant.bWin32Installed, we used nativeInitCultureData for that.
- invariant.bFramework = true;
-
- invariant.sEnglishDisplayName = "Invariant Language (Invariant Country)"; // English pretty name for this locale
- invariant.sNativeDisplayName = "Invariant Language (Invariant Country)"; // Native pretty name for this locale
- invariant.sSpecificCulture = ""; // The culture name to be used in CultureInfo.CreateSpecificCulture()
-
- // Language
- invariant.sISO639Language = "iv"; // ISO 639 Language Name
- invariant.sLocalizedLanguage = "Invariant Language"; // Display name for this Language
- invariant.sEnglishLanguage = "Invariant Language"; // English name for this language
- invariant.sNativeLanguage = "Invariant Language"; // Native name of this language
-
- // Region
- invariant.sRegionName = "IV"; // (RegionInfo)
- // Unused for now:
- // invariant.iCountry =1; // country code (RegionInfo)
- invariant.iGeoId = 244; // GeoId (Windows Only)
- invariant.sEnglishCountry = "Invariant Country"; // english country name (RegionInfo)
- invariant.sNativeCountry = "Invariant Country"; // native country name (Windows Only)
- invariant.sISO3166CountryName = "IV"; // (RegionInfo), ie: US
-
- // Numbers
- invariant.sPositiveSign = "+"; // positive sign
- invariant.sNegativeSign = "-"; // negative sign
- invariant.saNativeDigits = new String[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; // native characters for digits 0-9
- invariant.iDigitSubstitution = 1; // Digit substitution 0=context, 1=none/arabic, 2=Native/national (2 seems to be unused) (Windows Only)
- invariant.iLeadingZeros = 1; // leading zeros 0=no leading zeros, 1=leading zeros
- invariant.iDigits = 2; // number of fractional digits
- invariant.iNegativeNumber = 1; // negative number format
- invariant.waGrouping = new int[] { 3 }; // grouping of digits
- invariant.sDecimalSeparator = "."; // decimal separator
- invariant.sThousandSeparator = ","; // thousands separator
- invariant.sNaN = "NaN"; // Not a Number
- invariant.sPositiveInfinity = "Infinity"; // + Infinity
- invariant.sNegativeInfinity = "-Infinity"; // - Infinity
-
- // Percent
- invariant.iNegativePercent = 0; // Negative Percent (0-3)
- invariant.iPositivePercent = 0; // Positive Percent (0-11)
- invariant.sPercent = "%"; // Percent (%) symbol
- invariant.sPerMille = "\x2030"; // PerMille(‰) symbol
-
- // Currency
- invariant.sCurrency = "\x00a4"; // local monetary symbol "¤: for international monetary symbol
- invariant.sIntlMonetarySymbol = "XDR"; // international monetary symbol (RegionInfo)
- invariant.sEnglishCurrency = "International Monetary Fund"; // English name for this currency (Windows Only)
- invariant.sNativeCurrency = "International Monetary Fund"; // Native name for this currency (Windows Only)
- invariant.iCurrencyDigits = 2; // # local monetary fractional digits
- invariant.iCurrency = 0; // positive currency format
- invariant.iNegativeCurrency = 0; // negative currency format
- invariant.waMonetaryGrouping = new int[] { 3 }; // monetary grouping of digits
- invariant.sMonetaryDecimal = "."; // monetary decimal separator
- invariant.sMonetaryThousand = ","; // monetary thousands separator
-
- // Misc
- invariant.iMeasure = 0; // system of measurement 0=metric, 1=US (RegionInfo)
- invariant.sListSeparator = ","; // list separator
- // Unused for now:
- // invariant.iPaperSize =9; // default paper size (RegionInfo)
- // invariant.waFontSignature ="\x0002\x0000\x0000\x0000\x0000\x0000\x0000\x8000\x0001\x0000\x0000\x8000\x0001\x0000\x0000\x8000"; // Font signature (16 WORDS) (Windows Only)
-
- // Time
- invariant.sAM1159 = "AM"; // AM designator
- invariant.sPM2359 = "PM"; // PM designator
- invariant.saLongTimes = new String[] { "HH:mm:ss" }; // time format
- invariant.saShortTimes = new String[] { "HH:mm", "hh:mm tt", "H:mm", "h:mm tt" }; // short time format
- invariant.saDurationFormats = new String[] { "HH:mm:ss" }; // time duration format
-
- // Calendar specific data
- invariant.iFirstDayOfWeek = 0; // first day of week
- invariant.iFirstWeekOfYear = 0; // first week of year
- invariant.waCalendars = new int[] { (int)CalendarId.GREGORIAN }; // all available calendar type(s). The first one is the default calendar
-
- // Store for specific data about each calendar
- invariant.calendars = new CalendarData[CalendarData.MAX_CALENDARS];
- invariant.calendars[0] = CalendarData.Invariant;
-
- // Text information
- invariant.iReadingLayout = 0; // Reading Layout = RTL
-
- invariant.sTextInfo = ""; // Text info name to use for custom
- invariant.sCompareInfo = ""; // Compare info name (including sorting key) to use if custom
- invariant.sScripts = "Latn;"; // Typical Scripts for this locale (latn,cyrl, etc)
-
- invariant.iLanguage = 0x007f; // locale ID (0409) - NO sort information
- invariant.iDefaultAnsiCodePage = 1252; // default ansi code page ID (ACP)
- invariant.iDefaultOemCodePage = 437; // default oem code page ID (OCP or OEM)
- invariant.iDefaultMacCodePage = 10000; // default macintosh code page
- invariant.iDefaultEbcdicCodePage = 037; // default EBCDIC code page
- invariant.sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name)
- invariant.sAbbrevCountry = "IVC"; // abbreviated country name (RegionInfo) (Windows Region Name)
- invariant.sISO639Language2 = "ivl"; // 3 char ISO 639 lang name 2
- invariant.sISO3166CountryName2 = "ivc"; // 3 char ISO 3166 country name 2 2(RegionInfo)
- invariant.iInputLanguageHandle = 0x007f; // input language handle
- invariant.sConsoleFallbackName = ""; // The culture name for the console fallback UI culture
- invariant.sKeyboardsToInstall = "0409:00000409"; // Keyboard installation string.
- // Remember it
- s_Invariant = invariant;
+ StringStringDictionary regionNames = new StringStringDictionary(211 /* prime */);
+
+ regionNames.Add("029", "en-029");
+ regionNames.Add("AE", "ar-AE");
+ regionNames.Add("AF", "prs-AF");
+ regionNames.Add("AL", "sq-AL");
+ regionNames.Add("AM", "hy-AM");
+ regionNames.Add("AR", "es-AR");
+ regionNames.Add("AT", "de-AT");
+ regionNames.Add("AU", "en-AU");
+ regionNames.Add("AZ", "az-Cyrl-AZ");
+ regionNames.Add("BA", "bs-Latn-BA");
+ regionNames.Add("BD", "bn-BD");
+ regionNames.Add("BE", "nl-BE");
+ regionNames.Add("BG", "bg-BG");
+ regionNames.Add("BH", "ar-BH");
+ regionNames.Add("BN", "ms-BN");
+ regionNames.Add("BO", "es-BO");
+ regionNames.Add("BR", "pt-BR");
+ regionNames.Add("BY", "be-BY");
+ regionNames.Add("BZ", "en-BZ");
+ regionNames.Add("CA", "en-CA");
+ regionNames.Add("CH", "it-CH");
+ regionNames.Add("CL", "es-CL");
+ regionNames.Add("CN", "zh-CN");
+ regionNames.Add("CO", "es-CO");
+ regionNames.Add("CR", "es-CR");
+ regionNames.Add("CS", "sr-Cyrl-CS");
+ regionNames.Add("CZ", "cs-CZ");
+ regionNames.Add("DE", "de-DE");
+ regionNames.Add("DK", "da-DK");
+ regionNames.Add("DO", "es-DO");
+ regionNames.Add("DZ", "ar-DZ");
+ regionNames.Add("EC", "es-EC");
+ regionNames.Add("EE", "et-EE");
+ regionNames.Add("EG", "ar-EG");
+ regionNames.Add("ES", "es-ES");
+ regionNames.Add("ET", "am-ET");
+ regionNames.Add("FI", "fi-FI");
+ regionNames.Add("FO", "fo-FO");
+ regionNames.Add("FR", "fr-FR");
+ regionNames.Add("GB", "en-GB");
+ regionNames.Add("GE", "ka-GE");
+ regionNames.Add("GL", "kl-GL");
+ regionNames.Add("GR", "el-GR");
+ regionNames.Add("GT", "es-GT");
+ regionNames.Add("HK", "zh-HK");
+ regionNames.Add("HN", "es-HN");
+ regionNames.Add("HR", "hr-HR");
+ regionNames.Add("HU", "hu-HU");
+ regionNames.Add("ID", "id-ID");
+ regionNames.Add("IE", "en-IE");
+ regionNames.Add("IL", "he-IL");
+ regionNames.Add("IN", "hi-IN");
+ regionNames.Add("IQ", "ar-IQ");
+ regionNames.Add("IR", "fa-IR");
+ regionNames.Add("IS", "is-IS");
+ regionNames.Add("IT", "it-IT");
+ regionNames.Add("IV", "");
+ regionNames.Add("JM", "en-JM");
+ regionNames.Add("JO", "ar-JO");
+ regionNames.Add("JP", "ja-JP");
+ regionNames.Add("KE", "sw-KE");
+ regionNames.Add("KG", "ky-KG");
+ regionNames.Add("KH", "km-KH");
+ regionNames.Add("KR", "ko-KR");
+ regionNames.Add("KW", "ar-KW");
+ regionNames.Add("KZ", "kk-KZ");
+ regionNames.Add("LA", "lo-LA");
+ regionNames.Add("LB", "ar-LB");
+ regionNames.Add("LI", "de-LI");
+ regionNames.Add("LK", "si-LK");
+ regionNames.Add("LT", "lt-LT");
+ regionNames.Add("LU", "lb-LU");
+ regionNames.Add("LV", "lv-LV");
+ regionNames.Add("LY", "ar-LY");
+ regionNames.Add("MA", "ar-MA");
+ regionNames.Add("MC", "fr-MC");
+ regionNames.Add("ME", "sr-Latn-ME");
+ regionNames.Add("MK", "mk-MK");
+ regionNames.Add("MN", "mn-MN");
+ regionNames.Add("MO", "zh-MO");
+ regionNames.Add("MT", "mt-MT");
+ regionNames.Add("MV", "dv-MV");
+ regionNames.Add("MX", "es-MX");
+ regionNames.Add("MY", "ms-MY");
+ regionNames.Add("NG", "ig-NG");
+ regionNames.Add("NI", "es-NI");
+ regionNames.Add("NL", "nl-NL");
+ regionNames.Add("NO", "nn-NO");
+ regionNames.Add("NP", "ne-NP");
+ regionNames.Add("NZ", "en-NZ");
+ regionNames.Add("OM", "ar-OM");
+ regionNames.Add("PA", "es-PA");
+ regionNames.Add("PE", "es-PE");
+ regionNames.Add("PH", "en-PH");
+ regionNames.Add("PK", "ur-PK");
+ regionNames.Add("PL", "pl-PL");
+ regionNames.Add("PR", "es-PR");
+ regionNames.Add("PT", "pt-PT");
+ regionNames.Add("PY", "es-PY");
+ regionNames.Add("QA", "ar-QA");
+ regionNames.Add("RO", "ro-RO");
+ regionNames.Add("RS", "sr-Latn-RS");
+ regionNames.Add("RU", "ru-RU");
+ regionNames.Add("RW", "rw-RW");
+ regionNames.Add("SA", "ar-SA");
+ regionNames.Add("SE", "sv-SE");
+ regionNames.Add("SG", "zh-SG");
+ regionNames.Add("SI", "sl-SI");
+ regionNames.Add("SK", "sk-SK");
+ regionNames.Add("SN", "wo-SN");
+ regionNames.Add("SV", "es-SV");
+ regionNames.Add("SY", "ar-SY");
+ regionNames.Add("TH", "th-TH");
+ regionNames.Add("TJ", "tg-Cyrl-TJ");
+ regionNames.Add("TM", "tk-TM");
+ regionNames.Add("TN", "ar-TN");
+ regionNames.Add("TR", "tr-TR");
+ regionNames.Add("TT", "en-TT");
+ regionNames.Add("TW", "zh-TW");
+ regionNames.Add("UA", "uk-UA");
+ regionNames.Add("US", "en-US");
+ regionNames.Add("UY", "es-UY");
+ regionNames.Add("UZ", "uz-Cyrl-UZ");
+ regionNames.Add("VE", "es-VE");
+ regionNames.Add("VN", "vi-VN");
+ regionNames.Add("YE", "ar-YE");
+ regionNames.Add("ZA", "af-ZA");
+ regionNames.Add("ZW", "en-ZW");
+
+ s_RegionNames = regionNames;
}
- return s_Invariant;
- }
- }
- private volatile static CultureData s_Invariant;
- ///////////////
- // Constructors //
- ///////////////
- // Cache of cultures we've already looked up
- private static volatile Dictionary<String, CultureData> s_cachedCultures;
-
- [FriendAccessAllowed]
- internal static CultureData GetCultureData(String cultureName, bool useUserOverride)
- {
- // First do a shortcut for Invariant
- if (String.IsNullOrEmpty(cultureName))
- {
- return CultureData.Invariant;
- }
-
- // Try the hash table first
- String hashName = AnsiToLower(useUserOverride ? cultureName : cultureName + '*');
- Dictionary<String, CultureData> tempHashTable = s_cachedCultures;
- if (tempHashTable == null)
- {
- // No table yet, make a new one
- tempHashTable = new Dictionary<String, CultureData>();
- }
- else
- {
- // Check the hash table
- CultureData retVal;
- lock (((ICollection)tempHashTable).SyncRoot)
- {
- tempHashTable.TryGetValue(hashName, out retVal);
- }
- if (retVal != null)
- {
- return retVal;
- }
- }
-
- // Not found in the hash table, need to see if we can build one that works for us
- CultureData culture = CreateCultureData(cultureName, useUserOverride);
- if (culture == null)
- {
- return null;
- }
-
- // Found one, add it to the cache
- lock (((ICollection)tempHashTable).SyncRoot)
- {
- tempHashTable[hashName] = culture;
- }
-
- // Copy the hashtable to the corresponding member variables. This will potentially overwrite
- // new tables simultaneously created by a new thread, but maximizes thread safety.
- s_cachedCultures = tempHashTable;
-
- return culture;
- }
-
- private static CultureData CreateCultureData(string cultureName, bool useUserOverride)
- {
- CultureData culture = new CultureData();
- culture.bUseOverrides = useUserOverride;
- culture.sRealName = cultureName;
-
- // Ask native code if that one's real
- if (culture.InitCultureData() == false)
- {
- return null;
- }
-
- return culture;
- }
-
- private bool InitCultureData()
- {
- if (nativeInitCultureData(this) == false)
- {
- return false;
+ return s_RegionNames;
}
- return true;
}
// Cache of regions we've already looked up
- private static volatile Dictionary<String, CultureData> s_cachedRegions;
+ private static volatile StringCultureDataDictionary s_cachedRegions;
+ private static volatile StringStringDictionary s_RegionNames;
internal static CultureData GetCultureDataForRegion(String cultureName, bool useUserOverride)
{
@@ -571,16 +333,16 @@ namespace System.Globalization
// Try the hash table next
String hashName = AnsiToLower(useUserOverride ? cultureName : cultureName + '*');
- Dictionary<String, CultureData> tempHashTable = s_cachedRegions;
+ StringCultureDataDictionary tempHashTable = s_cachedRegions;
if (tempHashTable == null)
{
// No table yet, make a new one
- tempHashTable = new Dictionary<String, CultureData>();
+ tempHashTable = new StringCultureDataDictionary();
}
else
{
// Check the hash table
- lock (((ICollection)tempHashTable).SyncRoot)
+ lock (s_lock)
{
tempHashTable.TryGetValue(hashName, out retVal);
}
@@ -598,36 +360,25 @@ namespace System.Globalization
if (retVal == null || (retVal.IsNeutralCulture == true))
{
// Not a valid mapping, try the hard coded table
- if (RegionNames.ContainsKey(cultureName))
+ string name;
+ if (RegionNames.TryGetValue(cultureName, out name))
{
// Make sure we can get culture data for it
- retVal = GetCultureData(RegionNames[cultureName], useUserOverride);
+ retVal = GetCultureData(name, useUserOverride);
}
}
// If not found in the hard coded table we'll have to find a culture that works for us
if (retVal == null || (retVal.IsNeutralCulture == true))
{
- // Not found in the hard coded table, need to see if we can find a culture that works for us
- // Not a real culture name, see if it matches a region name
- // (we just return the first culture we match)
- CultureInfo[] specifics = SpecificCultures;
- for (int i = 0; i < specifics.Length; i++)
- {
- if (String.Compare(specifics[i].m_cultureData.SREGIONNAME, cultureName, StringComparison.OrdinalIgnoreCase) == 0)
- {
- // Matched, use this culture
- retVal = specifics[i].m_cultureData;
- break;
- }
- }
+ retVal = GetCultureDataFromRegionName(cultureName);
}
- // If we found one we can use, then cash it for next time
+ // If we found one we can use, then cache it for next time
if (retVal != null && (retVal.IsNeutralCulture == false))
{
// first add it to the cache
- lock (((ICollection)tempHashTable).SyncRoot)
+ lock (s_lock)
{
tempHashTable[hashName] = retVal;
}
@@ -647,54 +398,11 @@ namespace System.Globalization
return retVal;
}
-#if FEATURE_USE_LCID
- // Obtain locale name from LCID
- // NOTE: This will get neutral names, unlike the OS API
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String LCIDToLocaleName(int lcid);
-
- // We'd rather people use the named version since this doesn't allow custom locales
- internal static CultureData GetCultureData(int culture, bool bUseUserOverride)
- {
- String localeName = null;
- CultureData retVal = null;
-
- if (localeName == null)
- {
- // Convert the lcid to a name, then use that
- // Note that this'll return neutral names (unlike Vista native API)
- localeName = LCIDToLocaleName(culture);
- }
-
- // If its not valid, then throw
- if (String.IsNullOrEmpty(localeName))
- {
- // Could be valid for Invariant
- if (culture == 0x007f)
- return Invariant;
- }
- else
- {
- // Valid name, use it
- retVal = GetCultureData(localeName, bUseUserOverride);
- }
-
- // If not successful, throw
- if (retVal == null)
- throw new CultureNotFoundException(
- nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported"));
-
- // Return the one we found
- return retVal;
- }
-#endif
-
// Clear our internal caches
internal static void ClearCachedData()
{
s_cachedCultures = null;
s_cachedRegions = null;
- s_replacementCultureNames = null;
}
internal static CultureInfo[] GetCultures(CultureTypes types)
@@ -703,23 +411,16 @@ namespace System.Globalization
#pragma warning disable 618
// Validate flags
if ((int)types <= 0 || ((int)types & (int)~(CultureTypes.NeutralCultures | CultureTypes.SpecificCultures |
- CultureTypes.InstalledWin32Cultures | CultureTypes.UserCustomCulture |
- CultureTypes.ReplacementCultures | CultureTypes.WindowsOnlyCultures |
- CultureTypes.FrameworkCultures)) != 0)
+ CultureTypes.InstalledWin32Cultures | CultureTypes.UserCustomCulture |
+ CultureTypes.ReplacementCultures | CultureTypes.WindowsOnlyCultures |
+ CultureTypes.FrameworkCultures)) != 0)
{
- throw new ArgumentOutOfRangeException(
- nameof(types),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), CultureTypes.NeutralCultures, CultureTypes.FrameworkCultures));
+ throw new ArgumentOutOfRangeException(nameof(types),
+ SR.Format(SR.ArgumentOutOfRange_Range, CultureTypes.NeutralCultures, CultureTypes.FrameworkCultures));
}
- //
- // CHANGE FROM Whidbey
- //
// We have deprecated CultureTypes.FrameworkCultures.
// When this enum is used, we will enumerate Whidbey framework cultures (for compatibility).
- //
// We have deprecated CultureTypes.WindowsOnlyCultures.
// When this enum is used, we will return an empty array for this enum.
@@ -728,85 +429,349 @@ namespace System.Globalization
// Remove the enum as it is an no-op.
types &= (~CultureTypes.WindowsOnlyCultures);
}
+
+ if (GlobalizationMode.Invariant)
+ {
+ // in invariant mode we always return invariant culture only from the enumeration
+ return new CultureInfo[1] { new CultureInfo("") };
+ }
- String[] cultureNames = null;
+#pragma warning restore 618
+ return EnumCultures(types);
+ }
+
+ private static CultureData CreateCultureWithInvariantData()
+ {
+ // Make a new culturedata
+ CultureData invariant = new CultureData();
+
+ // Basics
+ // Note that we override the resources since this IS NOT supposed to change (by definition)
+ invariant._bUseOverrides = false;
+ invariant._sRealName = ""; // Name you passed in (ie: en-US, en, or de-DE_phoneb)
+ invariant._sWindowsName = ""; // Name OS thinks the object is (ie: de-DE_phoneb, or en-US (even if en was passed in))
+
+ // Identity
+ invariant._sName = ""; // locale name (ie: en-us)
+ invariant._sParent = ""; // Parent name (which may be a custom locale/culture)
+ invariant._bNeutral = false; // Flags for the culture (ie: neutral or not right now)
+ invariant._sEnglishDisplayName = "Invariant Language (Invariant Country)"; // English pretty name for this locale
+ invariant._sNativeDisplayName = "Invariant Language (Invariant Country)"; // Native pretty name for this locale
+ invariant._sSpecificCulture = ""; // The culture name to be used in CultureInfo.CreateSpecificCulture()
+
+ // Language
+ invariant._sISO639Language = "iv"; // ISO 639 Language Name
+ invariant._sISO639Language2 = "ivl"; // 3 char ISO 639 lang name 2
+ invariant._sLocalizedLanguage = "Invariant Language"; // Display name for this Language
+ invariant._sEnglishLanguage = "Invariant Language"; // English name for this language
+ invariant._sNativeLanguage = "Invariant Language"; // Native name of this language
+ invariant._sAbbrevLang = "IVL"; // abbreviated language name (Windows Language Name)
+ invariant._sConsoleFallbackName = ""; // The culture name for the console fallback UI culture
+ invariant._iInputLanguageHandle = 0x07F; // input language handle
+
+ // Region
+ invariant._sRegionName = "IV"; // (RegionInfo)
+ invariant._sEnglishCountry = "Invariant Country"; // english country name (RegionInfo)
+ invariant._sNativeCountry = "Invariant Country"; // native country name (Windows Only)
+ invariant._sISO3166CountryName = "IV"; // (RegionInfo), ie: US
+ invariant._sISO3166CountryName2 = "ivc"; // 3 char ISO 3166 country name 2 2(RegionInfo)
+ invariant._iGeoId = 244; // GeoId (Windows Only)
+
+ // Numbers
+ invariant._sPositiveSign = "+"; // positive sign
+ invariant._sNegativeSign = "-"; // negative sign
+ invariant._iDigits = 2; // number of fractional digits
+ invariant._iNegativeNumber = 1; // negative number format
+ invariant._waGrouping = new int[] { 3 }; // grouping of digits
+ invariant._sDecimalSeparator = "."; // decimal separator
+ invariant._sThousandSeparator = ","; // thousands separator
+ invariant._sNaN = "NaN"; // Not a Number
+ invariant._sPositiveInfinity = "Infinity"; // + Infinity
+ invariant._sNegativeInfinity = "-Infinity"; // - Infinity
+
+ // Percent
+ invariant._iNegativePercent = 0; // Negative Percent (0-3)
+ invariant._iPositivePercent = 0; // Positive Percent (0-11)
+ invariant._sPercent = "%"; // Percent (%) symbol
+ invariant._sPerMille = "\x2030"; // PerMille symbol
+
+ // Currency
+ invariant._sCurrency = "\x00a4"; // local monetary symbol: for international monetary symbol
+ invariant._sIntlMonetarySymbol = "XDR"; // international monetary symbol (RegionInfo)
+ invariant._sEnglishCurrency = "International Monetary Fund"; // English name for this currency (Windows Only)
+ invariant._sNativeCurrency = "International Monetary Fund"; // Native name for this currency (Windows Only)
+ invariant._iCurrencyDigits = 2; // # local monetary fractional digits
+ invariant._iCurrency = 0; // positive currency format
+ invariant._iNegativeCurrency = 0; // negative currency format
+ invariant._waMonetaryGrouping = new int[] { 3 }; // monetary grouping of digits
+ invariant._sMonetaryDecimal = "."; // monetary decimal separator
+ invariant._sMonetaryThousand = ","; // monetary thousands separator
+
+ // Misc
+ invariant._iMeasure = 0; // system of measurement 0=metric, 1=US (RegionInfo)
+ invariant._sListSeparator = ","; // list separator
+
+ // Time
+ invariant._sTimeSeparator = ":";
+ invariant._sAM1159 = "AM"; // AM designator
+ invariant._sPM2359 = "PM"; // PM designator
+ invariant._saLongTimes = new String[] { "HH:mm:ss" }; // time format
+ invariant._saShortTimes = new String[] { "HH:mm", "hh:mm tt", "H:mm", "h:mm tt" }; // short time format
+ invariant._saDurationFormats = new String[] { "HH:mm:ss" }; // time duration format
+
+
+ // Calendar specific data
+ invariant._iFirstDayOfWeek = 0; // first day of week
+ invariant._iFirstWeekOfYear = 0; // first week of year
+ invariant._waCalendars = new CalendarId[] { CalendarId.GREGORIAN }; // all available calendar type(s). The first one is the default calendar
+
+ // Store for specific data about each calendar
+ invariant._calendars = new CalendarData[CalendarData.MAX_CALENDARS];
+ invariant._calendars[0] = CalendarData.Invariant;
+
+ // Text information
+ invariant._iReadingLayout = 0;
+
+ // These are desktop only, not coreclr
+
+ invariant._iLanguage = CultureInfo.LOCALE_INVARIANT; // locale ID (0409) - NO sort information
+ invariant._iDefaultAnsiCodePage = 1252; // default ansi code page ID (ACP)
+ invariant._iDefaultOemCodePage = 437; // default oem code page ID (OCP or OEM)
+ invariant._iDefaultMacCodePage = 10000; // default macintosh code page
+ invariant._iDefaultEbcdicCodePage = 037; // default EBCDIC code page
+
+ if (GlobalizationMode.Invariant)
+ {
+ invariant._sLocalizedDisplayName = invariant._sNativeDisplayName;
+ invariant._sLocalizedCountry = invariant._sNativeCountry;
+ }
+
+ return invariant;
+ }
- //
- // Call nativeEnumCultureNames() to get a string array of culture names based on the specified
- // enumeration type.
- //
- // nativeEnumCultureNames is a QCall. We need to use a reference to return the string array
- // allocated from the QCall. That ref has to be wrapped as object handle.
- // See vm\qcall.h for details in QCall.
- //
+ /////////////////////////////////////////////////////////////////////////
+ // Build our invariant information
+ //
+ // We need an invariant instance, which we build hard-coded
+ /////////////////////////////////////////////////////////////////////////
+ internal static CultureData Invariant
+ {
+ get
+ {
+ if (s_Invariant == null)
+ {
+ // Remember it
+ s_Invariant = CreateCultureWithInvariantData();
+ }
+ return s_Invariant;
+ }
+ }
+ private volatile static CultureData s_Invariant;
- if (nativeEnumCultureNames((int)types, JitHelpers.GetObjectHandleOnStack(ref cultureNames)) == 0)
+ ///////////////
+ // Constructors //
+ ///////////////
+ // Cache of cultures we've already looked up
+ private static volatile StringCultureDataDictionary s_cachedCultures;
+ private static readonly Lock s_lock = new Lock();
+
+ internal static CultureData GetCultureData(String cultureName, bool useUserOverride)
+ {
+ // First do a shortcut for Invariant
+ if (String.IsNullOrEmpty(cultureName))
{
- return new CultureInfo[0];
+ return CultureData.Invariant;
}
- int arrayLength = cultureNames.Length;
+ // Try the hash table first
+ String hashName = AnsiToLower(useUserOverride ? cultureName : cultureName + '*');
+ StringCultureDataDictionary tempHashTable = s_cachedCultures;
+ if (tempHashTable == null)
+ {
+ // No table yet, make a new one
+ tempHashTable = new StringCultureDataDictionary();
+ }
+ else
+ {
+ // Check the hash table
+ bool ret;
+ CultureData retVal;
+ lock (s_lock)
+ {
+ ret = tempHashTable.TryGetValue(hashName, out retVal);
+ }
+ if (ret && retVal != null)
+ {
+ return retVal;
+ }
+ }
- CultureInfo[] cultures = new CultureInfo[arrayLength];
+ // Not found in the hash table, need to see if we can build one that works for us
+ CultureData culture = CreateCultureData(cultureName, useUserOverride);
+ if (culture == null)
+ {
+ return null;
+ }
- for (int i = 0; i < cultureNames.Length; i++)
+ // Found one, add it to the cache
+ lock (s_lock)
{
- cultures[i] = new CultureInfo(cultureNames[i]);
+ tempHashTable[hashName] = culture;
}
-#pragma warning restore 618
- return cultures;
- }
+ // Copy the hashtable to the corresponding member variables. This will potentially overwrite
+ // new tables simultaneously created by a new thread, but maximizes thread safety.
+ s_cachedCultures = tempHashTable;
- internal static volatile CultureInfo[] specificCultures;
+ return culture;
+ }
- private static CultureInfo[] SpecificCultures
+ private static unsafe string NormalizeCultureName(string name, out bool isNeutralName)
{
- get
+ isNeutralName = true;
+ int i = 0;
+
+ Debug.Assert(name.Length <= LOCALE_NAME_MAX_LENGTH);
+
+ char *pName = stackalloc char[LOCALE_NAME_MAX_LENGTH];
+ bool changed = false;
+
+ while (i < name.Length && name[i] != '-' && name[i] != '_')
{
- if (specificCultures == null)
- specificCultures = GetCultures(CultureTypes.SpecificCultures);
+ if (name[i] >= 'A' && name[i] <= 'Z')
+ {
+ // lowercase characters before '-'
+ pName[i] = (char) (((int)name[i]) + 0x20);
+ changed = true;
+ }
+ else
+ {
+ pName[i] = name[i];
+ }
+ i++;
+ }
- return specificCultures;
+ if (i < name.Length)
+ {
+ // this is not perfect to detect the non neutral cultures but it is good enough when we are running in invariant mode
+ isNeutralName = false;
}
+
+ while (i < name.Length)
+ {
+ if (name[i] >= 'a' && name[i] <= 'z')
+ {
+ pName[i] = (char) (((int)name[i]) - 0x20);
+ changed = true;
+ }
+ else
+ {
+ pName[i] = name[i];
+ }
+ i++;
+ }
+
+ if (changed)
+ return new string(pName, 0, name.Length);
+
+ return name;
}
- internal bool IsReplacementCulture
+ private static CultureData CreateCultureData(string cultureName, bool useUserOverride)
{
- get
+ if (GlobalizationMode.Invariant)
{
- return IsReplacementCultureName(this.SNAME);
+ CultureInfo.VerifyCultureName(cultureName, true);
+ CultureData cd = CreateCultureWithInvariantData();
+ cd._bUseOverrides = useUserOverride;
+ cd._sName = NormalizeCultureName(cultureName, out cd._bNeutral);
+ cd._sRealName = cd._sName;
+ cd._sWindowsName = cd._sName;
+ cd._iLanguage = CultureInfo.LOCALE_CUSTOM_UNSPECIFIED;
+
+ return cd;
}
- }
- internal static volatile String[] s_replacementCultureNames;
+ CultureData culture = new CultureData();
+ culture._bUseOverrides = useUserOverride;
+ culture._sRealName = cultureName;
- ////////////////////////////////////////////////////////////////////////
- //
- // Cache for the known replacement cultures.
- // This is used by CultureInfo.CultureType to check if a culture is a
- // replacement culture.
- //
- ////////////////////////////////////////////////////////////////////////
+ // Ask native code if that one's real
+ if (culture.InitCultureData() == false)
+ {
+ if (culture.InitCompatibilityCultureData() == false)
+ {
+ return null;
+ }
+ }
+ return culture;
+ }
- private static bool IsReplacementCultureName(String name)
+ private bool InitCompatibilityCultureData()
{
- Debug.Assert(name != null, "IsReplacementCultureName(): name should not be null");
- String[] replacementCultureNames = s_replacementCultureNames;
- if (replacementCultureNames == null)
+ // for compatibility handle the deprecated ids: zh-chs, zh-cht
+ string cultureName = _sRealName;
+
+ string fallbackCultureName;
+ string realCultureName;
+ switch (AnsiToLower(cultureName))
{
- if (nativeEnumCultureNames((int)CultureTypes.ReplacementCultures, JitHelpers.GetObjectHandleOnStack(ref replacementCultureNames)) == 0)
- {
+ case "zh-chs":
+ fallbackCultureName = "zh-Hans";
+ realCultureName = "zh-CHS";
+ break;
+ case "zh-cht":
+ fallbackCultureName = "zh-Hant";
+ realCultureName = "zh-CHT";
+ break;
+ default:
return false;
- }
+ }
+
+ _sRealName = fallbackCultureName;
+ if (InitCultureData() == false)
+ {
+ return false;
+ }
+ // fixup our data
+ _sName = realCultureName; // the name that goes back to the user
+ _sParent = fallbackCultureName;
+
+ return true;
+ }
+
+ // We'd rather people use the named version since this doesn't allow custom locales
+ internal static CultureData GetCultureData(int culture, bool bUseUserOverride)
+ {
+ string localeName = null;
+ CultureData retVal = null;
+
+ if (culture == CultureInfo.LOCALE_INVARIANT)
+ return Invariant;
+
+ if (GlobalizationMode.Invariant)
+ {
+ // LCID is not supported in the InvariantMode
+ throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
+ }
+
+ // Convert the lcid to a name, then use that
+ // Note that this will return neutral names (unlike Vista native API)
+ localeName = LCIDToLocaleName(culture);
- // Even if we don't have any replacement cultures, the returned replacementCultureNames will still an empty string array, not null.
- Debug.Assert(name != null, "IsReplacementCultureName(): replacementCultureNames should not be null");
- Array.Sort(replacementCultureNames);
- s_replacementCultureNames = replacementCultureNames;
+ if (!String.IsNullOrEmpty(localeName))
+ {
+ // Valid name, use it
+ retVal = GetCultureData(localeName, bUseUserOverride);
}
- return Array.BinarySearch(replacementCultureNames, name) >= 0;
+
+ // If not successful, throw
+ if (retVal == null)
+ throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
+
+ // Return the one we found
+ return retVal;
}
////////////////////////////////////////////////////////////////////////
@@ -826,17 +791,17 @@ namespace System.Globalization
{
get
{
- Debug.Assert(this.sRealName != null, "[CultureData.CultureName] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
+ Debug.Assert(_sRealName != null, "[CultureData.CultureName] Expected _sRealName to be populated by already");
// since windows doesn't know about zh-CHS and zh-CHT,
// we leave sRealName == zh-Hanx but we still need to
// pretend that it was zh-CHX.
- switch (this.sName)
+ switch (_sName)
{
case "zh-CHS":
case "zh-CHT":
- return this.sName;
+ return _sName;
}
- return this.sRealName;
+ return _sRealName;
}
}
@@ -845,7 +810,7 @@ namespace System.Globalization
{
get
{
- return this.bUseOverrides;
+ return _bUseOverrides;
}
}
@@ -854,13 +819,11 @@ namespace System.Globalization
{
get
{
- // Debug.Assert(this.sName != null,
- // "[CultureData.SNAME] Expected this.sName to be populated by COMNlsInfo::nativeInitCultureData already");
- if (this.sName == null)
+ if (_sName == null)
{
- this.sName = String.Empty;
+ _sName = String.Empty;
}
- return this.sName;
+ return _sName;
}
}
@@ -869,12 +832,12 @@ namespace System.Globalization
{
get
{
- if (this.sParent == null)
+ if (_sParent == null)
{
// Ask using the real name, so that we get parents of neutrals
- this.sParent = DoGetLocaleInfo(this.sRealName, LOCALE_SPARENT);
+ _sParent = GetLocaleInfo(_sRealName, LocaleStringData.ParentName);
}
- return this.sParent;
+ return _sParent;
}
}
@@ -883,31 +846,73 @@ namespace System.Globalization
{
get
{
- if (this.sLocalizedDisplayName == null)
+ if (_sLocalizedDisplayName == null)
{
+ if (this.IsSupplementalCustomCulture)
+ {
+ if (this.IsNeutralCulture)
+ {
+ _sLocalizedDisplayName = this.SNATIVELANGUAGE;
+ }
+ else
+ {
+ _sLocalizedDisplayName = this.SNATIVEDISPLAYNAME;
+ }
+ }
+ else
+ {
+ try
+ {
+ const string ZH_CHT = "zh-CHT";
+ const string ZH_CHS = "zh-CHS";
+
+ if (SNAME.Equals(ZH_CHT, StringComparison.OrdinalIgnoreCase))
+ {
+ _sLocalizedDisplayName = GetLanguageDisplayName("zh-Hant");
+ }
+ else if (SNAME.Equals(ZH_CHS, StringComparison.OrdinalIgnoreCase))
+ {
+ _sLocalizedDisplayName = GetLanguageDisplayName("zh-Hans");
+ }
+ else
+ {
+ _sLocalizedDisplayName = GetLanguageDisplayName(SNAME);
+ }
+ }
+ catch (Exception)
+ {
+ // do nothing
+ }
+ }
// If it hasn't been found (Windows 8 and up), fallback to the system
- if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
+ if (String.IsNullOrEmpty(_sLocalizedDisplayName))
{
// If its neutral use the language name
if (this.IsNeutralCulture)
{
- this.sLocalizedDisplayName = this.SLOCALIZEDLANGUAGE;
+ _sLocalizedDisplayName = this.SLOCALIZEDLANGUAGE;
}
else
{
- // We have to make the neutral distinction in case the OS returns a specific name
- if (CultureInfo.UserDefaultUICulture.Name.Equals(Thread.CurrentThread.CurrentUICulture.Name))
+ // 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))
{
- this.sLocalizedDisplayName = DoGetLocaleInfo(LOCALE_SLOCALIZEDDISPLAYNAME);
+ _sLocalizedDisplayName = this.SNATIVEDISPLAYNAME;
}
- if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
+ else
{
- this.sLocalizedDisplayName = this.SNATIVEDISPLAYNAME;
+ _sLocalizedDisplayName = GetLocaleInfo(LocaleStringData.LocalizedDisplayName);
}
}
}
}
- return this.sLocalizedDisplayName;
+
+ return _sLocalizedDisplayName;
}
}
@@ -916,39 +921,47 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishDisplayName == null)
+ if (_sEnglishDisplayName == null)
{
// If its neutral use the language name
if (this.IsNeutralCulture)
{
- this.sEnglishDisplayName = this.SENGLISHLANGUAGE;
+ _sEnglishDisplayName = this.SENGLISHLANGUAGE;
+ // differentiate the legacy display names
+ switch (_sName)
+ {
+ case "zh-CHS":
+ case "zh-CHT":
+ _sEnglishDisplayName += " Legacy";
+ break;
+ }
}
else
{
- this.sEnglishDisplayName = DoGetLocaleInfo(LOCALE_SENGLISHDISPLAYNAME);
+ _sEnglishDisplayName = GetLocaleInfo(LocaleStringData.EnglishDisplayName);
// if it isn't found build one:
- if (String.IsNullOrEmpty(this.sEnglishDisplayName))
+ if (String.IsNullOrEmpty(_sEnglishDisplayName))
{
// Our existing names mostly look like:
// "English" + "United States" -> "English (United States)"
// "Azeri (Latin)" + "Azerbaijan" -> "Azeri (Latin, Azerbaijan)"
- if (this.SENGLISHLANGUAGE.EndsWith(')'))
+ if (this.SENGLISHLANGUAGE[this.SENGLISHLANGUAGE.Length - 1] == ')')
{
// "Azeri (Latin)" + "Azerbaijan" -> "Azeri (Latin, Azerbaijan)"
- this.sEnglishDisplayName =
- this.SENGLISHLANGUAGE.Substring(0, this.sEnglishLanguage.Length - 1) +
+ _sEnglishDisplayName =
+ this.SENGLISHLANGUAGE.Substring(0, _sEnglishLanguage.Length - 1) +
", " + this.SENGCOUNTRY + ")";
}
else
{
// "English" + "United States" -> "English (United States)"
- this.sEnglishDisplayName = this.SENGLISHLANGUAGE + " (" + this.SENGCOUNTRY + ")";
+ _sEnglishDisplayName = this.SENGLISHLANGUAGE + " (" + this.SENGCOUNTRY + ")";
}
}
}
}
- return this.sEnglishDisplayName;
+ return _sEnglishDisplayName;
}
}
@@ -957,37 +970,47 @@ namespace System.Globalization
{
get
{
- if (this.sNativeDisplayName == null)
+ if (_sNativeDisplayName == null)
{
// If its neutral use the language name
if (this.IsNeutralCulture)
{
- this.sNativeDisplayName = this.SNATIVELANGUAGE;
+ _sNativeDisplayName = this.SNATIVELANGUAGE;
+ // differentiate the legacy display names
+ switch (_sName)
+ {
+ case "zh-CHS":
+ _sNativeDisplayName += " \u65E7\u7248";
+ break;
+ case "zh-CHT":
+ _sNativeDisplayName += " \u820A\u7248";
+ break;
+ }
}
else
{
- this.sNativeDisplayName = DoGetLocaleInfo(LOCALE_SNATIVEDISPLAYNAME);
+ _sNativeDisplayName = GetLocaleInfo(LocaleStringData.NativeDisplayName);
// if it isn't found build one:
- if (String.IsNullOrEmpty(this.sNativeDisplayName))
+ if (String.IsNullOrEmpty(_sNativeDisplayName))
{
// These should primarily be "Deutsch (Deutschland)" type names
- this.sNativeDisplayName = this.SNATIVELANGUAGE + " (" + this.SNATIVECOUNTRY + ")";
+ _sNativeDisplayName = this.SNATIVELANGUAGE + " (" + this.SNATIVECOUNTRY + ")";
}
}
}
- return this.sNativeDisplayName;
+ return _sNativeDisplayName;
}
}
// The culture name to be used in CultureInfo.CreateSpecificCulture()
- internal String SSPECIFICCULTURE
+ internal string SSPECIFICCULTURE
{
get
{
- // This got populated when ComNlsInfo::nativeInitCultureData told us we had a culture
- Debug.Assert(this.sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by COMNlsInfo::nativeInitCultureData already");
- return this.sSpecificCulture;
+ // This got populated during the culture initialization
+ Debug.Assert(_sSpecificCulture != null, "[CultureData.SSPECIFICCULTURE] Expected this.sSpecificCulture to be populated by culture data initialization already");
+ return _sSpecificCulture;
}
}
@@ -1000,37 +1023,37 @@ namespace System.Globalization
{
get
{
- if (this.sISO639Language == null)
+ if (_sISO639Language == null)
{
- this.sISO639Language = DoGetLocaleInfo(LOCALE_SISO639LANGNAME);
+ _sISO639Language = GetLocaleInfo(LocaleStringData.Iso639LanguageTwoLetterName);
}
- return this.sISO639Language;
+ return _sISO639Language;
}
}
// iso 639 language name, ie: eng
- internal String SISO639LANGNAME2
+ internal string SISO639LANGNAME2
{
get
{
- if (this.sISO639Language2 == null)
+ if (_sISO639Language2 == null)
{
- this.sISO639Language2 = DoGetLocaleInfo(LOCALE_SISO639LANGNAME2);
+ _sISO639Language2 = GetLocaleInfo(LocaleStringData.Iso639LanguageThreeLetterName);
}
- return this.sISO639Language2;
+ return _sISO639Language2;
}
}
// abbreviated windows language name (ie: enu) (non-standard, avoid this)
- internal String SABBREVLANGNAME
+ internal string SABBREVLANGNAME
{
get
{
- if (this.sAbbrevLang == null)
+ if (_sAbbrevLang == null)
{
- this.sAbbrevLang = DoGetLocaleInfo(LOCALE_SABBREVLANGNAME);
+ _sAbbrevLang = GetThreeLetterWindowsLanguageName(_sRealName);
}
- return this.sAbbrevLang;
+ return _sAbbrevLang;
}
}
@@ -1040,20 +1063,25 @@ namespace System.Globalization
{
get
{
- if (this.sLocalizedLanguage == null)
+ if (_sLocalizedLanguage == null)
{
- if (CultureInfo.UserDefaultUICulture.Name.Equals(Thread.CurrentThread.CurrentUICulture.Name))
+ // 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))
{
- this.sLocalizedLanguage = DoGetLocaleInfo(LOCALE_SLOCALIZEDLANGUAGENAME);
+ _sLocalizedLanguage = SNATIVELANGUAGE;
}
- // Some OS's might not have this resource or LCTYPE
- if (String.IsNullOrEmpty(this.sLocalizedLanguage))
+ else
{
- this.sLocalizedLanguage = SNATIVELANGUAGE;
+ _sLocalizedLanguage = GetLocaleInfo(LocaleStringData.LocalizedLanguageName);
}
}
- return this.sLocalizedLanguage;
+ return _sLocalizedLanguage;
}
}
@@ -1062,11 +1090,11 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishLanguage == null)
+ if (_sEnglishLanguage == null)
{
- this.sEnglishLanguage = DoGetLocaleInfo(LOCALE_SENGLISHLANGUAGENAME);
+ _sEnglishLanguage = GetLocaleInfo(LocaleStringData.EnglishLanguageName);
}
- return this.sEnglishLanguage;
+ return _sEnglishLanguage;
}
}
@@ -1075,13 +1103,11 @@ namespace System.Globalization
{
get
{
- if (this.sNativeLanguage == null)
+ if (_sNativeLanguage == null)
{
- {
- this.sNativeLanguage = DoGetLocaleInfo(LOCALE_SNATIVELANGUAGENAME);
- }
+ _sNativeLanguage = GetLocaleInfo(LocaleStringData.NativeLanguageName);
}
- return this.sNativeLanguage;
+ return _sNativeLanguage;
}
}
@@ -1094,24 +1120,23 @@ namespace System.Globalization
{
get
{
- if (this.sRegionName == null)
+ if (_sRegionName == null)
{
- this.sRegionName = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME);
+ _sRegionName = GetLocaleInfo(LocaleStringData.Iso3166CountryName);
}
- return this.sRegionName;
+ return _sRegionName;
}
}
- // GeoId
internal int IGEOID
{
get
{
- if (this.iGeoId == undef)
+ if (_iGeoId == undef)
{
- this.iGeoId = DoGetLocaleInfoInt(LOCALE_IGEOID);
+ _iGeoId = GetGeoId(_sRealName);
}
- return this.iGeoId;
+ return _iGeoId;
}
}
@@ -1120,23 +1145,23 @@ namespace System.Globalization
{
get
{
- if (this.sLocalizedCountry == null)
+ if (_sLocalizedCountry == null)
{
- // If it hasn't been found (Windows 8 and up), fallback to the system
- if (String.IsNullOrEmpty(this.sLocalizedCountry))
+ try
{
- // We have to make the neutral distinction in case the OS returns a specific name
- if (CultureInfo.UserDefaultUICulture.Name.Equals(Thread.CurrentThread.CurrentUICulture.Name))
- {
- this.sLocalizedCountry = DoGetLocaleInfo(LOCALE_SLOCALIZEDCOUNTRYNAME);
- }
- if (String.IsNullOrEmpty(this.sLocalizedDisplayName))
- {
- this.sLocalizedCountry = SNATIVECOUNTRY;
- }
+ _sLocalizedCountry = GetRegionDisplayName(SISO3166CTRYNAME);
+ }
+ catch (Exception)
+ {
+ // do nothing. we'll fallback
+ }
+
+ if (_sLocalizedCountry == null)
+ {
+ _sLocalizedCountry = SNATIVECOUNTRY;
}
}
- return this.sLocalizedCountry;
+ return _sLocalizedCountry;
}
}
@@ -1145,11 +1170,11 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishCountry == null)
+ if (_sEnglishCountry == null)
{
- this.sEnglishCountry = DoGetLocaleInfo(LOCALE_SENGLISHCOUNTRYNAME);
+ _sEnglishCountry = GetLocaleInfo(LocaleStringData.EnglishCountryName);
}
- return this.sEnglishCountry;
+ return _sEnglishCountry;
}
}
@@ -1158,11 +1183,11 @@ namespace System.Globalization
{
get
{
- if (this.sNativeCountry == null)
+ if (_sNativeCountry == null)
{
- this.sNativeCountry = DoGetLocaleInfo(LOCALE_SNATIVECOUNTRYNAME);
+ _sNativeCountry = GetLocaleInfo(LocaleStringData.NativeCountryName);
}
- return this.sNativeCountry;
+ return _sNativeCountry;
}
}
@@ -1171,90 +1196,70 @@ namespace System.Globalization
{
get
{
- if (this.sISO3166CountryName == null)
+ if (_sISO3166CountryName == null)
{
- this.sISO3166CountryName = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME);
+ _sISO3166CountryName = GetLocaleInfo(LocaleStringData.Iso3166CountryName);
}
- return this.sISO3166CountryName;
+ return _sISO3166CountryName;
}
}
- // ISO 3166 Country Name
+ // 3 letter ISO 3166 country code
internal String SISO3166CTRYNAME2
{
get
{
- if (this.sISO3166CountryName2 == null)
+ if (_sISO3166CountryName2 == null)
{
- this.sISO3166CountryName2 = DoGetLocaleInfo(LOCALE_SISO3166CTRYNAME2);
+ _sISO3166CountryName2 = GetLocaleInfo(LocaleStringData.Iso3166CountryName2);
}
- return this.sISO3166CountryName2;
+ return _sISO3166CountryName2;
}
}
- // abbreviated Country Name (windows version, non-standard, avoid)
- internal String SABBREVCTRYNAME
- {
- get
- {
- if (this.sAbbrevCountry == null)
- {
- this.sAbbrevCountry = DoGetLocaleInfo(LOCALE_SABBREVCTRYNAME);
- }
- return this.sAbbrevCountry;
- }
- }
-
- // Console fallback name (ie: locale to use for console apps for unicode-only locales)
internal int IINPUTLANGUAGEHANDLE
{
get
{
- if (this.iInputLanguageHandle == undef)
+ if (_iInputLanguageHandle == undef)
{
if (IsSupplementalCustomCulture)
{
- this.iInputLanguageHandle = 0x0409;
+ _iInputLanguageHandle = 0x0409;
}
else
{
// Input Language is same as LCID for built-in cultures
- this.iInputLanguageHandle = this.ILANGUAGE;
+ _iInputLanguageHandle = this.ILANGUAGE;
}
}
- return this.iInputLanguageHandle;
+ return _iInputLanguageHandle;
}
}
// Console fallback name (ie: locale to use for console apps for unicode-only locales)
- internal String SCONSOLEFALLBACKNAME
+ internal string SCONSOLEFALLBACKNAME
{
get
{
- if (this.sConsoleFallbackName == null)
+ if (_sConsoleFallbackName == null)
{
- string consoleFallbackName = DoGetLocaleInfo(LOCALE_SCONSOLEFALLBACKNAME);
- if (consoleFallbackName == "es-ES_tradnl")
- {
- consoleFallbackName = "es-ES";
- }
- this.sConsoleFallbackName = consoleFallbackName;
+ _sConsoleFallbackName = GetConsoleFallbackName(_sRealName);
}
- return this.sConsoleFallbackName;
+ return _sConsoleFallbackName;
}
}
-
// (user can override) grouping of digits
internal int[] WAGROUPING
{
get
{
- if (this.waGrouping == null || UseUserOverride)
+ if (_waGrouping == null)
{
- this.waGrouping = ConvertWin32GroupString(DoGetLocaleInfo(LOCALE_SGROUPING));
+ _waGrouping = GetLocaleInfo(LocaleGroupingData.Digit);
}
- return this.waGrouping;
+ return _waGrouping;
}
}
@@ -1267,11 +1272,11 @@ namespace System.Globalization
{
get
{
- if (this.sNaN == null)
+ if (_sNaN == null)
{
- this.sNaN = DoGetLocaleInfo(LOCALE_SNAN);
+ _sNaN = GetLocaleInfo(LocaleStringData.NaNSymbol);
}
- return this.sNaN;
+ return _sNaN;
}
}
@@ -1280,11 +1285,11 @@ namespace System.Globalization
{
get
{
- if (this.sPositiveInfinity == null)
+ if (_sPositiveInfinity == null)
{
- this.sPositiveInfinity = DoGetLocaleInfo(LOCALE_SPOSINFINITY);
+ _sPositiveInfinity = GetLocaleInfo(LocaleStringData.PositiveInfinitySymbol);
}
- return this.sPositiveInfinity;
+ return _sPositiveInfinity;
}
}
@@ -1293,11 +1298,11 @@ namespace System.Globalization
{
get
{
- if (this.sNegativeInfinity == null)
+ if (_sNegativeInfinity == null)
{
- this.sNegativeInfinity = DoGetLocaleInfo(LOCALE_SNEGINFINITY);
+ _sNegativeInfinity = GetLocaleInfo(LocaleStringData.NegativeInfinitySymbol);
}
- return this.sNegativeInfinity;
+ return _sNegativeInfinity;
}
}
@@ -1311,12 +1316,12 @@ namespace System.Globalization
{
get
{
- if (this.iNegativePercent == undef)
+ if (_iNegativePercent == undef)
{
// Note that <= Windows Vista this is synthesized by native code
- this.iNegativePercent = DoGetLocaleInfoInt(LOCALE_INEGATIVEPERCENT);
+ _iNegativePercent = GetLocaleInfo(LocaleNumberData.NegativePercentFormat);
}
- return this.iNegativePercent;
+ return _iNegativePercent;
}
}
@@ -1325,12 +1330,12 @@ namespace System.Globalization
{
get
{
- if (this.iPositivePercent == undef)
+ if (_iPositivePercent == undef)
{
// Note that <= Windows Vista this is synthesized by native code
- this.iPositivePercent = DoGetLocaleInfoInt(LOCALE_IPOSITIVEPERCENT);
+ _iPositivePercent = GetLocaleInfo(LocaleNumberData.PositivePercentFormat);
}
- return this.iPositivePercent;
+ return _iPositivePercent;
}
}
@@ -1339,26 +1344,24 @@ namespace System.Globalization
{
get
{
- if (this.sPercent == null)
+ if (_sPercent == null)
{
- // Note that <= Windows Vista this is synthesized by native code
- this.sPercent = DoGetLocaleInfo(LOCALE_SPERCENT);
+ _sPercent = GetLocaleInfo(LocaleStringData.PercentSymbol);
}
- return this.sPercent;
+ return _sPercent;
}
}
- // PerMille (‰) symbol
+ // PerMille symbol
internal String SPERMILLE
{
get
{
- if (this.sPerMille == null)
+ if (_sPerMille == null)
{
- // Note that <= Windows Vista this is synthesized by native code
- this.sPerMille = DoGetLocaleInfo(LOCALE_SPERMILLE);
+ _sPerMille = GetLocaleInfo(LocaleStringData.PerMilleSymbol);
}
- return this.sPerMille;
+ return _sPerMille;
}
}
@@ -1371,11 +1374,11 @@ namespace System.Globalization
{
get
{
- if (this.sCurrency == null || UseUserOverride)
+ if (_sCurrency == null)
{
- this.sCurrency = DoGetLocaleInfo(LOCALE_SCURRENCY);
+ _sCurrency = GetLocaleInfo(LocaleStringData.MonetarySymbol);
}
- return this.sCurrency;
+ return _sCurrency;
}
}
@@ -1384,11 +1387,11 @@ namespace System.Globalization
{
get
{
- if (this.sIntlMonetarySymbol == null)
+ if (_sIntlMonetarySymbol == null)
{
- this.sIntlMonetarySymbol = DoGetLocaleInfo(LOCALE_SINTLSYMBOL);
+ _sIntlMonetarySymbol = GetLocaleInfo(LocaleStringData.Iso4217MonetarySymbol);
}
- return this.sIntlMonetarySymbol;
+ return _sIntlMonetarySymbol;
}
}
@@ -1397,11 +1400,11 @@ namespace System.Globalization
{
get
{
- if (this.sEnglishCurrency == null)
+ if (_sEnglishCurrency == null)
{
- this.sEnglishCurrency = DoGetLocaleInfo(LOCALE_SENGCURRNAME);
+ _sEnglishCurrency = GetLocaleInfo(LocaleStringData.CurrencyEnglishName);
}
- return this.sEnglishCurrency;
+ return _sEnglishCurrency;
}
}
@@ -1410,11 +1413,11 @@ namespace System.Globalization
{
get
{
- if (this.sNativeCurrency == null)
+ if (_sNativeCurrency == null)
{
- this.sNativeCurrency = DoGetLocaleInfo(LOCALE_SNATIVECURRNAME);
+ _sNativeCurrency = GetLocaleInfo(LocaleStringData.CurrencyNativeName);
}
- return this.sNativeCurrency;
+ return _sNativeCurrency;
}
}
@@ -1427,31 +1430,24 @@ namespace System.Globalization
{
get
{
- if (this.waMonetaryGrouping == null || UseUserOverride)
+ if (_waMonetaryGrouping == null)
{
- this.waMonetaryGrouping = ConvertWin32GroupString(DoGetLocaleInfo(LOCALE_SMONGROUPING));
+ _waMonetaryGrouping = GetLocaleInfo(LocaleGroupingData.Monetary);
}
- return this.waMonetaryGrouping;
+ return _waMonetaryGrouping;
}
}
- // internal String sMonetaryDecimal ; // (user can override) monetary decimal separator
- // internal String sMonetaryThousand ; // (user can override) monetary thousands separator
-
- /////////
- // Misc //
- /////////
-
// (user can override) system of measurement 0=metric, 1=US (RegionInfo)
internal int IMEASURE
{
get
{
- if (this.iMeasure == undef || UseUserOverride)
+ if (_iMeasure == undef)
{
- this.iMeasure = DoGetLocaleInfoInt(LOCALE_IMEASURE);
+ _iMeasure = GetLocaleInfo(LocaleNumberData.MeasurementSystem);
}
- return this.iMeasure;
+ return _iMeasure;
}
}
@@ -1460,14 +1456,15 @@ namespace System.Globalization
{
get
{
- if (this.sListSeparator == null || UseUserOverride)
+ if (_sListSeparator == null)
{
- this.sListSeparator = DoGetLocaleInfo(LOCALE_SLIST);
+ _sListSeparator = GetLocaleInfo(LocaleStringData.ListSeparator);
}
- return this.sListSeparator;
+ return _sListSeparator;
}
}
+
////////////////////////////
// Calendar/Time (Gregorian) //
////////////////////////////
@@ -1477,11 +1474,11 @@ namespace System.Globalization
{
get
{
- if (this.sAM1159 == null || UseUserOverride)
+ if (_sAM1159 == null)
{
- this.sAM1159 = DoGetLocaleInfo(LOCALE_S1159);
+ _sAM1159 = GetLocaleInfo(LocaleStringData.AMDesignator);
}
- return this.sAM1159;
+ return _sAM1159;
}
}
@@ -1490,11 +1487,11 @@ namespace System.Globalization
{
get
{
- if (this.sPM2359 == null || UseUserOverride)
+ if (_sPM2359 == null)
{
- this.sPM2359 = DoGetLocaleInfo(LOCALE_S2359);
+ _sPM2359 = GetLocaleInfo(LocaleStringData.PMDesignator);
}
- return this.sPM2359;
+ return _sPM2359;
}
}
@@ -1503,32 +1500,38 @@ namespace System.Globalization
{
get
{
- if (this.saLongTimes == null || UseUserOverride)
+ if (_saLongTimes == null)
{
- String[] longTimes = DoEnumTimeFormats();
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ String[] longTimes = GetTimeFormats();
if (longTimes == null || longTimes.Length == 0)
{
- this.saLongTimes = Invariant.saLongTimes;
+ _saLongTimes = Invariant._saLongTimes;
}
else
{
- this.saLongTimes = longTimes;
+ _saLongTimes = longTimes;
}
}
- return this.saLongTimes;
+ return _saLongTimes;
}
}
// short time format
// Short times (derived from long times format)
+ // TODO: NLS Arrowhead - On Windows 7 we should have short times so this isn't necessary
internal String[] ShortTimes
{
get
{
- if (this.saShortTimes == null || UseUserOverride)
+ if (_saShortTimes == null)
{
+ Debug.Assert(!GlobalizationMode.Invariant);
+
// Try to get the short times from the OS/culture.dll
- String[] shortTimes = DoEnumShortTimeFormats();
+ String[] shortTimes = null;
+ shortTimes = GetShortTimeFormats();
if (shortTimes == null || shortTimes.Length == 0)
{
@@ -1539,13 +1542,24 @@ namespace System.Globalization
shortTimes = DeriveShortTimesFromLong();
}
+ /* The above logic doesn't make sense on Mac, since the OS can provide us a "short time pattern".
+ * currently this is the 4th element in the array returned by LongTimes. We'll add this to our array
+ * if it doesn't exist.
+ */
+ shortTimes = AdjustShortTimesForMac(shortTimes);
+
// Found short times, use them
- this.saShortTimes = shortTimes;
+ _saShortTimes = shortTimes;
}
- return this.saShortTimes;
+ return _saShortTimes;
}
}
+ private string[] AdjustShortTimesForMac(string[] shortTimes)
+ {
+ return shortTimes;
+ }
+
private string[] DeriveShortTimesFromLong()
{
// Our logic is to look for h,H,m,s,t. If we find an s, then we check the string
@@ -1611,13 +1625,19 @@ namespace System.Globalization
bool containsSpace;
int endIndex = GetIndexOfNextTokenAfterSeconds(time, j, out containsSpace);
- StringBuilder sb = new StringBuilder(time.Substring(0, j));
+
+ string sep;
+
if (containsSpace)
{
- sb.Append(' ');
+ sep = " ";
}
- sb.Append(time.Substring(endIndex));
- time = sb.ToString();
+ else
+ {
+ sep = "";
+ }
+
+ time = time.Substring(0, j) + sep + time.Substring(endIndex);
break;
case 'm':
case 'H':
@@ -1670,12 +1690,11 @@ namespace System.Globalization
{
get
{
- if (this.iFirstDayOfWeek == undef || UseUserOverride)
+ if (_iFirstDayOfWeek == undef)
{
- // Have to convert it from windows to .Net formats
- this.iFirstDayOfWeek = ConvertFirstDayOfWeekMonToSun(DoGetLocaleInfoInt(LOCALE_IFIRSTDAYOFWEEK));
+ _iFirstDayOfWeek = GetFirstDayOfWeek();
}
- return this.iFirstDayOfWeek;
+ return _iFirstDayOfWeek;
}
}
@@ -1684,71 +1703,71 @@ namespace System.Globalization
{
get
{
- if (this.iFirstWeekOfYear == undef || UseUserOverride)
+ if (_iFirstWeekOfYear == undef)
{
- this.iFirstWeekOfYear = DoGetLocaleInfoInt(LOCALE_IFIRSTWEEKOFYEAR);
+ _iFirstWeekOfYear = GetLocaleInfo(LocaleNumberData.FirstWeekOfYear);
}
- return this.iFirstWeekOfYear;
+ return _iFirstWeekOfYear;
}
}
// (user can override default only) short date format
- internal String[] ShortDates(int calendarId)
+ internal String[] ShortDates(CalendarId calendarId)
{
return GetCalendar(calendarId).saShortDates;
}
// (user can override default only) long date format
- internal String[] LongDates(int calendarId)
+ internal String[] LongDates(CalendarId calendarId)
{
return GetCalendar(calendarId).saLongDates;
}
// (user can override) date year/month format.
- internal String[] YearMonths(int calendarId)
+ internal String[] YearMonths(CalendarId calendarId)
{
return GetCalendar(calendarId).saYearMonths;
}
// day names
- internal string[] DayNames(int calendarId)
+ internal string[] DayNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saDayNames;
}
// abbreviated day names
- internal string[] AbbreviatedDayNames(int calendarId)
+ internal string[] AbbreviatedDayNames(CalendarId calendarId)
{
// Get abbreviated day names for this calendar from the OS if necessary
return GetCalendar(calendarId).saAbbrevDayNames;
}
// The super short day names
- internal string[] SuperShortDayNames(int calendarId)
+ internal string[] SuperShortDayNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saSuperShortDayNames;
}
// month names
- internal string[] MonthNames(int calendarId)
+ internal string[] MonthNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saMonthNames;
}
// Genitive month names
- internal string[] GenitiveMonthNames(int calendarId)
+ internal string[] GenitiveMonthNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saMonthGenitiveNames;
}
// month names
- internal string[] AbbreviatedMonthNames(int calendarId)
+ internal string[] AbbreviatedMonthNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saAbbrevMonthNames;
}
// Genitive month names
- internal string[] AbbreviatedGenitiveMonthNames(int calendarId)
+ internal string[] AbbreviatedGenitiveMonthNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saAbbrevMonthGenitiveNames;
}
@@ -1756,13 +1775,13 @@ namespace System.Globalization
// Leap year month names
// Note: This only applies to Hebrew, and it basically adds a "1" to the 6th month name
// the non-leap names skip the 7th name in the normal month name array
- internal string[] LeapYearMonthNames(int calendarId)
+ internal string[] LeapYearMonthNames(CalendarId calendarId)
{
return GetCalendar(calendarId).saLeapYearMonthNames;
}
// month/day format (single string, no override)
- internal String MonthDay(int calendarId)
+ internal String MonthDay(CalendarId calendarId)
{
return GetCalendar(calendarId).sMonthDay;
}
@@ -1774,29 +1793,30 @@ namespace System.Globalization
/////////////
// all available calendar type(s), The first one is the default calendar.
- internal int[] CalendarIds
+ internal CalendarId[] CalendarIds
{
get
{
- if (this.waCalendars == null)
+ if (_waCalendars == null)
{
// We pass in an array of ints, and native side fills it up with count calendars.
// We then have to copy that list to a new array of the right size.
// Default calendar should be first
- int[] calendarInts = new int[23];
- Debug.Assert(this.sWindowsName != null, "[CultureData.CalendarIds] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- int count = CalendarData.nativeGetCalendars(this.sWindowsName, this.bUseOverrides, calendarInts);
+ CalendarId[] calendars = new CalendarId[23];
+ Debug.Assert(_sWindowsName != null, "[CultureData.CalendarIds] Expected _sWindowsName to be populated by already");
+ int count = CalendarData.GetCalendars(_sWindowsName, _bUseOverrides, calendars);
// See if we had a calendar to add.
if (count == 0)
{
// Failed for some reason, just grab Gregorian from Invariant
- this.waCalendars = Invariant.waCalendars;
+ _waCalendars = Invariant._waCalendars;
}
else
{
// The OS may not return calendar 4 for zh-TW, but we've always allowed it.
- if (this.sWindowsName == "zh-TW")
+ // TODO: Is this hack necessary long-term?
+ if (_sWindowsName == "zh-TW")
{
bool found = false;
@@ -1804,7 +1824,7 @@ namespace System.Globalization
for (int i = 0; i < count; i++)
{
// Stop if we found calendar four
- if (calendarInts[i] == Calendar.CAL_TAIWAN)
+ if (calendars[i] == CalendarId.TAIWAN)
{
found = true;
break;
@@ -1817,21 +1837,20 @@ namespace System.Globalization
// Insert it as the 2nd calendar
count++;
// Copy them from the 2nd position to the end, -1 for skipping 1st, -1 for one being added.
- Array.Copy(calendarInts, 1, calendarInts, 2, 23 - 1 - 1);
- calendarInts[1] = Calendar.CAL_TAIWAN;
+ Array.Copy(calendars, 1, calendars, 2, 23 - 1 - 1);
+ calendars[1] = CalendarId.TAIWAN;
}
}
// It worked, remember the list
- int[] temp = new int[count];
- Array.Copy(calendarInts, temp, count);
+ CalendarId[] temp = new CalendarId[count];
+ Array.Copy(calendars, temp, count);
// Want 1st calendar to be default
// Prior to Vista the enumeration didn't have default calendar first
- // Only a coreclr concern, culture.dll does the right thing.
if (temp.Length > 1)
{
- int i = DoGetLocaleInfoInt(LOCALE_ICALENDARTYPE);
+ CalendarId i = (CalendarId)GetLocaleInfo(LocaleNumberData.CalendarType);
if (temp[1] == i)
{
temp[1] = temp[0];
@@ -1839,45 +1858,45 @@ namespace System.Globalization
}
}
- this.waCalendars = temp;
+ _waCalendars = temp;
}
}
- return this.waCalendars;
+ return _waCalendars;
}
}
// Native calendar names. index of optional calendar - 1, empty if no optional calendar at that number
- internal String CalendarName(int calendarId)
+ internal string CalendarName(CalendarId calendarId)
{
// Get the calendar
return GetCalendar(calendarId).sNativeName;
}
- internal CalendarData GetCalendar(int calendarId)
+ internal CalendarData GetCalendar(CalendarId calendarId)
{
- Debug.Assert(calendarId > 0 && calendarId <= CalendarData.MAX_CALENDARS,
+ Debug.Assert(calendarId > 0 && calendarId <= CalendarId.LAST_CALENDAR,
"[CultureData.GetCalendar] Expect calendarId to be in a valid range");
// arrays are 0 based, calendarIds are 1 based
- int calendarIndex = calendarId - 1;
+ int calendarIndex = (int)calendarId - 1;
// Have to have calendars
- if (calendars == null)
+ if (_calendars == null)
{
- calendars = new CalendarData[CalendarData.MAX_CALENDARS];
+ _calendars = new CalendarData[CalendarData.MAX_CALENDARS];
}
// we need the following local variable to avoid returning null
// when another thread creates a new array of CalendarData (above)
// right after we insert the newly created CalendarData (below)
- CalendarData calendarData = calendars[calendarIndex];
+ CalendarData calendarData = _calendars[calendarIndex];
// Make sure that calendar has data
- if (calendarData == null || UseUserOverride)
+ if (calendarData == null)
{
- Debug.Assert(this.sWindowsName != null, "[CultureData.GetCalendar] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- calendarData = new CalendarData(this.sWindowsName, calendarId, this.UseUserOverride);
- calendars[calendarIndex] = calendarData;
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetCalendar] Expected _sWindowsName to be populated by already");
+ calendarData = new CalendarData(_sWindowsName, calendarId, this.UseUserOverride);
+ _calendars[calendarIndex] = calendarData;
}
return calendarData;
@@ -1913,13 +1932,13 @@ namespace System.Globalization
{
get
{
- if (this.iReadingLayout == undef)
+ if (_iReadingLayout == undef)
{
- Debug.Assert(this.sRealName != null, "[CultureData.IsRightToLeft] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
- this.iReadingLayout = DoGetLocaleInfoInt(LOCALE_IREADINGLAYOUT);
+ Debug.Assert(_sRealName != null, "[CultureData.IsRightToLeft] Expected _sRealName to be populated by already");
+ _iReadingLayout = GetLocaleInfo(LocaleNumberData.ReadingLayout);
}
- return (this.iReadingLayout);
+ return (_iReadingLayout);
}
}
@@ -1934,23 +1953,10 @@ namespace System.Globalization
{
get
{
- if (this.sTextInfo == null)
- {
- // LOCALE_SSORTLOCALE is broken in Win7 for Alt sorts.
- // It is also not supported downlevel without culture.dll.
- if (IsNeutralCulture || IsSupplementalCustomCulture)
- {
- string sortLocale = DoGetLocaleInfo(LOCALE_SSORTLOCALE);
- this.sTextInfo = GetCultureData(sortLocale, bUseOverrides).SNAME;
- }
-
- if (this.sTextInfo == null)
- {
- this.sTextInfo = this.SNAME; // removes alternate sort
- }
- }
-
- return this.sTextInfo;
+ // Note: Custom cultures might point at another culture's textinfo, however windows knows how
+ // to redirect it to the desired textinfo culture, so this is OK.
+ Debug.Assert(_sRealName != null, "[CultureData.STEXTINFO] Expected _sRealName to be populated by already");
+ return (_sRealName);
}
}
@@ -1959,24 +1965,8 @@ namespace System.Globalization
{
get
{
- if (this.sCompareInfo == null)
- {
- // LOCALE_SSORTLOCALE is broken in Win7 for Alt sorts.
- // It is also not supported downlevel without culture.dll.
- // We really only need it for the custom locale case though
- // since for all other cases, it is the same as sWindowsName
- if (IsSupplementalCustomCulture)
- {
- this.sCompareInfo = DoGetLocaleInfo(LOCALE_SSORTLOCALE);
- }
-
- if (this.sCompareInfo == null)
- {
- this.sCompareInfo = this.sWindowsName;
- }
- }
-
- return this.sCompareInfo;
+ Debug.Assert(_sRealName != null, "[CultureData.SCOMPAREINFO] Expected _sRealName to be populated by already");
+ return (_sRealName);
}
}
@@ -1988,16 +1978,15 @@ namespace System.Globalization
}
}
-
internal int IDEFAULTANSICODEPAGE // default ansi code page ID (ACP)
{
get
{
- if (this.iDefaultAnsiCodePage == undef)
+ if (_iDefaultAnsiCodePage == undef)
{
- this.iDefaultAnsiCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTANSICODEPAGE);
+ _iDefaultAnsiCodePage = GetAnsiCodePage(_sRealName);
}
- return this.iDefaultAnsiCodePage;
+ return _iDefaultAnsiCodePage;
}
}
@@ -2005,11 +1994,11 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultOemCodePage == undef)
+ if (_iDefaultOemCodePage == undef)
{
- this.iDefaultOemCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTCODEPAGE);
+ _iDefaultOemCodePage = GetOemCodePage(_sRealName);
}
- return this.iDefaultOemCodePage;
+ return _iDefaultOemCodePage;
}
}
@@ -2017,11 +2006,11 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultMacCodePage == undef)
+ if (_iDefaultMacCodePage == undef)
{
- this.iDefaultMacCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTMACCODEPAGE);
+ _iDefaultMacCodePage = GetMacCodePage(_sRealName);
}
- return this.iDefaultMacCodePage;
+ return _iDefaultMacCodePage;
}
}
@@ -2029,54 +2018,33 @@ namespace System.Globalization
{
get
{
- if (this.iDefaultEbcdicCodePage == undef)
+ if (_iDefaultEbcdicCodePage == undef)
{
- this.iDefaultEbcdicCodePage = DoGetLocaleInfoInt(LOCALE_IDEFAULTEBCDICCODEPAGE);
+ _iDefaultEbcdicCodePage = GetEbcdicCodePage(_sRealName);
}
- return this.iDefaultEbcdicCodePage;
+ return _iDefaultEbcdicCodePage;
}
}
- // Obtain locale name from LCID
- // NOTE: This will get neutral names, unlike the OS API
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern int LocaleNameToLCID(String localeName);
-
- // These are desktop only, not coreclr
- // locale ID (0409), including sort information
internal int ILANGUAGE
{
get
{
- if (this.iLanguage == 0)
+ if (_iLanguage == 0)
{
- Debug.Assert(this.sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated by COMNlsInfo::nativeInitCultureData already");
- this.iLanguage = LocaleNameToLCID(this.sRealName);
+ Debug.Assert(_sRealName != null, "[CultureData.ILANGUAGE] Expected this.sRealName to be populated already");
+ _iLanguage = LocaleNameToLCID(_sRealName);
}
- return this.iLanguage;
+ return _iLanguage;
}
}
- internal bool IsWin32Installed
- {
- get { return this.bWin32Installed; }
- }
-
- internal bool IsFramework
- {
- get { return this.bFramework; }
- }
-
- ////////////////////
- // Derived properties //
- ////////////////////
-
internal bool IsNeutralCulture
{
get
{
- // NlsInfo::nativeInitCultureData told us if we're neutral or not
- return this.bNeutral;
+ // InitCultureData told us if we're neutral or not
+ return _bNeutral;
}
}
@@ -2093,7 +2061,13 @@ namespace System.Globalization
{
get
{
- int defaultCalId = DoGetLocaleInfoInt(LOCALE_ICALENDARTYPE);
+ if (GlobalizationMode.Invariant)
+ {
+ return CultureInfo.GetCalendarInstance(CalendarIds[0]);
+ }
+
+ CalendarId defaultCalId = (CalendarId)GetLocaleInfo(LocaleNumberData.CalendarType);
+
if (defaultCalId == 0)
{
defaultCalId = this.CalendarIds[0];
@@ -2104,29 +2078,29 @@ namespace System.Globalization
}
// All of our era names
- internal String[] EraNames(int calendarId)
+ internal String[] EraNames(CalendarId calendarId)
{
Debug.Assert(calendarId > 0, "[CultureData.saEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saEraNames;
}
- internal String[] AbbrevEraNames(int calendarId)
+ internal String[] AbbrevEraNames(CalendarId calendarId)
{
Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEraNames;
}
- internal String[] AbbreviatedEnglishEraNames(int calendarId)
+ internal String[] AbbreviatedEnglishEraNames(CalendarId calendarId)
{
Debug.Assert(calendarId > 0, "[CultureData.saAbbrevEraNames] Expected Calendar.ID > 0");
return this.GetCalendar(calendarId).saAbbrevEnglishEraNames;
}
- // String array DEFAULTS
- // Note: GetDTFIOverrideValues does the user overrides for these, so we don't have to.
+ //// String array DEFAULTS
+ //// Note: GetDTFIOverrideValues does the user overrides for these, so we don't have to.
// Time separator (derived from time format)
@@ -2134,23 +2108,23 @@ namespace System.Globalization
{
get
{
- if (sTimeSeparator == null || UseUserOverride)
+ if (_sTimeSeparator == null)
{
- string longTimeFormat = ReescapeWin32String(DoGetLocaleInfo(LOCALE_STIMEFORMAT));
+ string longTimeFormat = GetTimeFormatString();
if (String.IsNullOrEmpty(longTimeFormat))
{
longTimeFormat = LongTimes[0];
}
// Compute STIME from time format
- sTimeSeparator = GetTimeSeparator(longTimeFormat);
+ _sTimeSeparator = GetTimeSeparator(longTimeFormat);
}
- return sTimeSeparator;
+ return _sTimeSeparator;
}
}
// Date separator (derived from short date format)
- internal String DateSeparator(int calendarId)
+ internal String DateSeparator(CalendarId calendarId)
{
return GetDateSeparator(ShortDates(calendarId)[0]);
}
@@ -2178,11 +2152,11 @@ namespace System.Globalization
// always build a stringbuilder because we need to remove the ' or \.
//
////////////////////////////////////////////////////////////////////////////
- static private String UnescapeNlsString(String str, int start, int end)
+ private static String UnescapeNlsString(String str, int start, int end)
{
- Contract.Requires(str != null);
- Contract.Requires(start >= 0);
- Contract.Requires(end >= 0);
+ Debug.Assert(str != null);
+ Debug.Assert(start >= 0);
+ Debug.Assert(end >= 0);
StringBuilder result = null;
for (int i = start; i < str.Length && i <= end; i++)
@@ -2221,102 +2195,7 @@ namespace System.Globalization
return (result.ToString());
}
- ////////////////////////////////////////////////////////////////////////////
- //
- // Reescape a Win32 style quote string as a NLS+ style quoted string
- //
- // This is also the escaping style used by custom culture data files
- //
- // NLS+ uses \ to escape the next character, whether in a quoted string or
- // not, so we always have to change \ to \\.
- //
- // NLS+ uses \' to escape a quote inside a quoted string so we have to change
- // '' to \' (if inside a quoted string)
- //
- // We don't build the stringbuilder unless we find something to change
- ////////////////////////////////////////////////////////////////////////////
- static internal String ReescapeWin32String(String str)
- {
- // If we don't have data, then don't try anything
- if (str == null)
- return null;
-
- StringBuilder result = null;
-
- bool inQuote = false;
- for (int i = 0; i < str.Length; i++)
- {
- // Look for quote
- if (str[i] == '\'')
- {
- // Already in quote?
- if (inQuote)
- {
- // See another single quote. Is this '' of 'fred''s' or '''', or is it an ending quote?
- if (i + 1 < str.Length && str[i + 1] == '\'')
- {
- // Found another ', so we have ''. Need to add \' instead.
- // 1st make sure we have our stringbuilder
- if (result == null)
- result = new StringBuilder(str, 0, i, str.Length * 2);
-
- // Append a \' and keep going (so we don't turn off quote mode)
- result.Append("\\'");
- i++;
- continue;
- }
-
- // Turning off quote mode, fall through to add it
- inQuote = false;
- }
- else
- {
- // Found beginning quote, fall through to add it
- inQuote = true;
- }
- }
- // Is there a single \ character?
- else if (str[i] == '\\')
- {
- // Found a \, need to change it to \\
- // 1st make sure we have our stringbuilder
- if (result == null)
- result = new StringBuilder(str, 0, i, str.Length * 2);
-
- // Append our \\ to the string & continue
- result.Append("\\\\");
- continue;
- }
-
- // If we have a builder we need to add our character
- if (result != null)
- result.Append(str[i]);
- }
-
- // Unchanged string? , just return input string
- if (result == null)
- return str;
-
- // String changed, need to use the builder
- return result.ToString();
- }
-
- static internal String[] ReescapeWin32Strings(String[] array)
- {
- if (array != null)
- {
- for (int i = 0; i < array.Length; i++)
- {
- array[i] = ReescapeWin32String(array[i]);
- }
- }
-
- return array;
- }
-
- // NOTE: this method is used through reflection by System.Globalization.CultureXmlParser.ReadDateElement()
- // and breaking changes here will not show up at build time, only at run time.
- static private String GetTimeSeparator(String format)
+ private static String GetTimeSeparator(String format)
{
// Time format separator (ie: : in 12:39:00)
//
@@ -2329,9 +2208,7 @@ namespace System.Globalization
return GetSeparator(format, "Hhms");
}
- // NOTE: this method is used through reflection by System.Globalization.CultureXmlParser.ReadDateElement()
- // and breaking changes here will not show up at build time, only at run time.
- static private String GetDateSeparator(String format)
+ private static String GetDateSeparator(String format)
{
// Date format separator (ie: / in 9/1/03)
//
@@ -2413,128 +2290,61 @@ namespace System.Globalization
return -1;
}
- string DoGetLocaleInfo(uint lctype)
- {
- Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfo] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- return DoGetLocaleInfo(this.sWindowsName, lctype);
- }
-
- // For LOCALE_SPARENT we need the option of using the "real" name (forcing neutral names) instead of the
- // "windows" name, which can be specific for downlevel (< windows 7) os's.
- string DoGetLocaleInfo(string localeName, uint lctype)
- {
- // Fix lctype if we don't want overrides
- if (!UseUserOverride)
- {
- lctype |= LOCALE_NOUSEROVERRIDE;
- }
-
- // Ask OS for data
- Debug.Assert(localeName != null, "[CultureData.DoGetLocaleInfo] Expected localeName to be not be null");
- string result = CultureInfo.nativeGetLocaleInfoEx(localeName, lctype);
- if (result == null)
- {
- // Failed, just use empty string
- result = String.Empty;
- }
-
- return result;
- }
-
- int DoGetLocaleInfoInt(uint lctype)
- {
- // Fix lctype if we don't want overrides
- if (!UseUserOverride)
- {
- lctype |= LOCALE_NOUSEROVERRIDE;
- }
-
- // Ask OS for data, note that we presume it returns success, so we have to know that
- // sWindowsName is valid before calling.
- Debug.Assert(this.sWindowsName != null, "[CultureData.DoGetLocaleInfoInt] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- int result = CultureInfo.nativeGetLocaleInfoExInt(this.sWindowsName, lctype);
-
- return result;
- }
-
- String[] DoEnumTimeFormats()
- {
- // Note that this gets overrides for us all the time
- Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, 0, UseUserOverride));
-
- return result;
- }
-
- String[] DoEnumShortTimeFormats()
- {
- // Note that this gets overrides for us all the time
- Debug.Assert(this.sWindowsName != null, "[CultureData.DoEnumShortTimeFormats] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- String[] result = ReescapeWin32Strings(nativeEnumTimeFormats(this.sWindowsName, TIME_NOSECONDS, UseUserOverride));
-
- return result;
- }
-
- /////////////////
- // Static Helpers //
- ////////////////
internal static bool IsCustomCultureId(int cultureId)
{
- if (cultureId == CultureInfo.LOCALE_CUSTOM_DEFAULT || cultureId == CultureInfo.LOCALE_CUSTOM_UNSPECIFIED)
- return true;
-
- return false;
+ return (cultureId == CultureInfo.LOCALE_CUSTOM_DEFAULT || cultureId == CultureInfo.LOCALE_CUSTOM_UNSPECIFIED);
}
- ////////////////////////////////////////////////////////////////////////////
- //
- // Parameters:
- // calendarValueOnly Retrieve the values which are affected by the calendar change of DTFI.
- // This will cause values like longTimePattern not be retrieved since it is
- // not affected by the Calendar property in DTFI.
- //
- ////////////////////////////////////////////////////////////////////////////
internal void GetNFIValues(NumberFormatInfo nfi)
{
- if (this.IsInvariantCulture)
+ if (GlobalizationMode.Invariant || this.IsInvariantCulture)
{
- nfi.positiveSign = this.sPositiveSign;
- nfi.negativeSign = this.sNegativeSign;
-
- nfi.nativeDigits = this.saNativeDigits;
- nfi.digitSubstitution = this.iDigitSubstitution;
+ // FUTURE: NumberFormatInfo already has default values for many of these fields. Can we not do this?
+ nfi.positiveSign = _sPositiveSign;
+ nfi.negativeSign = _sNegativeSign;
- nfi.numberGroupSeparator = this.sThousandSeparator;
- nfi.numberDecimalSeparator = this.sDecimalSeparator;
- nfi.numberDecimalDigits = this.iDigits;
- nfi.numberNegativePattern = this.iNegativeNumber;
+ nfi.numberGroupSeparator = _sThousandSeparator;
+ nfi.numberDecimalSeparator = _sDecimalSeparator;
+ nfi.numberDecimalDigits = _iDigits;
+ nfi.numberNegativePattern = _iNegativeNumber;
- nfi.currencySymbol = this.sCurrency;
- nfi.currencyGroupSeparator = this.sMonetaryThousand;
- nfi.currencyDecimalSeparator = this.sMonetaryDecimal;
- nfi.currencyDecimalDigits = this.iCurrencyDigits;
- nfi.currencyNegativePattern = this.iNegativeCurrency;
- nfi.currencyPositivePattern = this.iCurrency;
+ nfi.currencySymbol = _sCurrency;
+ nfi.currencyGroupSeparator = _sMonetaryThousand;
+ nfi.currencyDecimalSeparator = _sMonetaryDecimal;
+ nfi.currencyDecimalDigits = _iCurrencyDigits;
+ nfi.currencyNegativePattern = _iNegativeCurrency;
+ nfi.currencyPositivePattern = _iCurrency;
}
else
{
- //
- // We don't have information for the following four. All cultures use
- // the same value of the number formatting values.
- //
- // PercentDecimalDigits
- // PercentDecimalSeparator
- // PercentGroupSize
- // PercentGroupSeparator
- //
+ Debug.Assert(_sWindowsName != null, "[CultureData.GetNFIValues] Expected _sWindowsName to be populated by already");
+ // String values
+ nfi.positiveSign = GetLocaleInfo(LocaleStringData.PositiveSign);
+ nfi.negativeSign = GetLocaleInfo(LocaleStringData.NegativeSign);
- //
- // Ask native side for our data.
- //
- Debug.Assert(this.sWindowsName != null, "[CultureData.GetNFIValues] Expected this.sWindowsName to be populated by COMNlsInfo::nativeInitCultureData already");
- CultureData.nativeGetNumberFormatInfoValues(this.sWindowsName, nfi, UseUserOverride);
- }
+ nfi.numberDecimalSeparator = GetLocaleInfo(LocaleStringData.DecimalSeparator);
+ nfi.numberGroupSeparator = GetLocaleInfo(LocaleStringData.ThousandSeparator);
+ nfi.currencyGroupSeparator = GetLocaleInfo(LocaleStringData.MonetaryThousandSeparator);
+ nfi.currencyDecimalSeparator = GetLocaleInfo(LocaleStringData.MonetaryDecimalSeparator);
+ nfi.currencySymbol = GetLocaleInfo(LocaleStringData.MonetarySymbol);
+
+ // Numeric values
+ nfi.numberDecimalDigits = GetLocaleInfo(LocaleNumberData.FractionalDigitsCount);
+ nfi.currencyDecimalDigits = GetLocaleInfo(LocaleNumberData.MonetaryFractionalDigitsCount);
+ nfi.currencyPositivePattern = GetLocaleInfo(LocaleNumberData.PositiveMonetaryNumberFormat);
+ nfi.currencyNegativePattern = GetLocaleInfo(LocaleNumberData.NegativeMonetaryNumberFormat);
+ nfi.numberNegativePattern = GetLocaleInfo(LocaleNumberData.NegativeNumberFormat);
+ // LOCALE_SNATIVEDIGITS (array of 10 single character strings).
+ string digits = GetLocaleInfo(LocaleStringData.Digits);
+ nfi.nativeDigits = new string[10];
+ for (int i = 0; i < nfi.nativeDigits.Length; i++)
+ {
+ nfi.nativeDigits[i] = new string(digits[i], 1);
+ }
+
+ nfi.digitSubstitution = GetDigitSubstitution(_sRealName);
+ }
//
// Gather additional data
@@ -2569,289 +2379,188 @@ namespace System.Globalization
//Special case for Italian. The currency decimal separator in the control panel is the empty string. When the user
//specifies C4 as the currency format, this results in the number apparently getting multiplied by 10000 because the
- //decimal point doesn't show up. We'll just workaround this here because our default currency format will never use nfi.
+ //decimal point doesn't show up. We'll just hack this here because our default currency format will never use nfi.
if (nfi.currencyDecimalSeparator == null || nfi.currencyDecimalSeparator.Length == 0)
{
nfi.currencyDecimalSeparator = nfi.numberDecimalSeparator;
}
}
- static private int ConvertFirstDayOfWeekMonToSun(int iTemp)
- {
- // Convert Mon-Sun to Sun-Sat format
- iTemp++;
- if (iTemp > 6)
- {
- // Wrap Sunday and convert invalid data to Sunday
- iTemp = 0;
- }
- return iTemp;
- }
-
// Helper
// This is ONLY used for caching names and shouldn't be used for anything else
internal static string AnsiToLower(string testString)
{
- StringBuilder sb = new StringBuilder(testString.Length);
-
- for (int ich = 0; ich < testString.Length; ich++)
+ int index = 0;
+
+ while (index<testString.Length && (testString[index]<'A' || testString[index]>'Z' ))
{
- char ch = testString[ich];
- sb.Append(ch <= 'Z' && ch >= 'A' ? (char)(ch - 'A' + 'a') : ch);
+ index++;
}
-
- return (sb.ToString());
- }
-
- // If we get a group from windows, then its in 3;0 format with the 0 backwards
- // of how NLS+ uses it (ie: if the string has a 0, then the int[] shouldn't and vice versa)
- // EXCEPT in the case where the list only contains 0 in which NLS and NLS+ have the same meaning.
- static private int[] ConvertWin32GroupString(String win32Str)
- {
- // None of these cases make any sense
- if (win32Str == null || win32Str.Length == 0)
+ if (index >= testString.Length)
{
- return (new int[] { 3 });
+ return testString; // we didn't really change the string
}
-
- if (win32Str[0] == '0')
+
+ StringBuilder sb = new StringBuilder(testString.Length);
+ for (int i=0; i<index; i++)
{
- return (new int[] { 0 });
+ sb.Append(testString[i]);
}
- // Since its in n;n;n;n;n format, we can always get the length quickly
- int[] values;
- if (win32Str[win32Str.Length - 1] == '0')
- {
- // Trailing 0 gets dropped. 1;0 -> 1
- values = new int[(win32Str.Length / 2)];
- }
- else
- {
- // Need extra space for trailing zero 1 -> 1;0
- values = new int[(win32Str.Length / 2) + 2];
- values[values.Length - 1] = 0;
- }
+ sb.Append((char) (testString[index] -'A' + 'a'));
- int i;
- int j;
- for (i = 0, j = 0; i < win32Str.Length && j < values.Length; i += 2, j++)
+ for (int ich = index+1; ich < testString.Length; ich++)
{
- // Note that this # shouldn't ever be zero, 'cause 0 is only at end
- // But we'll test because its registry that could be anything
- if (win32Str[i] < '1' || win32Str[i] > '9')
- return new int[] { 3 };
-
- values[j] = (int)(win32Str[i] - '0');
+ char ch = testString[ich];
+ sb.Append(ch <= 'Z' && ch >= 'A' ? (char)(ch - 'A' + 'a') : ch);
}
- return (values);
+ return (sb.ToString());
}
- // LCTYPES for GetLocaleInfo
- private const uint LOCALE_NOUSEROVERRIDE = 0x80000000; // do not use user overrides
- private const uint LOCALE_RETURN_NUMBER = 0x20000000; // return number instead of string
-
- // Modifier for genitive names
- private const uint LOCALE_RETURN_GENITIVE_NAMES = 0x10000000; //Flag to return the Genitive forms of month names
-
- //
- // The following LCTypes are mutually exclusive in that they may NOT
- // be used in combination with each other.
- //
-
- //
- // These are the various forms of the name of the locale:
- //
- private const uint LOCALE_SLOCALIZEDDISPLAYNAME = 0x00000002; // localized name of locale, eg "German (Germany)" in UI language
- private const uint LOCALE_SENGLISHDISPLAYNAME = 0x00000072; // Display name (language + country usually) in English, eg "German (Germany)"
- private const uint LOCALE_SNATIVEDISPLAYNAME = 0x00000073; // Display name in native locale language, eg "Deutsch (Deutschland)
-
- private const uint LOCALE_SLOCALIZEDLANGUAGENAME = 0x0000006f; // Language Display Name for a language, eg "German" in UI language
- private const uint LOCALE_SENGLISHLANGUAGENAME = 0x00001001; // English name of language, eg "German"
- private const uint LOCALE_SNATIVELANGUAGENAME = 0x00000004; // native name of language, eg "Deutsch"
-
- private const uint LOCALE_SLOCALIZEDCOUNTRYNAME = 0x00000006; // localized name of country, eg "Germany" in UI language
- private const uint LOCALE_SENGLISHCOUNTRYNAME = 0x00001002; // English name of country, eg "Germany"
- private const uint LOCALE_SNATIVECOUNTRYNAME = 0x00000008; // native name of country, eg "Deutschland"
-
-
- // private const uint LOCALE_ILANGUAGE =0x00000001; // language id // Don't use, use NewApis::LocaleNameToLCID instead (GetLocaleInfo doesn't return neutrals)
-
- // private const uint LOCALE_SLANGUAGE =LOCALE_SLOCALIZEDDISPLAYNAME; // localized name of language (use LOCALE_SLOCALIZEDDISPLAYNAME instead)
- // private const uint LOCALE_SENGLANGUAGE =LOCALE_SENGLISHLANGUAGENAME; // English name of language (use LOCALE_SENGLISHLANGUAGENAME instead)
- private const uint LOCALE_SABBREVLANGNAME = 0x00000003; // abbreviated language name
- // private const uint LOCALE_SNATIVELANGNAME =LOCALE_SNATIVELANGUAGENAME; // native name of language (use LOCALE_SNATIVELANGUAGENAME instead)
-
- private const uint LOCALE_ICOUNTRY = 0x00000005; // country code
- // private const uint LOCALE_SCOUNTRY =LOCALE_SLOCALIZEDCOUNTRYNAME; // localized name of country (use LOCALE_SLOCALIZEDCOUNTRYNAME instead)
- // private const uint LOCALE_SENGCOUNTRY =LOCALE_SENGLISHCOUNTRYNAME; // English name of country (use LOCALE_SENGLISHCOUNTRYNAME instead)
- private const uint LOCALE_SABBREVCTRYNAME = 0x00000007; // abbreviated country name
- // private const uint LOCALE_SNATIVECTRYNAME =LOCALE_SNATIVECOUNTRYNAME; // native name of country ( use LOCALE_SNATIVECOUNTRYNAME instead)
- private const uint LOCALE_IGEOID = 0x0000005B; // geographical location id
-
- private const uint LOCALE_IDEFAULTLANGUAGE = 0x00000009; // default language id
- private const uint LOCALE_IDEFAULTCOUNTRY = 0x0000000A; // default country code
- private const uint LOCALE_IDEFAULTCODEPAGE = 0x0000000B; // default oem code page
- private const uint LOCALE_IDEFAULTANSICODEPAGE = 0x00001004; // default ansi code page
- private const uint LOCALE_IDEFAULTMACCODEPAGE = 0x00001011; // default mac code page
-
- private const uint LOCALE_SLIST = 0x0000000C; // list item separator
- private const uint LOCALE_IMEASURE = 0x0000000D; // 0 = metric, 1 = US
-
- private const uint LOCALE_SDECIMAL = 0x0000000E; // decimal separator
- private const uint LOCALE_STHOUSAND = 0x0000000F; // thousand separator
- private const uint LOCALE_SGROUPING = 0x00000010; // digit grouping
- private const uint LOCALE_IDIGITS = 0x00000011; // number of fractional digits
- private const uint LOCALE_ILZERO = 0x00000012; // leading zeros for decimal
- private const uint LOCALE_INEGNUMBER = 0x00001010; // negative number mode
- private const uint LOCALE_SNATIVEDIGITS = 0x00000013; // native digits for 0-9
-
- private const uint LOCALE_SCURRENCY = 0x00000014; // local monetary symbol
- private const uint LOCALE_SINTLSYMBOL = 0x00000015; // uintl monetary symbol
- private const uint LOCALE_SMONDECIMALSEP = 0x00000016; // monetary decimal separator
- private const uint LOCALE_SMONTHOUSANDSEP = 0x00000017; // monetary thousand separator
- private const uint LOCALE_SMONGROUPING = 0x00000018; // monetary grouping
- private const uint LOCALE_ICURRDIGITS = 0x00000019; // # local monetary digits
- private const uint LOCALE_IINTLCURRDIGITS = 0x0000001A; // # uintl monetary digits
- private const uint LOCALE_ICURRENCY = 0x0000001B; // positive currency mode
- private const uint LOCALE_INEGCURR = 0x0000001C; // negative currency mode
-
- private const uint LOCALE_SDATE = 0x0000001D; // date separator (derived from LOCALE_SSHORTDATE, use that instead)
- private const uint LOCALE_STIME = 0x0000001E; // time separator (derived from LOCALE_STIMEFORMAT, use that instead)
- private const uint LOCALE_SSHORTDATE = 0x0000001F; // short date format string
- private const uint LOCALE_SLONGDATE = 0x00000020; // long date format string
- private const uint LOCALE_STIMEFORMAT = 0x00001003; // time format string
- private const uint LOCALE_IDATE = 0x00000021; // short date format ordering (derived from LOCALE_SSHORTDATE, use that instead)
- private const uint LOCALE_ILDATE = 0x00000022; // long date format ordering (derived from LOCALE_SLONGDATE, use that instead)
- private const uint LOCALE_ITIME = 0x00000023; // time format specifier (derived from LOCALE_STIMEFORMAT, use that instead)
- private const uint LOCALE_ITIMEMARKPOSN = 0x00001005; // time marker position (derived from LOCALE_STIMEFORMAT, use that instead)
- private const uint LOCALE_ICENTURY = 0x00000024; // century format specifier (short date, LOCALE_SSHORTDATE is preferred)
- private const uint LOCALE_ITLZERO = 0x00000025; // leading zeros in time field (derived from LOCALE_STIMEFORMAT, use that instead)
- private const uint LOCALE_IDAYLZERO = 0x00000026; // leading zeros in day field (short date, LOCALE_SSHORTDATE is preferred)
- private const uint LOCALE_IMONLZERO = 0x00000027; // leading zeros in month field (short date, LOCALE_SSHORTDATE is preferred)
- private const uint LOCALE_S1159 = 0x00000028; // AM designator
- private const uint LOCALE_S2359 = 0x00000029; // PM designator
-
- private const uint LOCALE_ICALENDARTYPE = 0x00001009; // type of calendar specifier
- private const uint LOCALE_IOPTIONALCALENDAR = 0x0000100B; // additional calendar types specifier
- private const uint LOCALE_IFIRSTDAYOFWEEK = 0x0000100C; // first day of week specifier
- private const uint LOCALE_IFIRSTWEEKOFYEAR = 0x0000100D; // first week of year specifier
-
- private const uint LOCALE_SDAYNAME1 = 0x0000002A; // long name for Monday
- private const uint LOCALE_SDAYNAME2 = 0x0000002B; // long name for Tuesday
- private const uint LOCALE_SDAYNAME3 = 0x0000002C; // long name for Wednesday
- private const uint LOCALE_SDAYNAME4 = 0x0000002D; // long name for Thursday
- private const uint LOCALE_SDAYNAME5 = 0x0000002E; // long name for Friday
- private const uint LOCALE_SDAYNAME6 = 0x0000002F; // long name for Saturday
- private const uint LOCALE_SDAYNAME7 = 0x00000030; // long name for Sunday
- private const uint LOCALE_SABBREVDAYNAME1 = 0x00000031; // abbreviated name for Monday
- private const uint LOCALE_SABBREVDAYNAME2 = 0x00000032; // abbreviated name for Tuesday
- private const uint LOCALE_SABBREVDAYNAME3 = 0x00000033; // abbreviated name for Wednesday
- private const uint LOCALE_SABBREVDAYNAME4 = 0x00000034; // abbreviated name for Thursday
- private const uint LOCALE_SABBREVDAYNAME5 = 0x00000035; // abbreviated name for Friday
- private const uint LOCALE_SABBREVDAYNAME6 = 0x00000036; // abbreviated name for Saturday
- private const uint LOCALE_SABBREVDAYNAME7 = 0x00000037; // abbreviated name for Sunday
- private const uint LOCALE_SMONTHNAME1 = 0x00000038; // long name for January
- private const uint LOCALE_SMONTHNAME2 = 0x00000039; // long name for February
- private const uint LOCALE_SMONTHNAME3 = 0x0000003A; // long name for March
- private const uint LOCALE_SMONTHNAME4 = 0x0000003B; // long name for April
- private const uint LOCALE_SMONTHNAME5 = 0x0000003C; // long name for May
- private const uint LOCALE_SMONTHNAME6 = 0x0000003D; // long name for June
- private const uint LOCALE_SMONTHNAME7 = 0x0000003E; // long name for July
- private const uint LOCALE_SMONTHNAME8 = 0x0000003F; // long name for August
- private const uint LOCALE_SMONTHNAME9 = 0x00000040; // long name for September
- private const uint LOCALE_SMONTHNAME10 = 0x00000041; // long name for October
- private const uint LOCALE_SMONTHNAME11 = 0x00000042; // long name for November
- private const uint LOCALE_SMONTHNAME12 = 0x00000043; // long name for December
- private const uint LOCALE_SMONTHNAME13 = 0x0000100E; // long name for 13th month (if exists)
- private const uint LOCALE_SABBREVMONTHNAME1 = 0x00000044; // abbreviated name for January
- private const uint LOCALE_SABBREVMONTHNAME2 = 0x00000045; // abbreviated name for February
- private const uint LOCALE_SABBREVMONTHNAME3 = 0x00000046; // abbreviated name for March
- private const uint LOCALE_SABBREVMONTHNAME4 = 0x00000047; // abbreviated name for April
- private const uint LOCALE_SABBREVMONTHNAME5 = 0x00000048; // abbreviated name for May
- private const uint LOCALE_SABBREVMONTHNAME6 = 0x00000049; // abbreviated name for June
- private const uint LOCALE_SABBREVMONTHNAME7 = 0x0000004A; // abbreviated name for July
- private const uint LOCALE_SABBREVMONTHNAME8 = 0x0000004B; // abbreviated name for August
- private const uint LOCALE_SABBREVMONTHNAME9 = 0x0000004C; // abbreviated name for September
- private const uint LOCALE_SABBREVMONTHNAME10 = 0x0000004D; // abbreviated name for October
- private const uint LOCALE_SABBREVMONTHNAME11 = 0x0000004E; // abbreviated name for November
- private const uint LOCALE_SABBREVMONTHNAME12 = 0x0000004F; // abbreviated name for December
- private const uint LOCALE_SABBREVMONTHNAME13 = 0x0000100F; // abbreviated name for 13th month (if exists)
-
- private const uint LOCALE_SPOSITIVESIGN = 0x00000050; // positive sign
- private const uint LOCALE_SNEGATIVESIGN = 0x00000051; // negative sign
- private const uint LOCALE_IPOSSIGNPOSN = 0x00000052; // positive sign position (derived from INEGCURR)
- private const uint LOCALE_INEGSIGNPOSN = 0x00000053; // negative sign position (derived from INEGCURR)
- private const uint LOCALE_IPOSSYMPRECEDES = 0x00000054; // mon sym precedes pos amt (derived from ICURRENCY)
- private const uint LOCALE_IPOSSEPBYSPACE = 0x00000055; // mon sym sep by space from pos amt (derived from ICURRENCY)
- private const uint LOCALE_INEGSYMPRECEDES = 0x00000056; // mon sym precedes neg amt (derived from INEGCURR)
- private const uint LOCALE_INEGSEPBYSPACE = 0x00000057; // mon sym sep by space from neg amt (derived from INEGCURR)
-
- private const uint LOCALE_FONTSIGNATURE = 0x00000058; // font signature
- private const uint LOCALE_SISO639LANGNAME = 0x00000059; // ISO abbreviated language name
- private const uint LOCALE_SISO3166CTRYNAME = 0x0000005A; // ISO abbreviated country name
-
- private const uint LOCALE_IDEFAULTEBCDICCODEPAGE = 0x00001012; // default ebcdic code page
- private const uint LOCALE_IPAPERSIZE = 0x0000100A; // 1 = letter, 5 = legal, 8 = a3, 9 = a4
- private const uint LOCALE_SENGCURRNAME = 0x00001007; // english name of currency
- private const uint LOCALE_SNATIVECURRNAME = 0x00001008; // native name of currency
- private const uint LOCALE_SYEARMONTH = 0x00001006; // year month format string
- private const uint LOCALE_SSORTNAME = 0x00001013; // sort name
- private const uint LOCALE_IDIGITSUBSTITUTION = 0x00001014; // 0 = context, 1 = none, 2 = national
-
- private const uint LOCALE_SNAME = 0x0000005c; // locale name (with sort info) (ie: de-DE_phoneb)
- private const uint LOCALE_SDURATION = 0x0000005d; // time duration format
- private const uint LOCALE_SKEYBOARDSTOINSTALL = 0x0000005e; // (windows only) keyboards to install
- private const uint LOCALE_SSHORTESTDAYNAME1 = 0x00000060; // Shortest day name for Monday
- private const uint LOCALE_SSHORTESTDAYNAME2 = 0x00000061; // Shortest day name for Tuesday
- private const uint LOCALE_SSHORTESTDAYNAME3 = 0x00000062; // Shortest day name for Wednesday
- private const uint LOCALE_SSHORTESTDAYNAME4 = 0x00000063; // Shortest day name for Thursday
- private const uint LOCALE_SSHORTESTDAYNAME5 = 0x00000064; // Shortest day name for Friday
- private const uint LOCALE_SSHORTESTDAYNAME6 = 0x00000065; // Shortest day name for Saturday
- private const uint LOCALE_SSHORTESTDAYNAME7 = 0x00000066; // Shortest day name for Sunday
- private const uint LOCALE_SISO639LANGNAME2 = 0x00000067; // 3 character ISO abbreviated language name
- private const uint LOCALE_SISO3166CTRYNAME2 = 0x00000068; // 3 character ISO country name
- private const uint LOCALE_SNAN = 0x00000069; // Not a Number
- private const uint LOCALE_SPOSINFINITY = 0x0000006a; // + Infinity
- private const uint LOCALE_SNEGINFINITY = 0x0000006b; // - Infinity
- private const uint LOCALE_SSCRIPTS = 0x0000006c; // Typical scripts in the locale
- private const uint LOCALE_SPARENT = 0x0000006d; // Fallback name for resources
- private const uint LOCALE_SCONSOLEFALLBACKNAME = 0x0000006e; // Fallback name for within the console
- // private const uint LOCALE_SLANGDISPLAYNAME =LOCALE_SLOCALIZEDLANGUAGENAME; // Language Display Name for a language (use LOCALE_SLOCALIZEDLANGUAGENAME instead)
-
- // Windows 7 LCTYPES
- private const uint LOCALE_IREADINGLAYOUT = 0x00000070; // Returns one of the following 4 reading layout values:
- // 0 - Left to right (eg en-US)
- // 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
- private const uint LOCALE_INEUTRAL = 0x00000071; // Returns 0 for specific cultures, 1 for neutral cultures.
- private const uint LOCALE_INEGATIVEPERCENT = 0x00000074; // Returns 0-11 for the negative percent format
- private const uint LOCALE_IPOSITIVEPERCENT = 0x00000075; // Returns 0-3 for the positive percent formatIPOSITIVEPERCENT
- private const uint LOCALE_SPERCENT = 0x00000076; // Returns the percent symbol
- private const uint LOCALE_SPERMILLE = 0x00000077; // Returns the permille (U+2030) symbol
- private const uint LOCALE_SMONTHDAY = 0x00000078; // Returns the preferred month/day format
- private const uint LOCALE_SSHORTTIME = 0x00000079; // Returns the preferred short time format (ie: no seconds, just h:mm)
- private const uint LOCALE_SOPENTYPELANGUAGETAG = 0x0000007a; // Open type language tag, eg: "latn" or "dflt"
- private const uint LOCALE_SSORTLOCALE = 0x0000007b; // Name of locale to use for sorting/collation/casing behavior.
-
- // Time formats enumerations
- internal const uint TIME_NOSECONDS = 0x00000002; // Don't use seconds (get short time format for enumtimeformats on win7+)
-
- // Get our initial minimal culture data (name, parent, etc.)
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool nativeInitCultureData(CultureData cultureData);
-
- // Grab the NumberFormatInfo data
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool nativeGetNumberFormatInfoValues(String localeName, NumberFormatInfo nfi, bool useUserOverride);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern String[] nativeEnumTimeFormats(String localeName, uint dwFlags, bool useUserOverride);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- internal static extern int nativeEnumCultureNames(int cultureTypes, ObjectHandleOnStack retStringArray);
+ /// <remarks>
+ /// The numeric values of the enum members match their Win32 counterparts. The CultureData Win32 PAL implementation
+ /// takes a dependency on this fact, in order to prevent having to construct a mapping from internal values to LCTypes.
+ /// </remarks>
+ private enum LocaleStringData : uint
+ {
+ /// <summary>localized name of locale, eg "German (Germany)" in UI language (coresponds to LOCALE_SLOCALIZEDDISPLAYNAME)</summary>
+ LocalizedDisplayName = 0x00000002,
+ /// <summary>Display name (language + country usually) in English, eg "German (Germany)" (coresponds to LOCALE_SENGLISHDISPLAYNAME)</summary>
+ EnglishDisplayName = 0x00000072,
+ /// <summary>Display name in native locale language, eg "Deutsch (Deutschland) (coresponds to LOCALE_SNATIVEDISPLAYNAME)</summary>
+ NativeDisplayName = 0x00000073,
+ /// <summary>Language Display Name for a language, eg "German" in UI language (coresponds to LOCALE_SLOCALIZEDLANGUAGENAME)</summary>
+ LocalizedLanguageName = 0x0000006f,
+ /// <summary>English name of language, eg "German" (coresponds to LOCALE_SENGLISHLANGUAGENAME)</summary>
+ EnglishLanguageName = 0x00001001,
+ /// <summary>native name of language, eg "Deutsch" (coresponds to LOCALE_SNATIVELANGUAGENAME)</summary>
+ NativeLanguageName = 0x00000004,
+ /// <summary>localized name of country, eg "Germany" in UI language (coresponds to LOCALE_SLOCALIZEDCOUNTRYNAME)</summary>
+ LocalizedCountryName = 0x00000006,
+ /// <summary>English name of country, eg "Germany" (coresponds to LOCALE_SENGLISHCOUNTRYNAME)</summary>
+ EnglishCountryName = 0x00001002,
+ /// <summary>native name of country, eg "Deutschland" (coresponds to LOCALE_SNATIVECOUNTRYNAME)</summary>
+ NativeCountryName = 0x00000008,
+ /// <summary>abbreviated language name (coresponds to LOCALE_SABBREVLANGNAME)</summary>
+ AbbreviatedWindowsLanguageName = 0x00000003,
+ /// <summary>list item separator (coresponds to LOCALE_SLIST)</summary>
+ ListSeparator = 0x0000000C,
+ /// <summary>decimal separator (coresponds to LOCALE_SDECIMAL)</summary>
+ DecimalSeparator = 0x0000000E,
+ /// <summary>thousand separator (coresponds to LOCALE_STHOUSAND)</summary>
+ ThousandSeparator = 0x0000000F,
+ /// <summary>digit grouping (coresponds to LOCALE_SGROUPING)</summary>
+ Digits = 0x00000013,
+ /// <summary>local monetary symbol (coresponds to LOCALE_SCURRENCY)</summary>
+ MonetarySymbol = 0x00000014,
+ /// <summary>English currency name (coresponds to LOCALE_SENGCURRNAME)</summary>
+ CurrencyEnglishName = 0x00001007,
+ /// <summary>Native currency name (coresponds to LOCALE_SNATIVECURRNAME)</summary>
+ CurrencyNativeName = 0x00001008,
+ /// <summary>uintl monetary symbol (coresponds to LOCALE_SINTLSYMBOL)</summary>
+ Iso4217MonetarySymbol = 0x00000015,
+ /// <summary>monetary decimal separator (coresponds to LOCALE_SMONDECIMALSEP)</summary>
+ MonetaryDecimalSeparator = 0x00000016,
+ /// <summary>monetary thousand separator (coresponds to LOCALE_SMONTHOUSANDSEP)</summary>
+ MonetaryThousandSeparator = 0x00000017,
+ /// <summary>AM designator (coresponds to LOCALE_S1159)</summary>
+ AMDesignator = 0x00000028,
+ /// <summary>PM designator (coresponds to LOCALE_S2359)</summary>
+ PMDesignator = 0x00000029,
+ /// <summary>positive sign (coresponds to LOCALE_SPOSITIVESIGN)</summary>
+ PositiveSign = 0x00000050,
+ /// <summary>negative sign (coresponds to LOCALE_SNEGATIVESIGN)</summary>
+ NegativeSign = 0x00000051,
+ /// <summary>ISO abbreviated language name (coresponds to LOCALE_SISO639LANGNAME)</summary>
+ Iso639LanguageTwoLetterName = 0x00000059,
+ /// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO639LANGNAME2)</summary>
+ Iso639LanguageThreeLetterName = 0x00000067,
+ /// <summary>ISO abbreviated language name (coresponds to LOCALE_SISO639LANGNAME)</summary>
+ Iso639LanguageName = 0x00000059,
+ /// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO3166CTRYNAME)</summary>
+ Iso3166CountryName = 0x0000005A,
+ /// <summary>3 letter ISO country code (coresponds to LOCALE_SISO3166CTRYNAME2)</summary>
+ Iso3166CountryName2 = 0x00000068, // 3 character ISO country name
+ /// <summary>Not a Number (coresponds to LOCALE_SNAN)</summary>
+ NaNSymbol = 0x00000069,
+ /// <summary>+ Infinity (coresponds to LOCALE_SPOSINFINITY)</summary>
+ PositiveInfinitySymbol = 0x0000006a,
+ /// <summary>- Infinity (coresponds to LOCALE_SNEGINFINITY)</summary>
+ NegativeInfinitySymbol = 0x0000006b,
+ /// <summary>Fallback name for resources (coresponds to LOCALE_SPARENT)</summary>
+ ParentName = 0x0000006d,
+ /// <summary>Fallback name for within the console (coresponds to LOCALE_SCONSOLEFALLBACKNAME)</summary>
+ ConsoleFallbackName = 0x0000006e,
+ /// <summary>Returns the percent symbol (coresponds to LOCALE_SPERCENT)</summary>
+ PercentSymbol = 0x00000076,
+ /// <summary>Returns the permille (U+2030) symbol (coresponds to LOCALE_SPERMILLE)</summary>
+ PerMilleSymbol = 0x00000077
+ }
+
+ /// <remarks>
+ /// The numeric values of the enum members match their Win32 counterparts. The CultureData Win32 PAL implementation
+ /// takes a dependency on this fact, in order to prevent having to construct a mapping from internal values to LCTypes.
+ /// </remarks>
+ private enum LocaleGroupingData : uint
+ {
+ /// <summary>digit grouping (coresponds to LOCALE_SGROUPING)</summary>
+ Digit = 0x00000010,
+ /// <summary>monetary grouping (coresponds to LOCALE_SMONGROUPING)</summary>
+ Monetary = 0x00000018,
+ }
+
+ /// <remarks>
+ /// The numeric values of the enum members match their Win32 counterparts. The CultureData Win32 PAL implementation
+ /// takes a dependency on this fact, in order to prevent having to construct a mapping from internal values to LCTypes.
+ /// </remarks>
+ private enum LocaleNumberData : uint
+ {
+ /// <summary>language id (coresponds to LOCALE_ILANGUAGE)</summary>
+ LanguageId = 0x00000001,
+ /// <summary>geographical location id, (coresponds to LOCALE_IGEOID)</summary>
+ GeoId = 0x0000005B,
+ /// <summary>0 = context, 1 = none, 2 = national (coresponds to LOCALE_IDIGITSUBSTITUTION)</summary>
+ DigitSubstitution = 0x00001014,
+ /// <summary>0 = metric, 1 = US (coresponds to LOCALE_IMEASURE)</summary>
+ MeasurementSystem = 0x0000000D,
+ /// <summary>number of fractional digits (coresponds to LOCALE_IDIGITS)</summary>
+ FractionalDigitsCount = 0x00000011,
+ /// <summary>negative number mode (coresponds to LOCALE_INEGNUMBER)</summary>
+ NegativeNumberFormat = 0x00001010,
+ /// <summary># local monetary digits (coresponds to LOCALE_ICURRDIGITS)</summary>
+ MonetaryFractionalDigitsCount = 0x00000019,
+ /// <summary>positive currency mode (coresponds to LOCALE_ICURRENCY)</summary>
+ PositiveMonetaryNumberFormat = 0x0000001B,
+ /// <summary>negative currency mode (coresponds to LOCALE_INEGCURR)</summary>
+ NegativeMonetaryNumberFormat = 0x0000001C,
+ /// <summary>type of calendar specifier (coresponds to LOCALE_ICALENDARTYPE)</summary>
+ CalendarType = 0x00001009,
+ /// <summary>first day of week specifier (coresponds to LOCALE_IFIRSTDAYOFWEEK)</summary>
+ FirstDayOfWeek = 0x0000100C,
+ /// <summary>first week of year specifier (coresponds to LOCALE_IFIRSTWEEKOFYEAR)</summary>
+ FirstWeekOfYear = 0x0000100D,
+ /// <summary>
+ /// Returns one of the following 4 reading layout values:
+ /// 0 - Left to right (eg en-US)
+ /// 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)
+ /// </summary>
+ ReadingLayout = 0x00000070,
+ /// <summary>Returns 0-11 for the negative percent format (coresponds to LOCALE_INEGATIVEPERCENT)</summary>
+ NegativePercentFormat = 0x00000074,
+ /// <summary>Returns 0-3 for the positive percent format (coresponds to LOCALE_IPOSITIVEPERCENT)</summary>
+ PositivePercentFormat = 0x00000075,
+ /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTCODEPAGE)</summary>
+ OemCodePage = 0x0000000B,
+ /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTANSICODEPAGE)</summary>
+ AnsiCodePage = 0x00001004,
+ /// <summary>default mac code page (coresponds to LOCALE_IDEFAULTMACCODEPAGE)</summary>
+ MacCodePage = 0x00001011,
+ /// <summary>default ebcdic code page (coresponds to LOCALE_IDEFAULTEBCDICCODEPAGE)</summary>
+ EbcdicCodePage = 0x00001012,
+ }
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.Unix.cs b/src/mscorlib/src/System/Globalization/CultureInfo.Unix.cs
new file mode 100644
index 0000000000..7a8a9fd08d
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.Unix.cs
@@ -0,0 +1,128 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Threading;
+
+namespace System.Globalization
+{
+ public partial class CultureInfo : IFormatProvider
+ {
+ private static CultureInfo GetUserDefaultCultureCacheOverride()
+ {
+ return null; // ICU doesn't provide a user override
+ }
+
+ internal static CultureInfo GetUserDefaultCulture()
+ {
+ if (GlobalizationMode.Invariant)
+ return CultureInfo.InvariantCulture;
+
+ CultureInfo cultureInfo = null;
+ string localeName;
+ if (CultureData.GetDefaultLocaleName(out localeName))
+ {
+ cultureInfo = GetCultureByName(localeName, true);
+ cultureInfo._isReadOnly = true;
+ }
+ else
+ {
+ cultureInfo = CultureInfo.InvariantCulture;
+ }
+
+ return cultureInfo;
+ }
+
+ private static CultureInfo GetUserDefaultUILanguage()
+ {
+ return GetUserDefaultCulture();
+ }
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // CurrentCulture
+ //
+ // This instance provides methods based on the current user settings.
+ // These settings are volatile and may change over the lifetime of the
+ // thread.
+ //
+ ////////////////////////////////////////////////////////////////////////
+
+ //
+ // We use the following order to return CurrentCulture and CurrentUICulture
+ // o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture
+ // o use thread culture if the user already set one using DefaultThreadCurrentCulture
+ // or DefaultThreadCurrentUICulture
+ // o Use NLS default user culture
+ // o Use NLS default system culture
+ // o Use Invariant culture
+ //
+ public static CultureInfo CurrentCulture
+ {
+ get
+ {
+ if (Thread.m_CurrentCulture != null)
+ {
+ return Thread.m_CurrentCulture;
+ }
+
+ CultureInfo ci = s_DefaultThreadCurrentCulture;
+ if (ci != null)
+ {
+ return ci;
+ }
+
+ // if s_userDefaultCulture == 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_userDefaultCulture == null)
+ {
+ Init();
+ }
+
+ Debug.Assert(s_userDefaultCulture != null);
+ return s_userDefaultCulture;
+ }
+
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
+ if (s_asyncLocalCurrentCulture == null)
+ {
+ Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentCulture), null);
+ }
+ s_asyncLocalCurrentCulture.Value = value;
+ }
+ }
+
+ public static CultureInfo CurrentUICulture
+ {
+ get
+ {
+ return GetCurrentUICultureNoAppX();
+ }
+
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
+ CultureInfo.VerifyCultureName(value, true);
+ if (s_asyncLocalCurrentUICulture == null)
+ {
+ Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentUICulture), null);
+ }
+
+ // this one will set s_currentThreadUICulture too
+ s_asyncLocalCurrentUICulture.Value = value;
+ }
+ }
+
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.Windows.cs b/src/mscorlib/src/System/Globalization/CultureInfo.Windows.cs
new file mode 100644
index 0000000000..e33874e760
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.Windows.cs
@@ -0,0 +1,278 @@
+// 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;
+
+#if ENABLE_WINRT
+using Internal.Runtime.Augments;
+#endif
+
+using System.Threading;
+#if FEATURE_APPX
+using System.Resources;
+#endif
+
+namespace System.Globalization
+{
+ public partial class CultureInfo : IFormatProvider
+ {
+#if FEATURE_APPX
+ // When running under AppX, we use this to get some information about the language list
+ private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager;
+
+ [ThreadStatic]
+ private static bool ts_IsDoingAppXCultureInfoLookup;
+#endif
+
+ /// <summary>
+ /// Gets the default user culture from WinRT, if available.
+ /// </summary>
+ /// <remarks>
+ /// This method may return null, if there is no default user culture or if WinRT isn't available.
+ /// </remarks>
+ private static CultureInfo GetUserDefaultCultureCacheOverride()
+ {
+#if ENABLE_WINRT
+ WinRTInteropCallbacks callbacks = WinRTInterop.UnsafeCallbacks;
+ if (callbacks != null && callbacks.IsAppxModel())
+ {
+ return (CultureInfo)callbacks.GetUserDefaultCulture();
+ }
+#endif
+
+ return null;
+ }
+
+ internal static CultureInfo GetUserDefaultCulture()
+ {
+ if (GlobalizationMode.Invariant)
+ return CultureInfo.InvariantCulture;
+
+ const uint LOCALE_SNAME = 0x0000005c;
+ const string LOCALE_NAME_USER_DEFAULT = null;
+ const string LOCALE_NAME_SYSTEM_DEFAULT = "!x-sys-default-locale";
+
+ string strDefault = CultureData.GetLocaleInfoEx(LOCALE_NAME_USER_DEFAULT, LOCALE_SNAME);
+ if (strDefault == null)
+ {
+ strDefault = CultureData.GetLocaleInfoEx(LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_SNAME);
+
+ if (strDefault == null)
+ {
+ // If system default doesn't work, use invariant
+ return CultureInfo.InvariantCulture;
+ }
+ }
+
+ CultureInfo temp = GetCultureByName(strDefault, true);
+
+ temp._isReadOnly = true;
+
+ return temp;
+ }
+
+ private static CultureInfo GetUserDefaultUILanguage()
+ {
+ if (GlobalizationMode.Invariant)
+ return CultureInfo.InvariantCulture;
+
+ const uint MUI_LANGUAGE_NAME = 0x8; // Use ISO language (culture) name convention
+ uint langCount = 0;
+ uint bufLen = 0;
+
+ if (Interop.Kernel32.GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, out langCount, null, ref bufLen))
+ {
+ char [] languages = new char[bufLen];
+ if (Interop.Kernel32.GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, out langCount, languages, ref bufLen))
+ {
+ int index = 0;
+ while (languages[index] != (char) 0 && index<languages.Length)
+ {
+ index++;
+ }
+
+ CultureInfo temp = GetCultureByName(new String(languages, 0, index), true);
+ temp._isReadOnly = true;
+ return temp;
+ }
+ }
+
+ return GetUserDefaultCulture();
+ }
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // CurrentCulture
+ //
+ // This instance provides methods based on the current user settings.
+ // These settings are volatile and may change over the lifetime of the
+ // thread.
+ //
+ ////////////////////////////////////////////////////////////////////////
+
+ //
+ // We use the following order to return CurrentCulture and CurrentUICulture
+ // o Use WinRT to return the current user profile language
+ // o use current thread culture if the user already set one using CurrentCulture/CurrentUICulture
+ // o use thread culture if the user already set one using DefaultThreadCurrentCulture
+ // or DefaultThreadCurrentUICulture
+ // o Use NLS default user culture
+ // o Use NLS default system culture
+ // o Use Invariant culture
+ //
+ public static CultureInfo CurrentCulture
+ {
+ get
+ {
+#if FEATURE_APPX
+ if (AppDomain.IsAppXModel())
+ {
+ CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
+ if (culture != null)
+ return culture;
+ }
+#endif
+ CultureInfo ci = GetUserDefaultCultureCacheOverride();
+ if (ci != null)
+ {
+ return ci;
+ }
+
+ if (Thread.m_CurrentCulture != null)
+ {
+ return Thread.m_CurrentCulture;
+ }
+
+ ci = s_DefaultThreadCurrentCulture;
+ if (ci != null)
+ {
+ return ci;
+ }
+
+ // if s_userDefaultCulture == 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_userDefaultCulture == null)
+ {
+ Init();
+ }
+
+ Debug.Assert(s_userDefaultCulture != null);
+ return s_userDefaultCulture;
+ }
+
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
+#if FEATURE_APPX
+ if (AppDomain.IsAppXModel())
+ {
+ if (SetCultureInfoForUserPreferredLanguageInAppX(value))
+ {
+ // successfully set the culture, otherwise fallback to legacy path
+ return;
+ }
+ }
+#endif
+ if (s_asyncLocalCurrentCulture == null)
+ {
+ Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentCulture), null);
+ }
+ s_asyncLocalCurrentCulture.Value = value;
+ }
+ }
+
+ public static CultureInfo CurrentUICulture
+ {
+ get
+ {
+#if FEATURE_APPX
+ if (AppDomain.IsAppXModel())
+ {
+ CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
+ if (culture != null)
+ return culture;
+ }
+#endif
+ return GetCurrentUICultureNoAppX();
+ }
+
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
+ }
+
+ CultureInfo.VerifyCultureName(value, true);
+#if FEATURE_APPX
+ if (AppDomain.IsAppXModel())
+ {
+ if (SetCultureInfoForUserPreferredLanguageInAppX(value))
+ {
+ // successfully set the culture, otherwise fallback to legacy path
+ return;
+ }
+ }
+#endif
+ if (s_asyncLocalCurrentUICulture == null)
+ {
+ Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentUICulture), null);
+ }
+
+ // this one will set s_currentThreadUICulture too
+ s_asyncLocalCurrentUICulture.Value = value;
+ }
+ }
+
+#if FEATURE_APPX
+ internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
+ {
+ // If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive
+ // call to itself, return null, since we don't want to stack overflow. For example,
+ // this can happen if some code in this method ends up calling CultureInfo.CurrentCulture
+ // (which is common on check'd build because of BCLDebug logging which calls Int32.ToString()).
+ // In this case, returning null will mean CultureInfo.CurrentCulture gets the default Win32
+ // value, which should be fine.
+ if (ts_IsDoingAppXCultureInfoLookup)
+ {
+ return null;
+ }
+
+ CultureInfo toReturn = null;
+
+ try
+ {
+ ts_IsDoingAppXCultureInfoLookup = true;
+
+ if (s_WindowsRuntimeResourceManager == null)
+ {
+ s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
+ }
+
+ toReturn = s_WindowsRuntimeResourceManager.GlobalResourceContextBestFitCultureInfo;
+ }
+ finally
+ {
+ ts_IsDoingAppXCultureInfoLookup = false;
+ }
+
+ return toReturn;
+ }
+
+ internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci)
+ {
+ if (s_WindowsRuntimeResourceManager == null)
+ {
+ s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
+ }
+
+ return s_WindowsRuntimeResourceManager.SetGlobalResourceContextDefaultCulture(ci);
+ }
+#endif
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs
index ba61c146f6..60938defac 100644
--- a/src/mscorlib/src/System/Globalization/CultureInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs
@@ -26,24 +26,27 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
- using System;
- using System.Security;
- using System.Threading;
- using System.Collections;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Reflection;
- using Microsoft.Win32;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Resources;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Threading;
+
+namespace System.Globalization
+{
+#if CORECLR
+ using StringCultureInfoDictionary = Dictionary<string, CultureInfo>;
+ using StringLcidDictionary = Dictionary<int, CultureInfo>;
+
+ using Lock = Object;
+#else
+ using StringCultureInfoDictionary = LowLevelDictionary<string, CultureInfo>;
+ using StringLcidDictionary = LowLevelDictionary<int, CultureInfo>;
+#endif
[Serializable]
- public partial class CultureInfo : ICloneable, IFormatProvider {
+ public partial class CultureInfo : IFormatProvider, ICloneable
+ {
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
@@ -53,38 +56,32 @@ namespace System.Globalization {
//--------------------------------------------------------------------//
// We use an RFC4646 type string to construct CultureInfo.
- // This string is stored in m_name and is authoritative.
- // We use the m_cultureData to get the data for our object
-
- // WARNING
- // WARNING: All member fields declared here must also be in ndp/clr/src/vm/object.h
- // WARNING: They aren't really private because object.h can access them, but other C# stuff cannot
- // WARNING: The type loader will rearrange class member offsets so the mscorwks!CultureInfoBaseObject
- // WARNING: must be manually structured to match the true loaded class layout
- // WARNING
- internal bool m_isReadOnly;
- internal CompareInfo compareInfo;
- internal TextInfo textInfo;
+ // This string is stored in _name and is authoritative.
+ // We use the _cultureData to get the data for our object
+
+ private bool _isReadOnly;
+ private CompareInfo compareInfo;
+ private TextInfo textInfo;
internal NumberFormatInfo numInfo;
internal DateTimeFormatInfo dateTimeInfo;
- internal Calendar calendar;
- [OptionalField(VersionAdded = 1)]
- internal int m_dataItem; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
- [OptionalField(VersionAdded = 1)]
- internal int cultureID = 0x007f; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
+ private Calendar calendar;
//
// The CultureData instance that we are going to read data from.
// For supported culture, this will be the CultureData instance that read data from mscorlib assembly.
// For customized culture, this will be the CultureData instance that read data from user customized culture binary file.
//
- [NonSerialized]internal CultureData m_cultureData;
-
- [NonSerialized]internal bool m_isInherited;
- [NonSerialized]private CultureInfo m_consoleFallbackCulture;
+ [NonSerialized]
+ internal CultureData _cultureData;
+
+ [NonSerialized]
+ internal bool _isInherited;
+
+ [NonSerialized]
+ private CultureInfo _consoleFallbackCulture;
// Names are confusing. Here are 3 names we have:
//
- // new CultureInfo() m_name m_nonSortName m_sortName
+ // new CultureInfo() _name _nonSortName _sortName
// en-US en-US en-US en-US
// de-de_phoneb de-DE_phoneb de-DE de-DE_phoneb
// fj-fj (custom) fj-FJ fj-FJ en-US (if specified sort is en-US)
@@ -96,17 +93,18 @@ namespace System.Globalization {
// Note that the name used to be serialized for Everett; it is now serialized
// because alernate sorts can have alternate names.
// This has a de-DE, de-DE_phoneb or fj-FJ style name
- internal string m_name;
+ internal string _name;
// This will hold the non sorting name to be returned from CultureInfo.Name property.
// This has a de-DE style name even for de-DE_phoneb type cultures
- [NonSerialized]private string m_nonSortName;
+ [NonSerialized]
+ private string _nonSortName;
// This will hold the sorting name to be returned from CultureInfo.SortName property.
// This might be completely unrelated to the culture name if a custom culture. Ie en-US for fj-FJ.
// Otherwise its the sort name, ie: de-DE or de-DE_phoneb
- [NonSerialized]private string m_sortName;
-
+ [NonSerialized]
+ private string _sortName;
//--------------------------------------------------------------------//
//
@@ -117,184 +115,74 @@ namespace System.Globalization {
//Get the current user default culture. This one is almost always used, so we create it by default.
private static volatile CultureInfo s_userDefaultCulture;
+ //The culture used in the user interface. This is mostly used to load correct localized resources.
+ private static volatile CultureInfo s_userDefaultUICulture;
//
// All of the following will be created on demand.
//
+ // WARNING: We allow diagnostic tools to directly inspect these three members (s_InvariantCultureInfo, s_DefaultThreadCurrentUICulture and s_DefaultThreadCurrentCulture)
+ // See https://github.com/dotnet/corert/blob/master/Documentation/design-docs/diagnostics/diagnostics-tools-contract.md for more details.
+ // Please do not change the type, the name, or the semantic usage of this member without understanding the implication for tools.
+ // Get in touch with the diagnostics team if you have questions.
+
//The Invariant culture;
private static volatile CultureInfo s_InvariantCultureInfo;
- //The culture used in the user interface. This is mostly used to load correct localized resources.
- private static volatile CultureInfo s_userDefaultUICulture;
-
- //This is the UI culture used to install the OS.
- private static volatile CultureInfo s_InstalledUICultureInfo;
-
//These are defaults that we use if a thread has not opted into having an explicit culture
private static volatile CultureInfo s_DefaultThreadCurrentUICulture;
private static volatile CultureInfo s_DefaultThreadCurrentCulture;
- //This is a cache of all previously created cultures. Valid keys are LCIDs or the name. We use two hashtables to track them,
- // depending on how they are called.
- private static volatile Hashtable s_LcidCachedCultures;
- private static volatile Hashtable s_NameCachedCultures;
+ internal static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture;
+ internal static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture;
-#if FEATURE_APPX
- // When running under AppX, we use this to get some information about the language list
- private static volatile WindowsRuntimeResourceManagerBase s_WindowsRuntimeResourceManager;
+ internal static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args)
+ {
+ Thread.m_CurrentCulture = args.CurrentValue;
+ }
- [ThreadStatic]
- private static bool ts_IsDoingAppXCultureInfoLookup;
-#endif
+ internal static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args)
+ {
+ Thread.m_CurrentUICulture = args.CurrentValue;
+ }
+
+ private static readonly Lock _lock = new Lock();
+ private static volatile StringCultureInfoDictionary s_NameCachedCultures;
+ private static volatile StringLcidDictionary s_LcidCachedCultures;
//The parent culture.
- [NonSerialized]private CultureInfo m_parent;
+ [NonSerialized]
+ private CultureInfo _parent;
// LOCALE constants of interest to us internally and privately for LCID functions
// (ie: avoid using these and use names if possible)
- internal const int LOCALE_NEUTRAL = 0x0000;
- private const int LOCALE_USER_DEFAULT = 0x0400;
- private const int LOCALE_SYSTEM_DEFAULT = 0x0800;
- internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00;
- internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
- internal const int LOCALE_INVARIANT = 0x007F;
- private const int LOCALE_TRADITIONAL_SPANISH = 0x040a;
+ internal const int LOCALE_NEUTRAL = 0x0000;
+ private const int LOCALE_USER_DEFAULT = 0x0400;
+ private const int LOCALE_SYSTEM_DEFAULT = 0x0800;
+ internal const int LOCALE_CUSTOM_UNSPECIFIED = 0x1000;
+ internal const int LOCALE_CUSTOM_DEFAULT = 0x0c00;
+ internal const int LOCALE_INVARIANT = 0x007F;
//
// The CultureData instance that reads the data provided by our CultureData class.
//
- //Using a field initializer rather than a static constructor so that the whole class can be lazy
- //init.
+ // Using a field initializer rather than a static constructor so that the whole class can be lazy
+ // init.
private static readonly bool init = Init();
private static bool Init()
{
-
- if (s_InvariantCultureInfo == null)
+ if (s_InvariantCultureInfo == null)
{
CultureInfo temp = new CultureInfo("", false);
- temp.m_isReadOnly = true;
+ temp._isReadOnly = true;
s_InvariantCultureInfo = temp;
}
- // First we set it to Invariant in case someone needs it before we're done finding it.
- // For example, if we throw an exception in InitUserDefaultCulture, we will still need an valid
- // s_userDefaultCulture to be used in Thread.CurrentCulture.
- s_userDefaultCulture = s_userDefaultUICulture = s_InvariantCultureInfo;
- s_userDefaultCulture = InitUserDefaultCulture();
- s_userDefaultUICulture = InitUserDefaultUICulture();
+ s_userDefaultCulture = GetUserDefaultCulture();
+ s_userDefaultUICulture = GetUserDefaultUILanguage();
return true;
}
- static CultureInfo InitUserDefaultCulture()
- {
- String strDefault = GetDefaultLocaleName(LOCALE_USER_DEFAULT);
- if (strDefault == null)
- {
- strDefault = GetDefaultLocaleName(LOCALE_SYSTEM_DEFAULT);
-
- if (strDefault == null)
- {
- // If system default doesn't work, keep using the invariant
- return (CultureInfo.InvariantCulture);
- }
- }
- CultureInfo temp = GetCultureByName(strDefault, true);
-
- temp.m_isReadOnly = true;
-
- return (temp);
- }
-
- static CultureInfo InitUserDefaultUICulture()
- {
- String strDefault = GetUserDefaultUILanguage();
-
- // In most of cases, UserDefaultCulture == UserDefaultUICulture, so we should use the same instance if possible.
- if (strDefault == UserDefaultCulture.Name)
- {
- return (UserDefaultCulture);
- }
-
- CultureInfo temp = GetCultureByName( strDefault, true);
-
- if (temp == null)
- {
- return (CultureInfo.InvariantCulture);
- }
-
- temp.m_isReadOnly = true;
-
- return (temp);
- }
-
-#if FEATURE_APPX
- internal static CultureInfo GetCultureInfoForUserPreferredLanguageInAppX()
- {
- // If a call to GetCultureInfoForUserPreferredLanguageInAppX() generated a recursive
- // call to itself, return null, since we don't want to stack overflow. For example,
- // this can happen if some code in this method ends up calling CultureInfo.CurrentCulture
- // (which is common on check'd build because of BCLDebug logging which calls Int32.ToString()).
- // In this case, returning null will mean CultureInfo.CurrentCulture gets the default Win32
- // value, which should be fine.
- if(ts_IsDoingAppXCultureInfoLookup)
- {
- return null;
- }
-
- // If running within a compilation process (mscorsvw.exe, for example), it is illegal to
- // load any non-mscorlib assembly for execution. Since WindowsRuntimeResourceManager lives
- // in System.Runtime.WindowsRuntime, caller will need to fall back to default Win32 value,
- // which should be fine because we should only ever need to access FX resources during NGEN.
- // FX resources are always loaded from satellite assemblies - even in AppX processes (see the
- // comments in code:System.Resources.ResourceManager.SetAppXConfiguration for more details).
- if (AppDomain.IsAppXNGen)
- {
- return null;
- }
-
- CultureInfo toReturn = null;
-
- try
- {
- ts_IsDoingAppXCultureInfoLookup = true;
-
- if(s_WindowsRuntimeResourceManager == null)
- {
- s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
- }
-
- toReturn = s_WindowsRuntimeResourceManager.GlobalResourceContextBestFitCultureInfo;
- }
- finally
- {
- ts_IsDoingAppXCultureInfoLookup = false;
- }
-
- return toReturn;
- }
-
- internal static bool SetCultureInfoForUserPreferredLanguageInAppX(CultureInfo ci)
- {
- // If running within a compilation process (mscorsvw.exe, for example), it is illegal to
- // load any non-mscorlib assembly for execution. Since WindowsRuntimeResourceManager lives
- // in System.Runtime.WindowsRuntime, caller will need to fall back to default Win32 value,
- // which should be fine because we should only ever need to access FX resources during NGEN.
- // FX resources are always loaded from satellite assemblies - even in AppX processes (see the
- // comments in code:System.Resources.ResourceManager.SetAppXConfiguration for more details).
- if (AppDomain.IsAppXNGen)
- {
- return false;
- }
-
- if (s_WindowsRuntimeResourceManager == null)
- {
- s_WindowsRuntimeResourceManager = ResourceManager.GetWinRTResourceManager();
- }
-
- return s_WindowsRuntimeResourceManager.SetGlobalResourceContextDefaultCulture(ci);
- }
-#endif
-
////////////////////////////////////////////////////////////////////////
//
// CultureInfo Constructors
@@ -302,38 +190,33 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public CultureInfo(String name) : this(name, true) {
+ public CultureInfo(String name)
+ : this(name, true)
+ {
}
- public CultureInfo(String name, bool useUserOverride) {
- if (name==null) {
+ public CultureInfo(String name, bool useUserOverride)
+ {
+ if (name == null)
+ {
throw new ArgumentNullException(nameof(name),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
-
- // Get our data providing record
- this.m_cultureData = CultureData.GetCultureData(name, useUserOverride);
- if (this.m_cultureData == null) {
- throw new CultureNotFoundException(nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported"));
- }
-
- this.m_name = this.m_cultureData.CultureName;
- this.m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
+ InitializeFromName(name, useUserOverride);
}
-
-#if FEATURE_USE_LCID
- public CultureInfo(int culture) : this(culture, true) {
+ public CultureInfo(int culture) : this(culture, true)
+ {
}
- public CultureInfo(int culture, bool useUserOverride) {
+ public CultureInfo(int culture, bool useUserOverride)
+ {
// We don't check for other invalid LCIDS here...
- if (culture < 0) {
- throw new ArgumentOutOfRangeException(nameof(culture),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ if (culture < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
@@ -351,88 +234,31 @@ namespace System.Globalization {
case LOCALE_CUSTOM_UNSPECIFIED:
// Can't support unknown custom cultures and we do not support neutral or
// non-custom user locales.
- throw new CultureNotFoundException(
- nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported"));
+ throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
default:
- // Now see if this LCID is supported in the system default CultureData table.
- this.m_cultureData = CultureData.GetCultureData(culture, useUserOverride);
+ // Now see if this LCID is supported in the system default CultureData table.
+ _cultureData = CultureData.GetCultureData(culture, useUserOverride);
break;
}
- this.m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
- this.m_name = this.m_cultureData.CultureName;
+ _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
+ _name = _cultureData.CultureName;
}
-#endif // FEATURE_USE_LCID
-
-#region Serialization
- // We need to store the override from the culture data record.
- private bool m_useUserOverride;
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
+ private void InitializeFromName(string name, bool useUserOverride)
{
-#if FEATURE_USE_LCID
- // Whidbey+ should remember our name
- // but v1 and v1.1 did not store name -- only lcid
- // Whidbey did not store actual alternate sort name in m_name
- // like we do in v4 so we can't use name for alternate sort
- // e.g. for es-ES_tradnl: v2 puts es-ES in m_name; v4 puts es-ES_tradnl
- if (m_name == null || IsAlternateSortLcid(cultureID))
- {
- Debug.Assert(cultureID >=0, "[CultureInfo.OnDeserialized] cultureID >= 0");
- InitializeFromCultureId(cultureID, m_useUserOverride);
- }
- else
- {
-#endif
- Debug.Assert(m_name != null, "[CultureInfo.OnDeserialized] m_name != null");
-
- this.m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
- if (this.m_cultureData == null)
- throw new CultureNotFoundException(
- nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
-
-#if FEATURE_USE_LCID
- }
-#endif
- m_isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
- }
-
-#if FEATURE_USE_LCID
- // A locale ID is a 32 bit value which is the combination of a
- // language ID, a sort ID, and a reserved area. The bits are
- // allocated as follows:
- //
- // +------------------------+-------+--------------------------------+
- // | Reserved |Sort ID| Language ID |
- // +------------------------+-------+--------------------------------+
- // 31 20 19 16 15 0 bit
- private const int LOCALE_SORTID_MASK = 0x000f0000;
+ // Get our data providing record
+ _cultureData = CultureData.GetCultureData(name, useUserOverride);
- static private bool IsAlternateSortLcid(int lcid)
- {
- if(lcid == LOCALE_TRADITIONAL_SPANISH)
+ if (_cultureData == null)
{
- return true;
+ throw new CultureNotFoundException(nameof(name), name, SR.Argument_CultureNotSupported);
}
- return (lcid & LOCALE_SORTID_MASK) != 0;
- }
-#endif
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
- this.m_name = this.m_cultureData.CultureName;
- this.m_useUserOverride = this.m_cultureData.UseUserOverride;
-#if FEATURE_USE_LCID
- // for compatibility with v2 serialize cultureID
- this.cultureID = this.m_cultureData.ILANGUAGE;
-#endif
+ _name = _cultureData.CultureName;
+ _isInherited = (this.GetType() != typeof(System.Globalization.CultureInfo));
}
-#endregion Serialization
-
// Constructor called by SQL Server's special munged culture - creates a culture with
// a TextInfo and CompareInfo that come from a supplied alternate source. This object
// is ALWAYS read-only.
@@ -441,38 +267,46 @@ namespace System.Globalization {
// the GetCultureInfo override *only*.
internal CultureInfo(String cultureName, String textAndCompareCultureName)
{
- if (cultureName==null) {
- throw new ArgumentNullException(nameof(cultureName),
- Environment.GetResourceString("ArgumentNull_String"));
+ if (cultureName == null)
+ {
+ throw new ArgumentNullException(nameof(cultureName),SR.ArgumentNull_String);
}
Contract.EndContractBlock();
- this.m_cultureData = CultureData.GetCultureData(cultureName, false);
- if (this.m_cultureData == null)
- throw new CultureNotFoundException(
- nameof(cultureName), cultureName, Environment.GetResourceString("Argument_CultureNotSupported"));
+ _cultureData = CultureData.GetCultureData(cultureName, false);
+ if (_cultureData == null)
+ throw new CultureNotFoundException(nameof(cultureName), cultureName, SR.Argument_CultureNotSupported);
- this.m_name = this.m_cultureData.CultureName;
+ _name = _cultureData.CultureName;
CultureInfo altCulture = GetCultureInfo(textAndCompareCultureName);
- this.compareInfo = altCulture.CompareInfo;
- this.textInfo = altCulture.TextInfo;
+ compareInfo = altCulture.CompareInfo;
+ textInfo = altCulture.TextInfo;
}
// We do this to try to return the system UI language and the default user languages
- // The callers should have a fallback if this fails (like Invariant)
+ // This method will fallback if this fails (like Invariant)
+ //
+ // TODO: It would appear that this is only ever called with userOveride = true
+ // and this method only has one caller. Can we fold it into the caller?
private static CultureInfo GetCultureByName(String name, bool userOverride)
- {
+ {
+ CultureInfo ci = null;
// Try to get our culture
try
{
- return userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name);
+ ci = userOverride ? new CultureInfo(name) : CultureInfo.GetCultureInfo(name);
}
catch (ArgumentException)
{
}
- return null;
+ if (ci == null)
+ {
+ ci = InvariantCulture;
+ }
+
+ return ci;
}
//
@@ -483,14 +317,18 @@ namespace System.Globalization {
// if we can't find a bigger name. That doesn't help with things like "zh" though, so
// the approach is of questionable value
//
- public static CultureInfo CreateSpecificCulture(String name) {
+ public static CultureInfo CreateSpecificCulture(String name)
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
CultureInfo culture;
- try {
+ try
+ {
culture = new CultureInfo(name);
- } catch(ArgumentException) {
+ }
+ catch (ArgumentException)
+ {
// When CultureInfo throws this exception, it may be because someone passed the form
// like "az-az" because it came out of an http accept lang. We should try a little
// parsing to perhaps fall back to "az" here and use *it* to create the neutral.
@@ -498,269 +336,160 @@ namespace System.Globalization {
int idx;
culture = null;
- for(idx = 0; idx < name.Length; idx++) {
- if('-' == name[idx]) {
- try {
+ for (idx = 0; idx < name.Length; idx++)
+ {
+ if ('-' == name[idx])
+ {
+ try
+ {
culture = new CultureInfo(name.Substring(0, idx));
break;
- } catch(ArgumentException) {
+ }
+ catch (ArgumentException)
+ {
// throw the original exception so the name in the string will be right
throw;
}
}
}
- if(null == culture) {
+ if (culture == null)
+ {
// nothing to save here; throw the original exception
throw;
}
}
- //In the most common case, they've given us a specific culture, so we'll just return that.
- if (!(culture.IsNeutralCulture)) {
+ // In the most common case, they've given us a specific culture, so we'll just return that.
+ if (!(culture.IsNeutralCulture))
+ {
return culture;
}
- return (new CultureInfo(culture.m_cultureData.SSPECIFICCULTURE));
+ return (new CultureInfo(culture._cultureData.SSPECIFICCULTURE));
}
- internal static bool VerifyCultureName(String cultureName, bool throwException)
+ internal static bool VerifyCultureName(String cultureName, bool throwException)
{
- // This function is used by ResourceManager.GetResourceFileName().
+ // This function is used by ResourceManager.GetResourceFileName().
// ResourceManager searches for resource using CultureInfo.Name,
// so we should check against CultureInfo.Name.
- for (int i=0; i<cultureName.Length; i++) {
+ for (int i = 0; i < cultureName.Length; i++)
+ {
char c = cultureName[i];
-
- if (Char.IsLetterOrDigit(c) || c=='-' || c=='_') {
+ // TODO: Names can only be RFC4646 names (ie: a-zA-Z0-9) while this allows any unicode letter/digit
+ if (Char.IsLetterOrDigit(c) || c == '-' || c == '_')
+ {
continue;
}
- if (throwException) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidResourceCultureName", cultureName));
+ if (throwException)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName));
}
return false;
}
return true;
-
}
- internal static bool VerifyCultureName(CultureInfo culture, bool throwException) {
- Debug.Assert(culture!=null, "[CultureInfo.VerifyCultureName]culture!=null");
-
+ internal static bool VerifyCultureName(CultureInfo culture, bool throwException)
+ {
//If we have an instance of one of our CultureInfos, the user can't have changed the
//name and we know that all names are valid in files.
- if (!culture.m_isInherited) {
+ if (!culture._isInherited)
+ {
return true;
}
return VerifyCultureName(culture.Name, throwException);
-
}
- ////////////////////////////////////////////////////////////////////////
- //
- // CurrentCulture
- //
- // This instance provides methods based on the current user settings.
- // These settings are volatile and may change over the lifetime of the
- // thread.
- //
- ////////////////////////////////////////////////////////////////////////
-
+ // We need to store the override from the culture data record.
+ private bool _useUserOverride;
- public static CultureInfo CurrentCulture
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx)
{
- get {
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
- // In the case of CoreCLR, Thread.m_CurrentCulture and
- // Thread.m_CurrentUICulture are thread static so as not to let
- // CultureInfo objects leak across AppDomain boundaries. The
- // fact that these fields are thread static introduces overhead
- // in accessing them (through Thread.CurrentCulture). There is
- // also overhead in accessing Thread.CurrentThread. In this
- // case, we can avoid the overhead of Thread.CurrentThread
- // because these fields are thread static, and so do not
- // require a Thread instance to be accessed.
-#if FEATURE_APPX
- if(AppDomain.IsAppXModel()) {
- CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
- if (culture != null)
- return culture;
- }
-#endif
- return Thread.m_CurrentCulture ??
- s_DefaultThreadCurrentCulture ??
- s_userDefaultCulture ??
- UserDefaultCulture;
- }
-
- set {
-#if FEATURE_APPX
- if (value == null) {
- throw new ArgumentNullException(nameof(value));
- }
-
- if (AppDomain.IsAppXModel()) {
- if (SetCultureInfoForUserPreferredLanguageInAppX(value)) {
- // successfully set the culture, otherwise fallback to legacy path
- return;
- }
- }
-#endif
- Thread.CurrentThread.CurrentCulture = value;
- }
+ _name = _cultureData.CultureName;
+ _useUserOverride = _cultureData.UseUserOverride;
}
- //
- // This is the equivalence of the Win32 GetUserDefaultLCID()
- //
- internal static CultureInfo UserDefaultCulture {
- get
+ [OnDeserialized]
+ private void OnDeserialized(StreamingContext ctx)
+ {
+ Debug.Assert(_name != null, "[CultureInfo.OnDeserialized] _name != null");
+ InitializeFromName(_name, _useUserOverride);
+ }
+
+ internal static CultureInfo GetCurrentUICultureNoAppX()
+ {
+ CultureInfo ci = GetUserDefaultCultureCacheOverride();
+ if (ci != null)
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
- CultureInfo temp = s_userDefaultCulture;
- if (temp == null)
- {
- //
- // setting the s_userDefaultCulture with invariant culture before intializing it is a protection
- // against recursion problem just in case if somebody called CurrentCulture from the CultureInfo
- // creation path. the recursion can happen if the current user culture is a replaced custom culture.
- //
-
- s_userDefaultCulture = CultureInfo.InvariantCulture;
- temp = InitUserDefaultCulture();
- s_userDefaultCulture = temp;
- }
- return (temp);
+ return ci;
}
- }
- //
- // This is the equivalence of the Win32 GetUserDefaultUILanguage()
- //
- internal static CultureInfo UserDefaultUICulture {
- get {
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
- CultureInfo temp = s_userDefaultUICulture;
- if (temp == null)
- {
- //
- // setting the s_userDefaultCulture with invariant culture before intializing it is a protection
- // against recursion problem just in case if somebody called CurrentUICulture from the CultureInfo
- // creation path. the recursion can happen if the current user culture is a replaced custom culture.
- //
-
- s_userDefaultUICulture = CultureInfo.InvariantCulture;
-
- temp = InitUserDefaultUICulture();
- s_userDefaultUICulture = temp;
- }
- return (temp);
+ if (Thread.m_CurrentUICulture != null)
+ {
+ return Thread.m_CurrentUICulture;
}
- }
+ ci = s_DefaultThreadCurrentUICulture;
+ if (ci != null)
+ {
+ return ci;
+ }
- public static CultureInfo CurrentUICulture {
- get {
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
- // In the case of CoreCLR, Thread.m_CurrentCulture and
- // Thread.m_CurrentUICulture are thread static so as not to let
- // CultureInfo objects leak across AppDomain boundaries. The
- // fact that these fields are thread static introduces overhead
- // in accessing them (through Thread.CurrentCulture). There is
- // also overhead in accessing Thread.CurrentThread. In this
- // case, we can avoid the overhead of Thread.CurrentThread
- // because these fields are thread static, and so do not
- // require a Thread instance to be accessed.
-#if FEATURE_APPX
- if(AppDomain.IsAppXModel()) {
- CultureInfo culture = GetCultureInfoForUserPreferredLanguageInAppX();
- if (culture != null)
- return culture;
- }
-#endif
- return Thread.m_CurrentUICulture ??
- s_DefaultThreadCurrentUICulture ??
- s_userDefaultUICulture ??
- UserDefaultUICulture;
- }
-
- set {
-#if FEATURE_APPX
- if (value == null) {
- throw new ArgumentNullException(nameof(value));
- }
-
- if (AppDomain.IsAppXModel()) {
- if (SetCultureInfoForUserPreferredLanguageInAppX(value)) {
- // successfully set the culture, otherwise fallback to legacy path
- return;
- }
- }
-#endif
- Thread.CurrentThread.CurrentUICulture = value;
+ // 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;
+ }
- //
- // This is the equivalence of the Win32 GetSystemDefaultUILanguage()
- //
- public static CultureInfo InstalledUICulture {
- get {
+ public static CultureInfo InstalledUICulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
- CultureInfo temp = s_InstalledUICultureInfo;
- if (temp == null) {
- String strDefault = GetSystemDefaultUILanguage();
- temp = GetCultureByName(strDefault, true);
-
- if (temp == null)
- {
- temp = InvariantCulture;
- }
-
- temp.m_isReadOnly = true;
- s_InstalledUICultureInfo = temp;
+ if (s_userDefaultCulture == null)
+ {
+ Init();
}
- return (temp);
+ Debug.Assert(s_userDefaultCulture != null, "[CultureInfo.InstalledUICulture] s_userDefaultCulture != null");
+ return s_userDefaultCulture;
}
}
- public static CultureInfo DefaultThreadCurrentCulture {
- get {
- return s_DefaultThreadCurrentCulture;
- }
-
- set {
-
- // If you add pre-conditions to this method, check to see if you also need to
+ public static CultureInfo DefaultThreadCurrentCulture
+ {
+ get { return s_DefaultThreadCurrentCulture; }
+ set
+ {
+ // If you add pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentCulture.set.
s_DefaultThreadCurrentCulture = value;
}
}
- public static CultureInfo DefaultThreadCurrentUICulture {
- get {
- return s_DefaultThreadCurrentUICulture;
- }
-
- set {
-
+ public static CultureInfo DefaultThreadCurrentUICulture
+ {
+ get { return s_DefaultThreadCurrentUICulture; }
+ set
+ {
//If they're trying to use a Culture with a name that we can't use in resource lookup,
//don't even let them set it on the thread.
- // If you add more pre-conditions to this method, check to see if you also need to
+ // If you add more pre-conditions to this method, check to see if you also need to
// add them to Thread.CurrentUICulture.set.
- if (value != null)
- {
+ if (value != null)
+ {
CultureInfo.VerifyCultureName(value, true);
}
@@ -782,10 +511,10 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public static CultureInfo InvariantCulture {
- [Pure]
- get {
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
+ public static CultureInfo InvariantCulture
+ {
+ get
+ {
return (s_InvariantCultureInfo);
}
}
@@ -803,21 +532,19 @@ namespace System.Globalization {
{
get
{
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
- CultureInfo culture = null;
-
- if (null == m_parent)
+ if (null == _parent)
{
try
{
- string parentName = this.m_cultureData.SPARENT;
+ string parentName = _cultureData.SPARENT;
+
if (String.IsNullOrEmpty(parentName))
{
- culture = InvariantCulture;
+ _parent = InvariantCulture;
}
else
{
- culture = new CultureInfo(parentName, this.m_cultureData.UseUserOverride);
+ _parent = new CultureInfo(parentName, _cultureData.UseUserOverride);
}
}
catch (ArgumentException)
@@ -825,58 +552,35 @@ namespace System.Globalization {
// 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.
- culture = InvariantCulture;
+ _parent = InvariantCulture;
}
-
- Interlocked.CompareExchange<CultureInfo>(ref m_parent, culture, null);
}
- return m_parent;
+ return _parent;
}
}
- ////////////////////////////////////////////////////////////////////////
- //
- // LCID
- //
- // Returns a properly formed culture identifier for the current
- // culture info.
- //
- ////////////////////////////////////////////////////////////////////////
-
-#if FEATURE_USE_LCID
- public virtual int LCID {
- get {
- return (this.m_cultureData.ILANGUAGE);
+ public virtual int LCID
+ {
+ get
+ {
+ return (this._cultureData.ILANGUAGE);
}
}
-#endif
- ////////////////////////////////////////////////////////////////////////
- //
- // BaseInputLanguage
- //
- // Essentially an LCID, though one that may be different than LCID in the case
- // of a customized culture (LCID == LOCALE_CUSTOM_UNSPECIFIED).
- //
- ////////////////////////////////////////////////////////////////////////
-#if FEATURE_USE_LCID
public virtual int KeyboardLayoutId
{
get
{
- int keyId = this.m_cultureData.IINPUTLANGUAGEHANDLE;
-
- // Not a customized culture, return the default Keyboard layout ID, which is the same as the language ID.
- return (keyId);
+ return _cultureData.IINPUTLANGUAGEHANDLE;
}
}
-#endif
- public static CultureInfo[] GetCultures(CultureTypes types) {
+ public static CultureInfo[] GetCultures(CultureTypes types)
+ {
Contract.Ensures(Contract.Result<CultureInfo[]>() != null);
// internally we treat UserCustomCultures as Supplementals but v2
// treats as Supplementals and Replacements
- if((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture)
+ if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture)
{
types |= CultureTypes.ReplacementCultures;
}
@@ -891,18 +595,20 @@ namespace System.Globalization {
// "en-US" This version does NOT include sort information in the name.
//
////////////////////////////////////////////////////////////////////////
- public virtual String Name {
- get {
- Contract.Ensures(Contract.Result<String>() != null);
-
+ public virtual String Name
+ {
+ get
+ {
// We return non sorting name here.
- if (this.m_nonSortName == null) {
- this.m_nonSortName = this.m_cultureData.SNAME;
- if (this.m_nonSortName == null) {
- this.m_nonSortName = String.Empty;
+ if (_nonSortName == null)
+ {
+ _nonSortName = _cultureData.SNAME;
+ if (_nonSortName == null)
+ {
+ _nonSortName = String.Empty;
}
}
- return this.m_nonSortName;
+ return _nonSortName;
}
}
@@ -911,20 +617,20 @@ namespace System.Globalization {
{
get
{
- if (this.m_sortName == null)
+ if (_sortName == null)
{
- this.m_sortName = this.m_cultureData.SCOMPAREINFO;
+ _sortName = _cultureData.SCOMPAREINFO;
}
- return this.m_sortName;
+ return _sortName;
}
}
- public String IetfLanguageTag
+ public string IetfLanguageTag
{
get
{
- Contract.Ensures(Contract.Result<String>() != null);
+ Contract.Ensures(Contract.Result<string>() != null);
// special case the compatibility cultures
switch (this.Name)
@@ -953,9 +659,9 @@ namespace System.Globalization {
get
{
Contract.Ensures(Contract.Result<String>() != null);
- Debug.Assert(m_name != null, "[CultureInfo.DisplayName]Always expect m_name to be set");
+ Debug.Assert(_name != null, "[CultureInfo.DisplayName] Always expect _name to be set");
- return m_cultureData.SLOCALIZEDDISPLAYNAME;
+ return _cultureData.SLOCALIZEDDISPLAYNAME;
}
}
@@ -968,10 +674,12 @@ namespace System.Globalization {
// (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
- public virtual String NativeName {
- get {
+ public virtual String NativeName
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
- return (this.m_cultureData.SNATIVEDISPLAYNAME);
+ return (_cultureData.SNATIVEDISPLAYNAME);
}
}
@@ -984,26 +692,32 @@ namespace System.Globalization {
// (United States)" will be returned.
//
////////////////////////////////////////////////////////////////////////
- public virtual String EnglishName {
- get {
+ public virtual String EnglishName
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
- return (this.m_cultureData.SENGDISPLAYNAME);
+ return (_cultureData.SENGDISPLAYNAME);
}
}
-
+
// ie: en
- public virtual String TwoLetterISOLanguageName {
- get {
+ public virtual String TwoLetterISOLanguageName
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
- return (this.m_cultureData.SISO639LANGNAME);
+ return (_cultureData.SISO639LANGNAME);
}
}
// ie: eng
- public virtual String ThreeLetterISOLanguageName {
- get {
+ public virtual String ThreeLetterISOLanguageName
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
- return (this.m_cultureData.SISO639LANGNAME2);
+ return _cultureData.SISO639LANGNAME2;
}
}
@@ -1015,10 +729,12 @@ namespace System.Globalization {
// The ISO names are much preferred
//
////////////////////////////////////////////////////////////////////////
- public virtual String ThreeLetterWindowsLanguageName {
- get {
+ public virtual String ThreeLetterWindowsLanguageName
+ {
+ get
+ {
Contract.Ensures(Contract.Result<String>() != null);
- return (this.m_cultureData.SABBREVLANGNAME);
+ return _cultureData.SABBREVLANGNAME;
}
}
@@ -1033,16 +749,14 @@ namespace System.Globalization {
{
get
{
- Contract.Ensures(Contract.Result<CompareInfo>() != null);
-
if (this.compareInfo == null)
{
// Since CompareInfo's don't have any overrideable properties, get the CompareInfo from
// the Non-Overridden CultureInfo so that we only create one CompareInfo per culture
- CompareInfo temp = UseUserOverride
- ? GetCultureInfo(this.m_name).CompareInfo
+ CompareInfo temp = UseUserOverride
+ ? GetCultureInfo(this._name).CompareInfo
: new CompareInfo(this);
- if (CompatibilitySwitches.IsCompatibilityBehaviorDefined)
+ if (OkayToCacheClassWithCompatibilityBehavior)
{
this.compareInfo = temp;
}
@@ -1055,6 +769,14 @@ namespace System.Globalization {
}
}
+ private static bool OkayToCacheClassWithCompatibilityBehavior
+ {
+ get
+ {
+ return true;
+ }
+ }
+
////////////////////////////////////////////////////////////////////////
//
// TextInfo
@@ -1062,19 +784,17 @@ namespace System.Globalization {
// Gets the TextInfo for this culture.
//
////////////////////////////////////////////////////////////////////////
-
-
- public virtual TextInfo TextInfo {
- get {
- Contract.Ensures(Contract.Result<TextInfo>() != null);
-
- if (textInfo==null)
+ public virtual TextInfo TextInfo
+ {
+ get
+ {
+ if (textInfo == null)
{
// Make a new textInfo
- TextInfo tempTextInfo = new TextInfo(this.m_cultureData);
- tempTextInfo.SetReadOnlyState(m_isReadOnly);
+ TextInfo tempTextInfo = new TextInfo(_cultureData);
+ tempTextInfo.SetReadOnlyState(_isReadOnly);
- if (CompatibilitySwitches.IsCompatibilityBehaviorDefined)
+ if (OkayToCacheClassWithCompatibilityBehavior)
{
textInfo = tempTextInfo;
}
@@ -1144,26 +864,24 @@ namespace System.Globalization {
public override String ToString()
{
- Contract.Ensures(Contract.Result<String>() != null);
-
- Debug.Assert(m_name != null, "[CultureInfo.ToString]Always expect m_name to be set");
- return m_name;
+ return _name;
}
- public virtual Object GetFormat(Type formatType) {
- if (formatType == typeof(NumberFormatInfo)) {
+ public virtual Object GetFormat(Type formatType)
+ {
+ if (formatType == typeof(NumberFormatInfo))
return (NumberFormat);
- }
- if (formatType == typeof(DateTimeFormatInfo)) {
+ if (formatType == typeof(DateTimeFormatInfo))
return (DateTimeFormat);
- }
return (null);
}
- public virtual bool IsNeutralCulture {
- get {
- return this.m_cultureData.IsNeutralCulture;
+ public virtual bool IsNeutralCulture
+ {
+ get
+ {
+ return _cultureData.IsNeutralCulture;
}
}
@@ -1173,43 +891,43 @@ namespace System.Globalization {
{
CultureTypes types = 0;
- if (m_cultureData.IsNeutralCulture)
+ if (_cultureData.IsNeutralCulture)
types |= CultureTypes.NeutralCultures;
- else
+ else
types |= CultureTypes.SpecificCultures;
- types |= m_cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0;
+ types |= _cultureData.IsWin32Installed ? CultureTypes.InstalledWin32Cultures : 0;
-// Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
+ // Disable warning 618: System.Globalization.CultureTypes.FrameworkCultures' is obsolete
#pragma warning disable 618
- types |= m_cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
-#pragma warning restore 618
+ types |= _cultureData.IsFramework ? CultureTypes.FrameworkCultures : 0;
- types |= m_cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
- types |= m_cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
+#pragma warning restore 618
+ types |= _cultureData.IsSupplementalCustomCulture ? CultureTypes.UserCustomCulture : 0;
+ types |= _cultureData.IsReplacementCulture ? CultureTypes.ReplacementCultures | CultureTypes.UserCustomCulture : 0;
return types;
}
}
- public virtual NumberFormatInfo NumberFormat {
- get
+ public virtual NumberFormatInfo NumberFormat
+ {
+ get
{
- Contract.Ensures(Contract.Result<NumberFormatInfo>() != null);
-
- if (numInfo == null) {
- NumberFormatInfo temp = new NumberFormatInfo(this.m_cultureData);
- temp.isReadOnly = m_isReadOnly;
+ if (numInfo == null)
+ {
+ NumberFormatInfo temp = new NumberFormatInfo(_cultureData);
+ temp.isReadOnly = _isReadOnly;
Interlocked.CompareExchange(ref numInfo, temp, null);
}
return (numInfo);
}
- set {
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Obj"));
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
VerifyWritable();
numInfo = value;
}
@@ -1223,44 +941,40 @@ namespace System.Globalization {
// the CultureID.
//
////////////////////////////////////////////////////////////////////////
-
-
- public virtual DateTimeFormatInfo DateTimeFormat {
- get {
- Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
-
- if (dateTimeInfo == null) {
+ public virtual DateTimeFormatInfo DateTimeFormat
+ {
+ get
+ {
+ if (dateTimeInfo == null)
+ {
// Change the calendar of DTFI to the specified calendar of this CultureInfo.
- DateTimeFormatInfo temp = new DateTimeFormatInfo(
- this.m_cultureData, this.Calendar);
- temp.m_isReadOnly = m_isReadOnly;
+ DateTimeFormatInfo temp = new DateTimeFormatInfo(_cultureData, this.Calendar);
+ temp._isReadOnly = _isReadOnly;
Interlocked.CompareExchange(ref dateTimeInfo, temp, null);
}
return (dateTimeInfo);
}
- set {
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Obj"));
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException(nameof(value), SR.ArgumentNull_Obj);
}
- Contract.EndContractBlock();
VerifyWritable();
dateTimeInfo = value;
}
}
- public void ClearCachedData() {
- s_userDefaultUICulture = null;
+ public void ClearCachedData()
+ {
s_userDefaultCulture = null;
RegionInfo.s_currentRegionInfo = null;
-#pragma warning disable CS0618
+ #pragma warning disable 0618 // disable the obsolete warning
TimeZone.ResetTimeZone();
-#pragma warning restore CS0618
+ #pragma warning restore 0618
TimeZoneInfo.ClearCachedData();
-
- // Delete the cached cultures.
s_LcidCachedCultures = null;
s_NameCachedCultures = null;
@@ -1275,8 +989,10 @@ namespace System.Globalization {
** Shouldn't throw exception since the calType value is from our data table or from Win32 registry.
** If we are in trouble (like getting a weird value from Win32 registry), just return the GregorianCalendar.
============================================================================*/
- internal static Calendar GetCalendarInstance(int calType) {
- if (calType==Calendar.CAL_GREGORIAN) {
+ internal static Calendar GetCalendarInstance(CalendarId calType)
+ {
+ if (calType == CalendarId.GREGORIAN)
+ {
return (new GregorianCalendar());
}
return GetCalendarInstanceRare(calType);
@@ -1284,45 +1000,38 @@ namespace System.Globalization {
//This function exists as a shortcut to prevent us from loading all of the non-gregorian
//calendars unless they're required.
- internal static Calendar GetCalendarInstanceRare(int calType) {
- Debug.Assert(calType!=Calendar.CAL_GREGORIAN, "calType!=Calendar.CAL_GREGORIAN");
-
- switch (calType) {
- case Calendar.CAL_GREGORIAN_US: // Gregorian (U.S.) calendar
- case Calendar.CAL_GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar
- case Calendar.CAL_GREGORIAN_ARABIC: // Gregorian Arabic calendar
- case Calendar.CAL_GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar
- case Calendar.CAL_GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar
+ internal static Calendar GetCalendarInstanceRare(CalendarId calType)
+ {
+ Debug.Assert(calType != CalendarId.GREGORIAN, "calType!=CalendarId.GREGORIAN");
+
+ switch (calType)
+ {
+ case CalendarId.GREGORIAN_US: // Gregorian (U.S.) calendar
+ case CalendarId.GREGORIAN_ME_FRENCH: // Gregorian Middle East French calendar
+ case CalendarId.GREGORIAN_ARABIC: // Gregorian Arabic calendar
+ case CalendarId.GREGORIAN_XLIT_ENGLISH: // Gregorian Transliterated English calendar
+ case CalendarId.GREGORIAN_XLIT_FRENCH: // Gregorian Transliterated French calendar
return (new GregorianCalendar((GregorianCalendarTypes)calType));
- case Calendar.CAL_TAIWAN: // Taiwan Era calendar
+ case CalendarId.TAIWAN: // Taiwan Era calendar
return (new TaiwanCalendar());
- case Calendar.CAL_JAPAN: // Japanese Emperor Era calendar
+ case CalendarId.JAPAN: // Japanese Emperor Era calendar
return (new JapaneseCalendar());
- case Calendar.CAL_KOREA: // Korean Tangun Era calendar
+ case CalendarId.KOREA: // Korean Tangun Era calendar
return (new KoreanCalendar());
- case Calendar.CAL_THAI: // Thai calendar
+ case CalendarId.THAI: // Thai calendar
return (new ThaiBuddhistCalendar());
- case Calendar.CAL_HIJRI: // Hijri (Arabic Lunar) calendar
+ case CalendarId.HIJRI: // Hijri (Arabic Lunar) calendar
return (new HijriCalendar());
- case Calendar.CAL_HEBREW: // Hebrew (Lunar) calendar
+ case CalendarId.HEBREW: // Hebrew (Lunar) calendar
return (new HebrewCalendar());
- case Calendar.CAL_UMALQURA:
+ case CalendarId.UMALQURA:
return (new UmAlQuraCalendar());
- case Calendar.CAL_PERSIAN:
+ case CalendarId.PERSIAN:
return (new PersianCalendar());
- case Calendar.CAL_CHINESELUNISOLAR:
- return (new ChineseLunisolarCalendar());
- case Calendar.CAL_JAPANESELUNISOLAR:
- return (new JapaneseLunisolarCalendar());
- case Calendar.CAL_KOREANLUNISOLAR:
- return (new KoreanLunisolarCalendar());
- case Calendar.CAL_TAIWANLUNISOLAR:
- return (new TaiwanLunisolarCalendar());
}
return (new GregorianCalendar());
}
-
/*=================================Calendar==========================
**Action: Return/set the default calendar used by this culture.
** This value can be overridden by regional option if this is a current culture.
@@ -1331,19 +1040,19 @@ namespace System.Globalization {
**Exceptions:
** ArgumentNull_Obj if the set value is null.
============================================================================*/
-
-
- public virtual Calendar Calendar {
- get {
- Contract.Ensures(Contract.Result<Calendar>() != null);
- if (calendar == null) {
- Debug.Assert(this.m_cultureData.CalendarIds.Length > 0, "this.m_cultureData.CalendarIds.Length > 0");
+ public virtual Calendar Calendar
+ {
+ get
+ {
+ if (calendar == null)
+ {
+ Debug.Assert(_cultureData.CalendarIds.Length > 0, "_cultureData.CalendarIds.Length > 0");
// Get the default calendar for this culture. Note that the value can be
// from registry if this is a user default culture.
- Calendar newObj = this.m_cultureData.DefaultCalendar;
+ Calendar newObj = _cultureData.DefaultCalendar;
- System.Threading.Thread.MemoryBarrier();
- newObj.SetReadOnlyState(m_isReadOnly);
+ System.Threading.Interlocked.MemoryBarrier();
+ newObj.SetReadOnlyState(_isReadOnly);
calendar = newObj;
}
return (calendar);
@@ -1358,26 +1067,30 @@ namespace System.Globalization {
============================================================================*/
- public virtual Calendar[] OptionalCalendars {
- get {
+ public virtual Calendar[] OptionalCalendars
+ {
+ get
+ {
Contract.Ensures(Contract.Result<Calendar[]>() != null);
//
// This property always returns a new copy of the calendar array.
//
- int[] calID = this.m_cultureData.CalendarIds;
- Calendar [] cals = new Calendar[calID.Length];
- for (int i = 0; i < cals.Length; i++) {
+ CalendarId[] calID = _cultureData.CalendarIds;
+ Calendar[] cals = new Calendar[calID.Length];
+ for (int i = 0; i < cals.Length; i++)
+ {
cals[i] = GetCalendarInstance(calID[i]);
}
return (cals);
}
}
-
- public bool UseUserOverride {
- get {
- return (this.m_cultureData.UseUserOverride);
+ public bool UseUserOverride
+ {
+ get
+ {
+ return _cultureData.UseUserOverride;
}
}
@@ -1385,26 +1098,24 @@ namespace System.Globalization {
{
Contract.Ensures(Contract.Result<CultureInfo>() != null);
- CultureInfo temp = m_consoleFallbackCulture;
+ CultureInfo temp = _consoleFallbackCulture;
if (temp == null)
{
- temp = CreateSpecificCulture(this.m_cultureData.SCONSOLEFALLBACKNAME);
- temp.m_isReadOnly = true;
- m_consoleFallbackCulture = temp;
+ temp = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME);
+ _isReadOnly = true;
+ _consoleFallbackCulture = temp;
}
return (temp);
}
public virtual Object Clone()
{
- Contract.Ensures(Contract.Result<Object>() != null);
-
CultureInfo ci = (CultureInfo)MemberwiseClone();
- ci.m_isReadOnly = false;
+ ci._isReadOnly = false;
//If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
//they've already been allocated. If this is a derived type, we'll take a more generic codepath.
- if (!m_isInherited)
+ if (!_isInherited)
{
if (this.dateTimeInfo != null)
{
@@ -1414,36 +1125,37 @@ namespace System.Globalization {
{
ci.numInfo = (NumberFormatInfo)this.numInfo.Clone();
}
-
}
else
{
ci.DateTimeFormat = (DateTimeFormatInfo)this.DateTimeFormat.Clone();
- ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone();
+ ci.NumberFormat = (NumberFormatInfo)this.NumberFormat.Clone();
}
if (textInfo != null)
{
- ci.textInfo = (TextInfo) textInfo.Clone();
+ ci.textInfo = (TextInfo)textInfo.Clone();
}
if (calendar != null)
{
- ci.calendar = (Calendar) calendar.Clone();
+ ci.calendar = (Calendar)calendar.Clone();
}
return (ci);
}
-
- public static CultureInfo ReadOnly(CultureInfo ci) {
- if (ci == null) {
+ public static CultureInfo ReadOnly(CultureInfo ci)
+ {
+ if (ci == null)
+ {
throw new ArgumentNullException(nameof(ci));
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
- if (ci.IsReadOnly) {
+ if (ci.IsReadOnly)
+ {
return (ci);
}
CultureInfo newInfo = (CultureInfo)(ci.MemberwiseClone());
@@ -1452,20 +1164,24 @@ namespace System.Globalization {
{
//If this is exactly our type, we can make certain optimizations so that we don't allocate NumberFormatInfo or DTFI unless
//they've already been allocated. If this is a derived type, we'll take a more generic codepath.
- if (!ci.m_isInherited) {
- if (ci.dateTimeInfo != null) {
+ if (!ci._isInherited)
+ {
+ if (ci.dateTimeInfo != null)
+ {
newInfo.dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci.dateTimeInfo);
}
- if (ci.numInfo != null) {
+ if (ci.numInfo != null)
+ {
newInfo.numInfo = NumberFormatInfo.ReadOnly(ci.numInfo);
}
-
- } else {
+ }
+ else
+ {
newInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat);
newInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat);
}
}
-
+
if (ci.textInfo != null)
{
newInfo.textInfo = TextInfo.ReadOnly(ci.textInfo);
@@ -1478,23 +1194,26 @@ namespace System.Globalization {
// Don't set the read-only flag too early.
// We should set the read-only flag here. Otherwise, info.DateTimeFormat will not be able to set.
- newInfo.m_isReadOnly = true;
+ newInfo._isReadOnly = true;
return (newInfo);
}
- public bool IsReadOnly {
- get {
- return (m_isReadOnly);
+ public bool IsReadOnly
+ {
+ get
+ {
+ return (_isReadOnly);
}
}
- private void VerifyWritable() {
- if (m_isReadOnly) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ private void VerifyWritable()
+ {
+ if (_isReadOnly)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- Contract.EndContractBlock();
}
// For resource lookup, we consider a culture the invariant culture by name equality.
@@ -1509,24 +1228,17 @@ namespace System.Globalization {
// If lcid is -1, use the altName and create one of those special SQL cultures.
internal static CultureInfo GetCultureInfoHelper(int lcid, string name, string altName)
{
- // There is a race condition in this code with the side effect that the second thread's value
- // clobbers the first in the dictionary. This is an acceptable race condition since the CultureInfo objects
- // are content equal (but not reference equal). Since we make no guarantees there, this race condition is
- // acceptable.
- // See code:Dictionary#DictionaryVersusHashtableThreadSafety for details on Dictionary versus
- // Hashtable thread safety.
-
// retval is our return value.
CultureInfo retval;
// Temporary hashtable for the names.
- Hashtable tempNameHT = s_NameCachedCultures;
+ StringCultureInfoDictionary tempNameHT = s_NameCachedCultures;
if (name != null)
{
name = CultureData.AnsiToLower(name);
}
-
+
if (altName != null)
{
altName = CultureData.AnsiToLower(altName);
@@ -1535,55 +1247,56 @@ namespace System.Globalization {
// We expect the same result for both hashtables, but will test individually for added safety.
if (tempNameHT == null)
{
- tempNameHT = Hashtable.Synchronized(new Hashtable());
+ tempNameHT = new StringCultureInfoDictionary();
}
else
{
// If we are called by name, check if the object exists in the hashtable. If so, return it.
- if (lcid == -1)
+ if (lcid == -1 || lcid == 0)
{
- retval = (CultureInfo)tempNameHT[name + '\xfffd' + altName];
- if (retval != null)
+ bool ret;
+ lock (_lock)
{
- return retval;
+ ret = tempNameHT.TryGetValue(lcid == 0 ? name : name + '\xfffd' + altName, out retval);
}
- }
- else if (lcid == 0)
- {
- retval = (CultureInfo)tempNameHT[name];
- if (retval != null)
+
+ if (ret && retval != null)
{
return retval;
}
}
}
-#if FEATURE_USE_LCID
+
// Next, the Lcid table.
- Hashtable tempLcidHT = s_LcidCachedCultures;
+ StringLcidDictionary tempLcidHT = s_LcidCachedCultures;
if (tempLcidHT == null)
{
// Case insensitive is not an issue here, save the constructor call.
- tempLcidHT = Hashtable.Synchronized(new Hashtable());
+ tempLcidHT = new StringLcidDictionary();
}
else
{
// If we were called by Lcid, check if the object exists in the table. If so, return it.
if (lcid > 0)
{
- retval = (CultureInfo) tempLcidHT[lcid];
- if (retval != null)
+ bool ret;
+ lock (_lock)
+ {
+ ret = tempLcidHT.TryGetValue(lcid, out retval);
+ }
+ if (ret && retval != null)
{
return retval;
}
}
}
-#endif
+
// We now have two temporary hashtables and the desired object was not found.
// We'll construct it. We catch any exceptions from the constructor call and return null.
try
{
- switch(lcid)
+ switch (lcid)
{
case -1:
// call the private constructor
@@ -1595,65 +1308,55 @@ namespace System.Globalization {
break;
default:
-#if FEATURE_USE_LCID
retval = new CultureInfo(lcid, false);
break;
-#else
- return null;
-#endif
}
}
- catch(ArgumentException)
+ catch (ArgumentException)
{
return null;
}
// Set it to read-only
- retval.m_isReadOnly = true;
+ retval._isReadOnly = true;
if (lcid == -1)
{
- // This new culture will be added only to the name hash table.
- tempNameHT[name + '\xfffd' + altName] = retval;
-
+ lock (_lock)
+ {
+ // This new culture will be added only to the name hash table.
+ tempNameHT[name + '\xfffd' + altName] = retval;
+ }
// when lcid == -1 then TextInfo object is already get created and we need to set it as read only.
retval.TextInfo.SetReadOnlyState(true);
}
- else
+ else if (lcid == 0)
{
// Remember our name (as constructed). Do NOT use alternate sort name versions because
// we have internal state representing the sort. (So someone would get the wrong cached version)
- string newName = CultureData.AnsiToLower(retval.m_name);
-
- // We add this new culture info object to both tables.
- tempNameHT[newName] = retval;
-#if FEATURE_USE_LCID
- const int LCID_ZH_CHS_HANS = 0x0004;
- const int LCID_ZH_CHT_HANT = 0x7c04;
+ string newName = CultureData.AnsiToLower(retval._name);
- if ((retval.LCID == LCID_ZH_CHS_HANS && newName == "zh-hans")
- || (retval.LCID == LCID_ZH_CHT_HANT && newName == "zh-hant"))
+ // We add this new culture info object to both tables.
+ lock (_lock)
{
- // do nothing because we only want zh-CHS and zh-CHT to cache
- // by lcid
+ tempNameHT[newName] = retval;
}
- else
+ }
+ else
+ {
+ lock (_lock)
{
- tempLcidHT[retval.LCID] = retval;
+ tempLcidHT[lcid] = retval;
}
-
-#endif
}
-#if FEATURE_USE_LCID
// Copy the two hashtables to the corresponding member variables. This will potentially overwrite
// new tables simultaneously created by a new thread, but maximizes thread safety.
- if(-1 != lcid)
+ if (-1 != lcid)
{
// Only when we modify the lcid hash table, is there a need to overwrite.
s_LcidCachedCultures = tempLcidHT;
}
-#endif
s_NameCachedCultures = tempNameHT;
@@ -1661,7 +1364,6 @@ namespace System.Globalization {
return retval;
}
-#if FEATURE_USE_LCID
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found). (LCID version)... use named version
public static CultureInfo GetCultureInfo(int culture)
@@ -1669,21 +1371,19 @@ namespace System.Globalization {
// Must check for -1 now since the helper function uses the value to signal
// the altCulture code path for SQL Server.
// Also check for zero as this would fail trying to add as a key to the hash.
- if (culture <= 0) {
- throw new ArgumentOutOfRangeException(nameof(culture),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ if (culture <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(culture), SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(culture, null, null);
if (null == retval)
{
- throw new CultureNotFoundException(
- nameof(culture), culture, Environment.GetResourceString("Argument_CultureNotSupported"));
+ throw new CultureNotFoundException(nameof(culture), culture, SR.Argument_CultureNotSupported);
}
return retval;
}
-#endif
// Gets a cached copy of the specified culture from an internal hashtable (or creates it
// if not found). (Named version)
@@ -1694,15 +1394,12 @@ namespace System.Globalization {
{
throw new ArgumentNullException(nameof(name));
}
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
- Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(0, name, null);
if (retval == null)
{
throw new CultureNotFoundException(
- nameof(name), name, Environment.GetResourceString("Argument_CultureNotSupported"));
-
+ nameof(name), name, SR.Argument_CultureNotSupported);
}
return retval;
}
@@ -1712,32 +1409,28 @@ namespace System.Globalization {
public static CultureInfo GetCultureInfo(string name, string altName)
{
// Make sure we have a valid, non-zero length string as name
- if (null == name)
+ if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
- if (null == altName)
+ if (altName == null)
{
throw new ArgumentNullException(nameof(altName));
}
+
Contract.Ensures(Contract.Result<CultureInfo>() != null);
Contract.EndContractBlock();
CultureInfo retval = GetCultureInfoHelper(-1, name, altName);
if (retval == null)
{
- throw new CultureNotFoundException(nameof(name) + " or " + nameof(altName),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_OneOfCulturesNotSupported"),
- name,
- altName));
+ throw new CultureNotFoundException("name or altName",
+ SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName));
}
return retval;
}
-
// This function is deprecated, we don't like it
public static CultureInfo GetCultureInfoByIetfLanguageTag(string name)
{
@@ -1746,105 +1439,19 @@ namespace System.Globalization {
// Disallow old zh-CHT/zh-CHS names
if (name == "zh-CHT" || name == "zh-CHS")
{
- throw new CultureNotFoundException(
- nameof(name),
- String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
- );
+ throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name));
}
-
+
CultureInfo ci = GetCultureInfo(name);
// Disallow alt sorts and es-es_TS
if (ci.LCID > 0xffff || ci.LCID == 0x040a)
{
- throw new CultureNotFoundException(
- nameof(name),
- String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_CultureIetfNotSupported"), name)
- );
+ throw new CultureNotFoundException(nameof(name), SR.Format(SR.Argument_CultureIetfNotSupported, name));
}
-
- return ci;
- }
-
- private static volatile bool s_isTaiwanSku;
- private static volatile bool s_haveIsTaiwanSku;
- internal static bool IsTaiwanSku
- {
- get
- {
- if (!s_haveIsTaiwanSku)
- {
- s_isTaiwanSku = (GetSystemDefaultUILanguage() == "zh-TW");
- s_haveIsTaiwanSku = true;
- }
- return (bool)s_isTaiwanSku;
- }
- }
-
- //
- // Helper Methods.
- //
-
- // Get Locale Info Ex calls. So we don't have to muck with the different int/string return types we declared two of these:
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String nativeGetLocaleInfoEx(String localeName, uint field);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern int nativeGetLocaleInfoExInt(String localeName, uint field);
-
- private static String GetDefaultLocaleName(int localeType)
- {
- Debug.Assert(localeType == LOCALE_USER_DEFAULT || localeType == LOCALE_SYSTEM_DEFAULT, "[CultureInfo.GetDefaultLocaleName] localeType must be LOCALE_USER_DEFAULT or LOCALE_SYSTEM_DEFAULT");
-
- string localeName = null;
- if(InternalGetDefaultLocaleName(localeType, JitHelpers.GetStringHandleOnStack(ref localeName)))
- {
- return localeName;
- }
- return string.Empty;
- }
-
- // Get the default locale name
- [SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool InternalGetDefaultLocaleName(int localetype, StringHandleOnStack localeString);
-
- private static String GetUserDefaultUILanguage()
- {
- string userDefaultUiLanguage = null;
- if(InternalGetUserDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref userDefaultUiLanguage)))
- {
- return userDefaultUiLanguage;
- }
- return String.Empty;
- }
-
- // Get the user's default UI language, return locale name
- [SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool InternalGetUserDefaultUILanguage(StringHandleOnStack userDefaultUiLanguage);
-
- private static String GetSystemDefaultUILanguage()
- {
- string systemDefaultUiLanguage = null;
- if(InternalGetSystemDefaultUILanguage(JitHelpers.GetStringHandleOnStack(ref systemDefaultUiLanguage)))
- {
- return systemDefaultUiLanguage;
- }
- return String.Empty;
+ return ci;
}
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- [SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static extern bool InternalGetSystemDefaultUILanguage(StringHandleOnStack systemDefaultUiLanguage);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String[] nativeGetResourceFallbackArray();
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs b/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
deleted file mode 100644
index d4ab700a16..0000000000
--- a/src/mscorlib/src/System/Globalization/CultureNotFoundException.cs
+++ /dev/null
@@ -1,129 +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.
-
-
-namespace System.Globalization {
-
- using System;
- using System.Runtime.Serialization;
- using System.Threading;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- public partial class CultureNotFoundException : ArgumentException, ISerializable
- {
- private string m_invalidCultureName; // unrecognized culture name
- private Nullable<int> m_invalidCultureId; // unrecognized culture Lcid
-
- public CultureNotFoundException()
- : base(DefaultMessage)
- {
- }
-
- public CultureNotFoundException(String message)
- : base(message)
- {
- }
-
- public CultureNotFoundException(String paramName, String message)
- : base(message, paramName)
- {
- }
-
- public CultureNotFoundException(String message, Exception innerException)
- : base(message, innerException)
- {
- }
-
- public CultureNotFoundException(String paramName, int invalidCultureId, String message)
- : base(message, paramName)
- {
- m_invalidCultureId = invalidCultureId;
- }
-
- public CultureNotFoundException(String message, int invalidCultureId, Exception innerException)
- : base(message, innerException)
- {
- m_invalidCultureId = invalidCultureId;
- }
-
- public CultureNotFoundException(String paramName, string invalidCultureName, String message)
- : base(message, paramName)
- {
- m_invalidCultureName = invalidCultureName;
- }
-
- public CultureNotFoundException(String message, string invalidCultureName, Exception innerException)
- : base(message, innerException)
- {
- m_invalidCultureName = invalidCultureName;
- }
-
- protected CultureNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
- m_invalidCultureId = (Nullable<int>) info.GetValue("InvalidCultureId", typeof(Nullable<int>));
- m_invalidCultureName = (string) info.GetValue("InvalidCultureName", typeof(string));
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- base.GetObjectData(info, context);
- Nullable<int> invalidCultureId = null;
- invalidCultureId = m_invalidCultureId;
- info.AddValue("InvalidCultureId", invalidCultureId, typeof(Nullable<int>));
- info.AddValue("InvalidCultureName", m_invalidCultureName, typeof(string));
- }
- public virtual Nullable<int> InvalidCultureId
- {
- get { return m_invalidCultureId; }
- }
-
- public virtual string InvalidCultureName
- {
- get { return m_invalidCultureName; }
- }
-
- private static String DefaultMessage
- {
- get
- {
- return Environment.GetResourceString("Argument_CultureNotSupported");
- }
- }
-
- private String FormatedInvalidCultureId
- {
- get
- {
- if (InvalidCultureId != null)
- {
- return String.Format(CultureInfo.InvariantCulture,
- "{0} (0x{0:x4})", (int)InvalidCultureId);
- }
- return InvalidCultureName;
- }
- }
-
- public override String Message
- {
- get
- {
- String s = base.Message;
- if (
- m_invalidCultureId != null ||
- m_invalidCultureName != null)
- {
- String valueMessage = Environment.GetResourceString("Argument_CultureInvalidIdentifier", FormatedInvalidCultureId);
- if (s == null)
- return valueMessage;
- return s + Environment.NewLine + valueMessage;
- }
- return s;
- }
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/CultureTypes.cs b/src/mscorlib/src/System/Globalization/CultureTypes.cs
deleted file mode 100644
index b19ab86bb1..0000000000
--- a/src/mscorlib/src/System/Globalization/CultureTypes.cs
+++ /dev/null
@@ -1,30 +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.
-
-//
-// The enumeration constants used in CultureInfo.GetCultures().
-//
-// Note that this isn't exposed in Silverlight
-namespace System.Globalization {
-
-
-[Serializable]
- [Flags]
- public enum CultureTypes
- {
- NeutralCultures = 0x0001, // Neutral cultures are cultures like "en", "de", "zh", etc, for enumeration this includes ALL neutrals regardless of other flags
- SpecificCultures = 0x0002, // Non-netural cultuers. Examples are "en-us", "zh-tw", etc., for enumeration this includes ALL specifics regardless of other flags
- InstalledWin32Cultures = 0x0004, // Win32 installed cultures in the system and exists in the framework too., this is effectively all cultures
-
- AllCultures = NeutralCultures | SpecificCultures | InstalledWin32Cultures,
-
- UserCustomCulture = 0x0008, // User defined custom culture
- ReplacementCultures = 0x0010, // User defined replacement custom culture.
- [Obsolete("This value has been deprecated. Please use other values in CultureTypes.")]
- WindowsOnlyCultures = 0x0020, // this will always return empty list.
- [Obsolete("This value has been deprecated. Please use other values in CultureTypes.")]
- FrameworkCultures = 0x0040, // will return only the v2 cultures marked as Framework culture.
- }
-
-}
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs b/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
deleted file mode 100644
index 1ace207952..0000000000
--- a/src/mscorlib/src/System/Globalization/DateTimeFormat.cs
+++ /dev/null
@@ -1,1130 +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.
-
-namespace System {
- using System.Text;
- using System.Threading;
- using System.Globalization;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- /*
- Customized format patterns:
- P.S. Format in the table below is the internal number format used to display the pattern.
-
- Patterns Format Description Example
- ========= ========== ===================================== ========
- "h" "0" hour (12-hour clock)w/o leading zero 3
- "hh" "00" hour (12-hour clock)with leading zero 03
- "hh*" "00" hour (12-hour clock)with leading zero 03
-
- "H" "0" hour (24-hour clock)w/o leading zero 8
- "HH" "00" hour (24-hour clock)with leading zero 08
- "HH*" "00" hour (24-hour clock) 08
-
- "m" "0" minute w/o leading zero
- "mm" "00" minute with leading zero
- "mm*" "00" minute with leading zero
-
- "s" "0" second w/o leading zero
- "ss" "00" second with leading zero
- "ss*" "00" second with leading zero
-
- "f" "0" second fraction (1 digit)
- "ff" "00" second fraction (2 digit)
- "fff" "000" second fraction (3 digit)
- "ffff" "0000" second fraction (4 digit)
- "fffff" "00000" second fraction (5 digit)
- "ffffff" "000000" second fraction (6 digit)
- "fffffff" "0000000" second fraction (7 digit)
-
- "F" "0" second fraction (up to 1 digit)
- "FF" "00" second fraction (up to 2 digit)
- "FFF" "000" second fraction (up to 3 digit)
- "FFFF" "0000" second fraction (up to 4 digit)
- "FFFFF" "00000" second fraction (up to 5 digit)
- "FFFFFF" "000000" second fraction (up to 6 digit)
- "FFFFFFF" "0000000" second fraction (up to 7 digit)
-
- "t" first character of AM/PM designator A
- "tt" AM/PM designator AM
- "tt*" AM/PM designator PM
-
- "d" "0" day w/o leading zero 1
- "dd" "00" day with leading zero 01
- "ddd" short weekday name (abbreviation) Mon
- "dddd" full weekday name Monday
- "dddd*" full weekday name Monday
-
-
- "M" "0" month w/o leading zero 2
- "MM" "00" month with leading zero 02
- "MMM" short month name (abbreviation) Feb
- "MMMM" full month name Febuary
- "MMMM*" full month name Febuary
-
- "y" "0" two digit year (year % 100) w/o leading zero 0
- "yy" "00" two digit year (year % 100) with leading zero 00
- "yyy" "D3" year 2000
- "yyyy" "D4" year 2000
- "yyyyy" "D5" year 2000
- ...
-
- "z" "+0;-0" timezone offset w/o leading zero -8
- "zz" "+00;-00" timezone offset with leading zero -08
- "zzz" "+00;-00" for hour offset, "00" for minute offset full timezone offset -07:30
- "zzz*" "+00;-00" for hour offset, "00" for minute offset full timezone offset -08:00
-
- "K" -Local "zzz", e.g. -08:00
- -Utc "'Z'", representing UTC
- -Unspecified ""
- -DateTimeOffset "zzzzz" e.g -07:30:15
-
- "g*" the current era name A.D.
-
- ":" time separator : -- DEPRECATED - Insert separator directly into pattern (eg: "H.mm.ss")
- "/" date separator /-- DEPRECATED - Insert separator directly into pattern (eg: "M-dd-yyyy")
- "'" quoted string 'ABC' will insert ABC into the formatted string.
- '"' quoted string "ABC" will insert ABC into the formatted string.
- "%" used to quote a single pattern characters E.g.The format character "%y" is to print two digit year.
- "\" escaped character E.g. '\d' insert the character 'd' into the format string.
- other characters insert the character into the format string.
-
- Pre-defined format characters:
- (U) to indicate Universal time is used.
- (G) to indicate Gregorian calendar is used.
-
- Format Description Real format Example
- ========= ================================= ====================== =======================
- "d" short date culture-specific 10/31/1999
- "D" long data culture-specific Sunday, October 31, 1999
- "f" full date (long date + short time) culture-specific Sunday, October 31, 1999 2:00 AM
- "F" full date (long date + long time) culture-specific Sunday, October 31, 1999 2:00:00 AM
- "g" general date (short date + short time) culture-specific 10/31/1999 2:00 AM
- "G" general date (short date + long time) culture-specific 10/31/1999 2:00:00 AM
- "m"/"M" Month/Day date culture-specific October 31
-(G) "o"/"O" Round Trip XML "yyyy-MM-ddTHH:mm:ss.fffffffK" 1999-10-31 02:00:00.0000000Z
-(G) "r"/"R" RFC 1123 date, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" Sun, 31 Oct 1999 10:00:00 GMT
-(G) "s" Sortable format, based on ISO 8601. "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
- ('T' for local time)
- "t" short time culture-specific 2:00 AM
- "T" long time culture-specific 2:00:00 AM
-(G) "u" Universal time with sortable format, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'" 1999-10-31 10:00:00Z
- based on ISO 8601.
-(U) "U" Universal time with full culture-specific Sunday, October 31, 1999 10:00:00 AM
- (long date + long time) format
- "y"/"Y" Year/Month day culture-specific October, 1999
-
- */
-
- //This class contains only static members and does not require the serializable attribute.
- internal static
- class DateTimeFormat {
-
- internal const int MaxSecondsFractionDigits = 7;
- internal static readonly TimeSpan NullOffset = TimeSpan.MinValue;
-
- internal static char[] allStandardFormats =
- {
- 'd', 'D', 'f', 'F', 'g', 'G',
- 'm', 'M', 'o', 'O', 'r', 'R',
- 's', 't', 'T', 'u', 'U', 'y', 'Y',
- };
-
- internal const String RoundtripFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK";
- internal const String RoundtripDateTimeUnfixed = "yyyy'-'MM'-'ddTHH':'mm':'ss zzz";
-
- private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
-
- internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat;
- internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames;
- internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames;
- internal const string Gmt = "GMT";
-
- internal static String[] fixedNumberFormats = new String[] {
- "0",
- "00",
- "000",
- "0000",
- "00000",
- "000000",
- "0000000",
- };
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Format the positive integer value to a string and perfix with assigned
- // length of leading zero.
- //
- // Parameters:
- // value: The value to format
- // len: The maximum length for leading zero.
- // If the digits of the value is greater than len, no leading zero is added.
- //
- // Notes:
- // The function can format to Int32.MaxValue.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) {
- Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
- FormatDigits(outputBuffer, value, len, false);
- }
-
- internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) {
- Debug.Assert(value >= 0, "DateTimeFormat.FormatDigits(): value >= 0");
-
- // Limit the use of this function to be two-digits, so that we have the same behavior
- // as RTM bits.
- if (!overrideLengthLimit && len > 2)
- {
- len = 2;
- }
-
- char* buffer = stackalloc char[16];
- char* p = buffer + 16;
- int n = value;
- do {
- *--p = (char)(n % 10 + '0');
- n /= 10;
- } while ((n != 0)&&(p > buffer));
-
- int digits = (int) (buffer + 16 - p);
-
- //If the repeat count is greater than 0, we're trying
- //to emulate the "00" format, so we have to prepend
- //a zero if the string only has one character.
- while ((digits < len) && (p > buffer)) {
- *--p='0';
- digits++;
- }
- outputBuffer.Append(p, digits);
- }
-
- private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) {
- outputBuffer.Append(HebrewNumber.ToString(digits));
- }
-
- internal static int ParseRepeatPattern(String format, int pos, char patternChar)
- {
- int len = format.Length;
- int index = pos + 1;
- while ((index < len) && (format[index] == patternChar))
- {
- index++;
- }
- return (index - pos);
- }
-
- private static String FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi)
- {
- Debug.Assert(dayOfWeek >= 0 && dayOfWeek <= 6, "dayOfWeek >= 0 && dayOfWeek <= 6");
- if (repeat == 3)
- {
- return (dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek));
- }
- // Call dtfi.GetDayName() here, instead of accessing DayNames property, because we don't
- // want a clone of DayNames, which will hurt perf.
- return (dtfi.GetDayName((DayOfWeek)dayOfWeek));
- }
-
- private static String FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi)
- {
- Debug.Assert(month >=1 && month <= 12, "month >=1 && month <= 12");
- if (repeatCount == 3)
- {
- return (dtfi.GetAbbreviatedMonthName(month));
- }
- // Call GetMonthName() here, instead of accessing MonthNames property, because we don't
- // want a clone of MonthNames, which will hurt perf.
- return (dtfi.GetMonthName(month));
- }
-
- //
- // FormatHebrewMonthName
- //
- // Action: Return the Hebrew month name for the specified DateTime.
- // Returns: The month name string for the specified DateTime.
- // Arguments:
- // time the time to format
- // month The month is the value of HebrewCalendar.GetMonth(time).
- // repeat Return abbreviated month name if repeat=3, or full month name if repeat=4
- // dtfi The DateTimeFormatInfo which uses the Hebrew calendars as its calendar.
- // Exceptions: None.
- //
-
- /* Note:
- If DTFI is using Hebrew calendar, GetMonthName()/GetAbbreviatedMonthName() will return month names like this:
- 1 Hebrew 1st Month
- 2 Hebrew 2nd Month
- .. ...
- 6 Hebrew 6th Month
- 7 Hebrew 6th Month II (used only in a leap year)
- 8 Hebrew 7th Month
- 9 Hebrew 8th Month
- 10 Hebrew 9th Month
- 11 Hebrew 10th Month
- 12 Hebrew 11th Month
- 13 Hebrew 12th Month
-
- Therefore, if we are in a regular year, we have to increment the month name if moth is greater or eqaul to 7.
- */
- private static String FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi)
- {
- Debug.Assert(repeatCount != 3 || repeatCount != 4, "repeateCount should be 3 or 4");
- if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) {
- // This month is in a leap year
- return (dtfi.internalGetMonthName(month, MonthNameStyles.LeapYear, (repeatCount == 3)));
- }
- // This is in a regular year.
- if (month >= 7) {
- month++;
- }
- if (repeatCount == 3) {
- return (dtfi.GetAbbreviatedMonthName(month));
- }
- return (dtfi.GetMonthName(month));
- }
-
- //
- // The pos should point to a quote character. This method will
- // append to the result StringBuilder the string encloed by the quote character.
- //
- internal static int ParseQuoteString(String format, int pos, StringBuilder result)
- {
- //
- // NOTE : pos will be the index of the quote character in the 'format' string.
- //
- int formatLen = format.Length;
- int beginPos = pos;
- char quoteChar = format[pos++]; // Get the character used to quote the following string.
-
- bool foundQuote = false;
- while (pos < formatLen)
- {
- char ch = format[pos++];
- if (ch == quoteChar)
- {
- foundQuote = true;
- break;
- }
- else if (ch == '\\') {
- // The following are used to support escaped character.
- // Escaped character is also supported in the quoted string.
- // Therefore, someone can use a format like "'minute:' mm\"" to display:
- // minute: 45"
- // because the second double quote is escaped.
- if (pos < formatLen) {
- result.Append(format[pos++]);
- } else {
- //
- // This means that '\' is at the end of the formatting string.
- //
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
- } else {
- result.Append(ch);
- }
- }
-
- if (!foundQuote)
- {
- // Here we can't find the matching quote.
- throw new FormatException(
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("Format_BadQuote"), quoteChar));
- }
-
- //
- // Return the character count including the begin/end quote characters and enclosed string.
- //
- return (pos - beginPos);
- }
-
- //
- // Get the next character at the index of 'pos' in the 'format' string.
- // Return value of -1 means 'pos' is already at the end of the 'format' string.
- // Otherwise, return value is the int value of the next character.
- //
- internal static int ParseNextChar(String format, int pos)
- {
- if (pos >= format.Length - 1)
- {
- return (-1);
- }
- return ((int)format[pos+1]);
- }
-
- //
- // IsUseGenitiveForm
- //
- // Actions: Check the format to see if we should use genitive month in the formatting.
- // Starting at the position (index) in the (format) string, look back and look ahead to
- // see if there is "d" or "dd". In the case like "d MMMM" or "MMMM dd", we can use
- // genitive form. Genitive form is not used if there is more than two "d".
- // Arguments:
- // format The format string to be scanned.
- // index Where we should start the scanning. This is generally where "M" starts.
- // tokenLen The len of the current pattern character. This indicates how many "M" that we have.
- // patternToMatch The pattern that we want to search. This generally uses "d"
- //
- private static bool IsUseGenitiveForm(String format, int index, int tokenLen, char patternToMatch) {
- int i;
- int repeat = 0;
- //
- // Look back to see if we can find "d" or "ddd"
- //
-
- // Find first "d".
- for (i = index - 1; i >= 0 && format[i] != patternToMatch; i--) { /*Do nothing here */ };
-
- if (i >= 0) {
- // Find a "d", so look back to see how many "d" that we can find.
- while (--i >= 0 && format[i] == patternToMatch) {
- repeat++;
- }
- //
- // repeat == 0 means that we have one (patternToMatch)
- // repeat == 1 means that we have two (patternToMatch)
- //
- if (repeat <= 1) {
- return (true);
- }
- // Note that we can't just stop here. We may find "ddd" while looking back, and we have to look
- // ahead to see if there is "d" or "dd".
- }
-
- //
- // If we can't find "d" or "dd" by looking back, try look ahead.
- //
-
- // Find first "d"
- for (i = index + tokenLen; i < format.Length && format[i] != patternToMatch; i++) { /* Do nothing here */ };
-
- if (i < format.Length) {
- repeat = 0;
- // Find a "d", so contine the walk to see how may "d" that we can find.
- while (++i < format.Length && format[i] == patternToMatch) {
- repeat++;
- }
- //
- // repeat == 0 means that we have one (patternToMatch)
- // repeat == 1 means that we have two (patternToMatch)
- //
- if (repeat <= 1) {
- return (true);
- }
- }
- return (false);
- }
-
-
- //
- // FormatCustomized
- //
- // Actions: Format the DateTime instance using the specified format.
- //
- private static String FormatCustomized(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset) {
-
-
- Calendar cal = dtfi.Calendar;
- StringBuilder result = StringBuilderCache.Acquire();
- // This is a flag to indicate if we are format the dates using Hebrew calendar.
-
- bool isHebrewCalendar = (cal.ID == Calendar.CAL_HEBREW);
- // This is a flag to indicate if we are formating hour/minute/second only.
- bool bTimeOnly = true;
-
- int i = 0;
- int tokenLen, hour12;
-
- while (i < format.Length) {
- char ch = format[i];
- int nextChar;
- switch (ch) {
- case 'g':
- tokenLen = ParseRepeatPattern(format, i, ch);
- result.Append(dtfi.GetEraName(cal.GetEra(dateTime)));
- break;
- case 'h':
- tokenLen = ParseRepeatPattern(format, i, ch);
- hour12 = dateTime.Hour % 12;
- if (hour12 == 0)
- {
- hour12 = 12;
- }
- FormatDigits(result, hour12, tokenLen);
- break;
- case 'H':
- tokenLen = ParseRepeatPattern(format, i, ch);
- FormatDigits(result, dateTime.Hour, tokenLen);
- break;
- case 'm':
- tokenLen = ParseRepeatPattern(format, i, ch);
- FormatDigits(result, dateTime.Minute, tokenLen);
- break;
- case 's':
- tokenLen = ParseRepeatPattern(format, i, ch);
- FormatDigits(result, dateTime.Second, tokenLen);
- break;
- case 'f':
- case 'F':
- tokenLen = ParseRepeatPattern(format, i, ch);
- if (tokenLen <= MaxSecondsFractionDigits) {
- long fraction = (dateTime.Ticks % Calendar.TicksPerSecond);
- fraction = fraction / (long)Math.Pow(10, 7 - tokenLen);
- if (ch == 'f') {
- result.Append(((int)fraction).ToString(fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
- }
- else {
- int effectiveDigits = tokenLen;
- while (effectiveDigits > 0) {
- if (fraction % 10 == 0) {
- fraction = fraction / 10;
- effectiveDigits--;
- }
- else {
- break;
- }
- }
- if (effectiveDigits > 0) {
- result.Append(((int)fraction).ToString(fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
- }
- else {
- // No fraction to emit, so see if we should remove decimal also.
- if (result.Length > 0 && result[result.Length - 1] == '.') {
- result.Remove(result.Length - 1, 1);
- }
- }
- }
- } else {
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
- break;
- case 't':
- tokenLen = ParseRepeatPattern(format, i, ch);
- if (tokenLen == 1)
- {
- if (dateTime.Hour < 12)
- {
- if (dtfi.AMDesignator.Length >= 1)
- {
- result.Append(dtfi.AMDesignator[0]);
- }
- }
- else
- {
- if (dtfi.PMDesignator.Length >= 1)
- {
- result.Append(dtfi.PMDesignator[0]);
- }
- }
-
- }
- else
- {
- result.Append((dateTime.Hour < 12 ? dtfi.AMDesignator : dtfi.PMDesignator));
- }
- break;
- case 'd':
- //
- // tokenLen == 1 : Day of month as digits with no leading zero.
- // tokenLen == 2 : Day of month as digits with leading zero for single-digit months.
- // tokenLen == 3 : Day of week as a three-leter abbreviation.
- // tokenLen >= 4 : Day of week as its full name.
- //
- tokenLen = ParseRepeatPattern(format, i, ch);
- if (tokenLen <= 2)
- {
- int day = cal.GetDayOfMonth(dateTime);
- if (isHebrewCalendar) {
- // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
- HebrewFormatDigits(result, day);
- } else {
- FormatDigits(result, day, tokenLen);
- }
- }
- else
- {
- int dayOfWeek = (int)cal.GetDayOfWeek(dateTime);
- result.Append(FormatDayOfWeek(dayOfWeek, tokenLen, dtfi));
- }
- bTimeOnly = false;
- break;
- case 'M':
- //
- // tokenLen == 1 : Month as digits with no leading zero.
- // tokenLen == 2 : Month as digits with leading zero for single-digit months.
- // tokenLen == 3 : Month as a three-letter abbreviation.
- // tokenLen >= 4 : Month as its full name.
- //
- tokenLen = ParseRepeatPattern(format, i, ch);
- int month = cal.GetMonth(dateTime);
- if (tokenLen <= 2)
- {
- if (isHebrewCalendar) {
- // For Hebrew calendar, we need to convert numbers to Hebrew text for yyyy, MM, and dd values.
- HebrewFormatDigits(result, month);
- } else {
- FormatDigits(result, month, tokenLen);
- }
- }
- else {
- if (isHebrewCalendar) {
- result.Append(FormatHebrewMonthName(dateTime, month, tokenLen, dtfi));
- } else {
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0 && tokenLen >= 4) {
- result.Append(
- dtfi.internalGetMonthName(
- month,
- IsUseGenitiveForm(format, i, tokenLen, 'd')? MonthNameStyles.Genitive : MonthNameStyles.Regular,
- false));
- } else {
- result.Append(FormatMonth(month, tokenLen, dtfi));
- }
- }
- }
- bTimeOnly = false;
- break;
- case 'y':
- // Notes about OS behavior:
- // y: Always print (year % 100). No leading zero.
- // yy: Always print (year % 100) with leading zero.
- // yyy/yyyy/yyyyy/... : Print year value. No leading zero.
-
- int year = cal.GetYear(dateTime);
- tokenLen = ParseRepeatPattern(format, i, ch);
- if (dtfi.HasForceTwoDigitYears) {
- FormatDigits(result, year, tokenLen <= 2 ? tokenLen : 2);
- }
- else if (cal.ID == Calendar.CAL_HEBREW) {
- HebrewFormatDigits(result, year);
- }
- else {
- if (tokenLen <= 2) {
- FormatDigits(result, year % 100, tokenLen);
- }
- else {
- String fmtPattern = "D" + tokenLen.ToString();
- result.Append(year.ToString(fmtPattern, CultureInfo.InvariantCulture));
- }
- }
- bTimeOnly = false;
- break;
- case 'z':
- tokenLen = ParseRepeatPattern(format, i, ch);
- FormatCustomizedTimeZone(dateTime, offset, format, tokenLen, bTimeOnly, result);
- break;
- case 'K':
- tokenLen = 1;
- FormatCustomizedRoundripTimeZone(dateTime, offset, result);
- break;
- case ':':
- result.Append(dtfi.TimeSeparator);
- tokenLen = 1;
- break;
- case '/':
- result.Append(dtfi.DateSeparator);
- tokenLen = 1;
- break;
- case '\'':
- case '\"':
- tokenLen = ParseQuoteString(format, i, result);
- break;
- case '%':
- // Optional format character.
- // For example, format string "%d" will print day of month
- // without leading zero. Most of the cases, "%" can be ignored.
- nextChar = ParseNextChar(format, i);
- // nextChar will be -1 if we already reach the end of the format string.
- // Besides, we will not allow "%%" appear in the pattern.
- if (nextChar >= 0 && nextChar != (int)'%') {
- result.Append(FormatCustomized(dateTime, ((char)nextChar).ToString(), dtfi, offset));
- tokenLen = 2;
- }
- else
- {
- //
- // This means that '%' is at the end of the format string or
- // "%%" appears in the format string.
- //
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
- break;
- case '\\':
- // Escaped character. Can be used to insert character into the format string.
- // For exmple, "\d" will insert the character 'd' into the string.
- //
- // NOTENOTE : we can remove this format character if we enforce the enforced quote
- // character rule.
- // That is, we ask everyone to use single quote or double quote to insert characters,
- // then we can remove this character.
- //
- nextChar = ParseNextChar(format, i);
- if (nextChar >= 0)
- {
- result.Append(((char)nextChar));
- tokenLen = 2;
- }
- else
- {
- //
- // This means that '\' is at the end of the formatting string.
- //
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
- break;
- default:
- // NOTENOTE : we can remove this rule if we enforce the enforced quote
- // character rule.
- // That is, if we ask everyone to use single quote or double quote to insert characters,
- // then we can remove this default block.
- result.Append(ch);
- tokenLen = 1;
- break;
- }
- i += tokenLen;
- }
- return StringBuilderCache.GetStringAndRelease(result);
-
- }
-
-
- // output the 'z' famliy of formats, which output a the offset from UTC, e.g. "-07:30"
- private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, String format, Int32 tokenLen, Boolean timeOnly, StringBuilder result) {
- // See if the instance already has an offset
- Boolean dateTimeFormat = (offset == NullOffset);
- if (dateTimeFormat) {
- // No offset. The instance is a DateTime and the output should be the local time zone
-
- if (timeOnly && dateTime.Ticks < Calendar.TicksPerDay) {
- // For time only format and a time only input, the time offset on 0001/01/01 is less
- // accurate than the system's current offset because of daylight saving time.
- offset = TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- } else if (dateTime.Kind == DateTimeKind.Utc) {
- offset = TimeSpan.Zero;
- } else {
- offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
- }
- if (offset >= TimeSpan.Zero) {
- result.Append('+');
- }
- else {
- result.Append('-');
- // get a positive offset, so that you don't need a separate code path for the negative numbers.
- offset = offset.Negate();
- }
-
- if (tokenLen <= 1) {
- // 'z' format e.g "-7"
- result.AppendFormat(CultureInfo.InvariantCulture, "{0:0}", offset.Hours);
- }
- else {
- // 'zz' or longer format e.g "-07"
- result.AppendFormat(CultureInfo.InvariantCulture, "{0:00}", offset.Hours);
- if (tokenLen >= 3) {
- // 'zzz*' or longer format e.g "-07:30"
- result.AppendFormat(CultureInfo.InvariantCulture, ":{0:00}", offset.Minutes);
- }
- }
- }
-
- // output the 'K' format, which is for round-tripping the data
- private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) {
-
- // The objective of this format is to round trip the data in the type
- // For DateTime it should round-trip the Kind value and preserve the time zone.
- // DateTimeOffset instance, it should do so by using the internal time zone.
-
- if (offset == NullOffset) {
- // source is a date time, so behavior depends on the kind.
- switch (dateTime.Kind) {
- case DateTimeKind.Local:
- // This should output the local offset, e.g. "-07:30"
- offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- // fall through to shared time zone output code
- break;
- case DateTimeKind.Utc:
- // The 'Z' constant is a marker for a UTC date
- result.Append("Z");
- return;
- default:
- // If the kind is unspecified, we output nothing here
- return;
- }
- }
- if (offset >= TimeSpan.Zero) {
- result.Append('+');
- }
- else {
- result.Append('-');
- // get a positive offset, so that you don't need a separate code path for the negative numbers.
- offset = offset.Negate();
- }
-
- AppendNumber(result, offset.Hours, 2);
- result.Append(':');
- AppendNumber(result, offset.Minutes, 2);
- }
-
-
- internal static String GetRealFormat(String format, DateTimeFormatInfo dtfi)
- {
- String realFormat = null;
-
- switch (format[0])
- {
- case 'd': // Short Date
- realFormat = dtfi.ShortDatePattern;
- break;
- case 'D': // Long Date
- realFormat = dtfi.LongDatePattern;
- break;
- case 'f': // Full (long date + short time)
- realFormat = dtfi.LongDatePattern + " " + dtfi.ShortTimePattern;
- break;
- case 'F': // Full (long date + long time)
- realFormat = dtfi.FullDateTimePattern;
- break;
- case 'g': // General (short date + short time)
- realFormat = dtfi.GeneralShortTimePattern;
- break;
- case 'G': // General (short date + long time)
- realFormat = dtfi.GeneralLongTimePattern;
- break;
- case 'm':
- case 'M': // Month/Day Date
- realFormat = dtfi.MonthDayPattern;
- break;
- case 'o':
- case 'O':
- realFormat = RoundtripFormat;
- break;
- case 'r':
- case 'R': // RFC 1123 Standard
- realFormat = dtfi.RFC1123Pattern;
- break;
- case 's': // Sortable without Time Zone Info
- realFormat = dtfi.SortableDateTimePattern;
- break;
- case 't': // Short Time
- realFormat = dtfi.ShortTimePattern;
- break;
- case 'T': // Long Time
- realFormat = dtfi.LongTimePattern;
- break;
- case 'u': // Universal with Sortable format
- realFormat = dtfi.UniversalSortableDateTimePattern;
- break;
- case 'U': // Universal with Full (long date + long time) format
- realFormat = dtfi.FullDateTimePattern;
- break;
- case 'y':
- case 'Y': // Year/Month Date
- realFormat = dtfi.YearMonthPattern;
- break;
- default:
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
- return (realFormat);
- }
-
-
- // Expand a pre-defined format string (like "D" for long date) to the real format that
- // we are going to use in the date time parsing.
- // This method also convert the dateTime if necessary (e.g. when the format is in Universal time),
- // and change dtfi if necessary (e.g. when the format should use invariant culture).
- //
- private static String ExpandPredefinedFormat(String format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, ref TimeSpan offset) {
- switch (format[0]) {
- case 'o':
- case 'O': // Round trip format
- dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- case 'r':
- case 'R': // RFC 1123 Standard
- if (offset != NullOffset) {
- // Convert to UTC invariants mean this will be in range
- dateTime = dateTime - offset;
- }
- else if (dateTime.Kind == DateTimeKind.Local) {
- InvalidFormatForLocal(format, dateTime);
- }
- dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- case 's': // Sortable without Time Zone Info
- dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- case 'u': // Universal time in sortable format.
- if (offset != NullOffset) {
- // Convert to UTC invariants mean this will be in range
- dateTime = dateTime - offset;
- }
- else if (dateTime.Kind == DateTimeKind.Local) {
-
- InvalidFormatForLocal(format, dateTime);
- }
- dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- case 'U': // Universal time in culture dependent format.
- if (offset != NullOffset) {
- // This format is not supported by DateTimeOffset
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
- // Universal time is always in Greogrian calendar.
- //
- // Change the Calendar to be Gregorian Calendar.
- //
- dtfi = (DateTimeFormatInfo)dtfi.Clone();
- if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) {
- dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
- }
- dateTime = dateTime.ToUniversalTime();
- break;
- }
- format = GetRealFormat(format, dtfi);
- return (format);
- }
-
- internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi) {
- return Format(dateTime, format, dtfi, NullOffset);
- }
-
-
- internal static String Format(DateTime dateTime, String format, DateTimeFormatInfo dtfi, TimeSpan offset)
- {
- Contract.Requires(dtfi != null);
- if (format==null || format.Length==0) {
- Boolean timeOnlySpecialCase = false;
- if (dateTime.Ticks < Calendar.TicksPerDay) {
- // If the time is less than 1 day, consider it as time of day.
- // Just print out the short time format.
- //
- // This is a workaround for VB, since they use ticks less then one day to be
- // time of day. In cultures which use calendar other than Gregorian calendar, these
- // alternative calendar may not support ticks less than a day.
- // For example, Japanese calendar only supports date after 1868/9/8.
- // This will pose a problem when people in VB get the time of day, and use it
- // to call ToString(), which will use the general format (short date + long time).
- // Since Japanese calendar does not support Gregorian year 0001, an exception will be
- // thrown when we try to get the Japanese year for Gregorian year 0001.
- // Therefore, the workaround allows them to call ToString() for time of day from a DateTime by
- // formatting as ISO 8601 format.
- switch (dtfi.Calendar.ID) {
- case Calendar.CAL_JAPAN:
- case Calendar.CAL_TAIWAN:
- case Calendar.CAL_HIJRI:
- case Calendar.CAL_HEBREW:
- case Calendar.CAL_JULIAN:
- case Calendar.CAL_UMALQURA:
- case Calendar.CAL_PERSIAN:
- timeOnlySpecialCase = true;
- dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- }
- }
- if (offset == NullOffset) {
- // Default DateTime.ToString case.
- if (timeOnlySpecialCase) {
- format = "s";
- }
- else {
- format = "G";
- }
- }
- else {
- // Default DateTimeOffset.ToString case.
- if (timeOnlySpecialCase) {
- format = RoundtripDateTimeUnfixed;
- }
- else {
- format = dtfi.DateTimeOffsetPattern;
- }
-
- }
-
- }
-
- if (format.Length == 1) {
- switch (format[0])
- {
- case 'O':
- case 'o':
- return FastFormatRoundtrip(dateTime, offset);
- case 'R':
- case 'r':
- return FastFormatRfc1123(dateTime, offset, dtfi);
- }
-
- format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, ref offset);
- }
-
- return (FormatCustomized(dateTime, format, dtfi, offset));
- }
-
- internal static string FastFormatRfc1123(DateTime dateTime, TimeSpan offset, DateTimeFormatInfo dtfi)
- {
- // ddd, dd MMM yyyy HH:mm:ss GMT
- const int Rfc1123FormatLength = 29;
- StringBuilder result = StringBuilderCache.Acquire(Rfc1123FormatLength);
-
- if (offset != NullOffset)
- {
- // Convert to UTC invariants
- dateTime = dateTime - offset;
- }
-
- result.Append(InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]);
- result.Append(',');
- result.Append(' ');
- AppendNumber(result, dateTime.Day, 2);
- result.Append(' ');
- result.Append(InvariantAbbreviatedMonthNames[dateTime.Month - 1]);
- result.Append(' ');
- AppendNumber(result, dateTime.Year, 4);
- result.Append(' ');
- AppendHHmmssTimeOfDay(result, dateTime);
- result.Append(' ');
- result.Append(Gmt);
-
- return StringBuilderCache.GetStringAndRelease(result);
- }
-
- internal static string FastFormatRoundtrip(DateTime dateTime, TimeSpan offset)
- {
- // yyyy-MM-ddTHH:mm:ss.fffffffK
- const int roundTripFormatLength = 28;
- StringBuilder result = StringBuilderCache.Acquire(roundTripFormatLength);
-
- AppendNumber(result, dateTime.Year, 4);
- result.Append('-');
- AppendNumber(result, dateTime.Month, 2);
- result.Append('-');
- AppendNumber(result, dateTime.Day, 2);
- result.Append('T');
- AppendHHmmssTimeOfDay(result, dateTime);
- result.Append('.');
-
- long fraction = dateTime.Ticks % TimeSpan.TicksPerSecond;
- AppendNumber(result, fraction, 7);
-
- FormatCustomizedRoundripTimeZone(dateTime, offset, result);
-
- return StringBuilderCache.GetStringAndRelease(result);
- }
-
- private static void AppendHHmmssTimeOfDay(StringBuilder result, DateTime dateTime)
- {
- // HH:mm:ss
- AppendNumber(result, dateTime.Hour, 2);
- result.Append(':');
- AppendNumber(result, dateTime.Minute, 2);
- result.Append(':');
- AppendNumber(result, dateTime.Second, 2);
- }
-
- internal static void AppendNumber(StringBuilder builder, long val, int digits)
- {
- for (int i = 0; i < digits; i++)
- {
- builder.Append('0');
- }
-
- int index = 1;
- while (val > 0 && index <= digits)
- {
- builder[builder.Length - index] = (char)('0' + (val % 10));
- val = val / 10;
- index++;
- }
-
- Debug.Assert(val == 0, "DateTimeFormat.AppendNumber(): digits less than size of val");
- }
-
- internal static String[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi)
- {
- Contract.Requires(dtfi != null);
- String [] allFormats = null;
- String [] results = null;
-
- switch (format)
- {
- case 'd':
- case 'D':
- case 'f':
- case 'F':
- case 'g':
- case 'G':
- case 'm':
- case 'M':
- case 't':
- case 'T':
- case 'y':
- case 'Y':
- allFormats = dtfi.GetAllDateTimePatterns(format);
- results = new String[allFormats.Length];
- for (int i = 0; i < allFormats.Length; i++)
- {
- results[i] = Format(dateTime, allFormats[i], dtfi);
- }
- break;
- case 'U':
- DateTime universalTime = dateTime.ToUniversalTime();
- allFormats = dtfi.GetAllDateTimePatterns(format);
- results = new String[allFormats.Length];
- for (int i = 0; i < allFormats.Length; i++)
- {
- results[i] = Format(universalTime, allFormats[i], dtfi);
- }
- break;
- //
- // The following ones are special cases because these patterns are read-only in
- // DateTimeFormatInfo.
- //
- case 'r':
- case 'R':
- case 'o':
- case 'O':
- case 's':
- case 'u':
- results = new String[] {Format(dateTime, new String(format, 1), dtfi)};
- break;
- default:
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
-
- }
- return (results);
- }
-
- internal static String[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi)
- {
- List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE);
-
- for (int i = 0; i < allStandardFormats.Length; i++)
- {
- String[] strings = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi);
- for (int j = 0; j < strings.Length; j++)
- {
- results.Add(strings[j]);
- }
- }
- String[] value = new String[results.Count];
- results.CopyTo(0, value, 0, results.Count);
- return (value);
- }
-
- // This is a placeholder for an MDA to detect when the user is using a
- // local DateTime with a format that will be interpreted as UTC.
- internal static void InvalidFormatForLocal(String format, DateTime dateTime) {
- }
-
-
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
deleted file mode 100644
index b2374ef0b2..0000000000
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfo.cs
+++ /dev/null
@@ -1,2858 +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.
-
-
-namespace System.Globalization {
- using System;
- using System.Security;
- using System.Threading;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Text;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- //
- // Flags used to indicate different styles of month names.
- // This is an internal flag used by internalGetMonthName().
- // Use flag here in case that we need to provide a combination of these styles
- // (such as month name of a leap year in genitive form. Not likely for now,
- // but would like to keep the option open).
- //
-
- [Flags]
- internal enum MonthNameStyles {
- Regular = 0x00000000,
- Genitive = 0x00000001,
- LeapYear = 0x00000002,
- }
-
- //
- // Flags used to indicate special rule used in parsing/formatting
- // for a specific DateTimeFormatInfo instance.
- // 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
- // or alternative month names, etc.
-
- [Flags]
- internal enum DateTimeFormatFlags {
- None = 0x00000000,
- UseGenitiveMonth = 0x00000001,
- UseLeapYearMonth = 0x00000002,
- UseSpacesInMonthNames = 0x00000004, // Has spaces or non-breaking space in the month names.
- UseHebrewRule = 0x00000008, // Format/Parse using the Hebrew calendar rule.
- UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names.
- UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers.
-
- NotInitialized = -1,
- }
-
-
- [Serializable]
- public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
- {
- //
- // Note, some fields are derived so don't really need to be serialized, but we can't mark as
- // optional because Whidbey was expecting them. Post-Arrowhead we could fix that
- // once Whidbey serialization is no longer necessary.
- //
-
- // cache for the invariant culture.
- // invariantInfo is constant irrespective of your current culture.
- private static volatile DateTimeFormatInfo invariantInfo;
-
- // an index which points to a record in Culture Data Table.
- [NonSerialized]private CultureData m_cultureData;
-
- // The culture name used to create this DTFI.
- [OptionalField(VersionAdded = 2)]
- internal String m_name = null;
-
- // The language name of the culture used to create this DTFI.
- [NonSerialized]private String m_langName = null;
-
- // CompareInfo usually used by the parser.
- [NonSerialized]private CompareInfo m_compareInfo = null;
-
- // Culture matches current DTFI. mainly used for string comparisons during parsing.
- [NonSerialized]private CultureInfo m_cultureInfo = null;
-
- //
- // Caches for various properties.
- //
-
- internal String amDesignator = null;
- internal String pmDesignator = null;
- [OptionalField(VersionAdded = 1)]
- internal String dateSeparator = null; // derived from short date (whidbey expects, arrowhead doesn't)
- [OptionalField(VersionAdded = 1)]
- internal String generalShortTimePattern = null; // short date + short time (whidbey expects, arrowhead doesn't)
- [OptionalField(VersionAdded = 1)]
- internal String generalLongTimePattern = null; // short date + long time (whidbey expects, arrowhead doesn't)
- [OptionalField(VersionAdded = 1)]
- internal String timeSeparator = null; // derived from long time (whidbey expects, arrowhead doesn't)
- internal String monthDayPattern = null;
- [OptionalField(VersionAdded = 2)] // added in .NET Framework Release {2.0SP1/3.0SP1/3.5RTM}
- internal String dateTimeOffsetPattern = null;
-
- //
- // The following are constant values.
- //
- internal const String rfc1123Pattern = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'";
-
- // The sortable pattern is based on ISO 8601.
- internal const String sortableDateTimePattern = "yyyy'-'MM'-'dd'T'HH':'mm':'ss";
- internal const String universalSortableDateTimePattern = "yyyy'-'MM'-'dd HH':'mm':'ss'Z'";
-
- //
- // The following are affected by calendar settings.
- //
- internal Calendar calendar = null;
-
- internal int firstDayOfWeek = -1;
- internal int calendarWeekRule = -1;
-
- [OptionalField(VersionAdded = 1)]
- internal String fullDateTimePattern = null; // long date + long time (whidbey expects, arrowhead doesn't)
-
- internal String[] abbreviatedDayNames = null;
-
- [OptionalField(VersionAdded = 2)]
- internal String[] m_superShortDayNames = null;
-
- internal String[] dayNames = null;
- internal String[] abbreviatedMonthNames = null;
- internal String[] monthNames = null;
- // Cache the genitive month names that we retrieve from the data table.
- [OptionalField(VersionAdded = 2)]
- internal String[] genitiveMonthNames = null;
-
- // Cache the abbreviated genitive month names that we retrieve from the data table.
- [OptionalField(VersionAdded = 2)]
- internal String[] m_genitiveAbbreviatedMonthNames = null;
-
- // Cache the month names of a leap year that we retrieve from the data table.
- [OptionalField(VersionAdded = 2)]
- internal String[] leapYearMonthNames = null;
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
-
- // The "default" Date/time patterns
- internal String longDatePattern = null;
- internal String shortDatePattern = null;
- internal String yearMonthPattern = null;
- internal String longTimePattern = null;
- internal String shortTimePattern = null;
-
- // These are Whidbey-serialization compatable arrays (eg: default not included)
- // "all" is a bit of a misnomer since the "default" pattern stored above isn't
- // necessarily a member of the list
- [OptionalField(VersionAdded = 3)]
- private String[] allYearMonthPatterns = null; // This was wasn't serialized in Whidbey
- internal String[] allShortDatePatterns = null;
- internal String[] allLongDatePatterns = null;
- internal String[] allShortTimePatterns = null;
- internal String[] allLongTimePatterns = null;
-
- // Cache the era names for this DateTimeFormatInfo instance.
- internal String[] m_eraNames = null;
- internal String[] m_abbrevEraNames = null;
- internal String[] m_abbrevEnglishEraNames = null;
-
- internal int[] optionalCalendars = null;
-
- private const int DEFAULT_ALL_DATETIMES_SIZE = 132;
-
- // CultureInfo updates this
- internal bool m_isReadOnly=false;
-
- // This flag gives hints about if formatting/parsing should perform special code path for things like
- // genitive form or leap year month names.
- [OptionalField(VersionAdded = 2)]
- internal DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized;
-
- private String CultureName
- {
- get
- {
- if (m_name == null)
- {
- m_name = this.m_cultureData.CultureName;
- }
- return (m_name);
- }
- }
-
- private CultureInfo Culture
- {
- get
- {
- if (m_cultureInfo == null)
- {
- m_cultureInfo = CultureInfo.GetCultureInfo(this.CultureName);
- }
- return m_cultureInfo;
- }
- }
-
- private String LanguageName
- {
- get
- {
- if (m_langName == null)
- {
- m_langName = this.m_cultureData.SISO639LANGNAME;
- }
- return (m_langName);
- }
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Create an array of string which contains the abbreviated day names.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- private String[] internalGetAbbreviatedDayOfWeekNames()
- {
- if (this.abbreviatedDayNames == null)
- {
- // Get the abbreviated day names for our current calendar
- this.abbreviatedDayNames = this.m_cultureData.AbbreviatedDayNames(Calendar.ID);
- Debug.Assert(this.abbreviatedDayNames.Length == 7, "[DateTimeFormatInfo.GetAbbreviatedDayOfWeekNames] Expected 7 day names in a week");
- }
- return (this.abbreviatedDayNames);
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Action: Returns the string array of the one-letter day of week names.
- // Returns:
- // an array of one-letter day of week names
- // Arguments:
- // None
- // Exceptions:
- // None
- //
- ////////////////////////////////////////////////////////////////////////
-
- private String[] internalGetSuperShortDayNames()
- {
- if (this.m_superShortDayNames == null)
- {
- // Get the super short day names for our current calendar
- this.m_superShortDayNames = this.m_cultureData.SuperShortDayNames(Calendar.ID);
- Debug.Assert(this.m_superShortDayNames.Length == 7, "[DateTimeFormatInfo.internalGetSuperShortDayNames] Expected 7 day names in a week");
- }
- return (this.m_superShortDayNames);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Create an array of string which contains the day names.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- private String[] internalGetDayOfWeekNames()
- {
- if (this.dayNames == null)
- {
- // Get the day names for our current calendar
- this.dayNames = this.m_cultureData.DayNames(Calendar.ID);
- Debug.Assert(this.dayNames.Length == 7, "[DateTimeFormatInfo.GetDayOfWeekNames] Expected 7 day names in a week");
- }
- return (this.dayNames);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Create an array of string which contains the abbreviated month names.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- private String[] internalGetAbbreviatedMonthNames()
- {
- if (this.abbreviatedMonthNames == null)
- {
- // Get the month names for our current calendar
- this.abbreviatedMonthNames = this.m_cultureData.AbbreviatedMonthNames(Calendar.ID);
- Debug.Assert(this.abbreviatedMonthNames.Length == 12 || this.abbreviatedMonthNames.Length == 13,
- "[DateTimeFormatInfo.GetAbbreviatedMonthNames] Expected 12 or 13 month names in a year");
- }
- return (this.abbreviatedMonthNames);
- }
-
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Create an array of string which contains the month names.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- private String[] internalGetMonthNames()
- {
- if (this.monthNames == null)
- {
- // Get the month names for our current calendar
- this.monthNames = this.m_cultureData.MonthNames(Calendar.ID);
- Debug.Assert(this.monthNames.Length == 12 || this.monthNames.Length == 13,
- "[DateTimeFormatInfo.GetMonthNames] Expected 12 or 13 month names in a year");
- }
-
- return (this.monthNames);
- }
-
-
- //
- // Invariant DateTimeFormatInfo doesn't have user-overriden values
- // Default calendar is gregorian
- public DateTimeFormatInfo()
- : this(CultureInfo.InvariantCulture.m_cultureData,
- GregorianCalendar.GetDefaultInstance())
- {
- }
-
- internal DateTimeFormatInfo(CultureData cultureData, Calendar cal)
- {
- Contract.Requires(cultureData != null);
- Contract.Requires(cal != null);
-
- // Remember our culture
- this.m_cultureData = cultureData;
-
- // m_isDefaultCalendar is set in the setter of Calendar below.
- this.Calendar = cal;
- }
- private void InitializeOverridableProperties(CultureData cultureData, int calendarID)
- {
- // Silverlight 2.0 never took a snapshot of the user's overridable properties
- // This has a substantial performance impact so skip when CoreCLR
- Contract.Requires(cultureData != null);
- Debug.Assert(calendarID > 0, "[DateTimeFormatInfo.Populate] Expected Calendar.ID > 0");
-
- if (this.firstDayOfWeek == -1) { this.firstDayOfWeek = cultureData.IFIRSTDAYOFWEEK; }
- if (this.calendarWeekRule == -1) { this.calendarWeekRule = cultureData.IFIRSTWEEKOFYEAR; }
-
- if (this.amDesignator == null) { this.amDesignator = cultureData.SAM1159; }
- if (this.pmDesignator == null) { this.pmDesignator = cultureData.SPM2359; }
- if (this.timeSeparator == null) { this.timeSeparator = cultureData.TimeSeparator; }
- if (this.dateSeparator == null) { this.dateSeparator = cultureData.DateSeparator(calendarID); }
-
- this.allLongTimePatterns = this.m_cultureData.LongTimes;
- Debug.Assert(this.allLongTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long time patterns");
-
- this.allShortTimePatterns = this.m_cultureData.ShortTimes;
- Debug.Assert(this.allShortTimePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short time patterns");
-
- this.allLongDatePatterns = cultureData.LongDates(calendarID);
- Debug.Assert(this.allLongDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some long date patterns");
-
- this.allShortDatePatterns = cultureData.ShortDates(calendarID);
- Debug.Assert(this.allShortDatePatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some short date patterns");
-
- this.allYearMonthPatterns = cultureData.YearMonths(calendarID);
- Debug.Assert(this.allYearMonthPatterns.Length > 0, "[DateTimeFormatInfo.Populate] Expected some year month patterns");
- }
-
-#region Serialization
- // The following fields are defined to keep the serialization compatibility with .NET V1.0/V1.1.
- [OptionalField(VersionAdded = 1)]
- private int CultureID;
- [OptionalField(VersionAdded = 1)]
- private bool m_useUserOverride;
- [OptionalField(VersionAdded = 1)]
- private bool bUseCalendarInfo;
- [OptionalField(VersionAdded = 1)]
- private int nDataItem;
- [OptionalField(VersionAdded = 2)]
- internal bool m_isDefaultCalendar; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey)
-
- // This was synthesized by Whidbey so we knew what words might appear in the middle of a date string
- // Now we always synthesize so its not helpful
- [OptionalField(VersionAdded = 1)]
- internal String[] m_dateWords = null; // calculated, no need to serialze (whidbey expects, arrowhead doesn't)
-
- [OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- if (this.m_name != null)
- {
- m_cultureData = CultureData.GetCultureData(m_name, m_useUserOverride);
-
- if (this.m_cultureData == null)
- throw new CultureNotFoundException(
- nameof(m_name), m_name, Environment.GetResourceString("Argument_CultureNotSupported"));
- }
- // Note: This is for Everett compatibility
-
-#if FEATURE_USE_LCID
- else
- m_cultureData = CultureData.GetCultureData(CultureID, m_useUserOverride);
-#endif
- if (calendar == null)
- {
- calendar = (Calendar) GregorianCalendar.GetDefaultInstance().Clone();
- calendar.SetReadOnlyState(m_isReadOnly);
- }
- InitializeOverridableProperties(m_cultureData, calendar.ID);
-
- //
- // turn off read only state till we finish initializing all fields and then store read only state after we are done.
- //
- bool isReadOnly = m_isReadOnly;
- m_isReadOnly = false;
-
- // If we deserialized defaults ala Whidbey, make sure they're still defaults
- // Whidbey's arrays could get a bit mixed up.
- if (longDatePattern != null) this.LongDatePattern = longDatePattern;
- if (shortDatePattern != null) this.ShortDatePattern = shortDatePattern;
- if (yearMonthPattern != null) this.YearMonthPattern = yearMonthPattern;
- if (longTimePattern != null) this.LongTimePattern = longTimePattern;
- if (shortTimePattern != null) this.ShortTimePattern = shortTimePattern;
-
- m_isReadOnly = isReadOnly;
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
-#if FEATURE_USE_LCID
- CultureID = this.m_cultureData.ILANGUAGE; // Used for serialization compatibility with Whidbey which didn't always serialize the name
-#endif
- m_useUserOverride = this.m_cultureData.UseUserOverride;
-
- // make sure the m_name is initialized.
- m_name = this.CultureName;
-
- // Important to initialize these fields otherwise we may run into exception when deserializing on Whidbey
- // because Whidbey try to initialize some of these fields using calendar data which could be null values
- // and then we get exceptions. So we call the accessors to force the caches to get loaded.
- Object o;
- o = this.LongTimePattern;
- o = this.LongDatePattern;
- o = this.ShortTimePattern;
- o = this.ShortDatePattern;
- o = this.YearMonthPattern;
- o = this.AllLongTimePatterns;
- o = this.AllLongDatePatterns;
- o = this.AllShortTimePatterns;
- o = this.AllShortDatePatterns;
- o = this.AllYearMonthPatterns;
- }
-#endregion Serialization
-
- // Returns a default DateTimeFormatInfo that will be universally
- // supported and constant irrespective of the current culture.
- // Used by FromString methods.
- //
-
- public static DateTimeFormatInfo InvariantInfo {
- get {
- Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
- if (invariantInfo == null)
- {
- DateTimeFormatInfo info = new DateTimeFormatInfo();
- info.Calendar.SetReadOnlyState(true);
- info.m_isReadOnly = true;
- invariantInfo = info;
- }
- return (invariantInfo);
- }
- }
-
- // Returns the current culture's DateTimeFormatInfo. Used by Parse methods.
- //
-
- public static DateTimeFormatInfo CurrentInfo {
- get {
- Contract.Ensures(Contract.Result<DateTimeFormatInfo>() != null);
- System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
- if (!culture.m_isInherited) {
- DateTimeFormatInfo info = culture.dateTimeInfo;
- if (info != null) {
- return info;
- }
- }
- return (DateTimeFormatInfo)culture.GetFormat(typeof(DateTimeFormatInfo));
- }
- }
-
-
- public static DateTimeFormatInfo GetInstance(IFormatProvider provider) {
- // Fast case for a regular CultureInfo
- DateTimeFormatInfo info;
- CultureInfo cultureProvider = provider as CultureInfo;
- if (cultureProvider != null && !cultureProvider.m_isInherited)
- {
- return cultureProvider.DateTimeFormat;
- }
- // Fast case for a DTFI;
- info = provider as DateTimeFormatInfo;
- if (info != null) {
- return info;
- }
- // Wasn't cultureInfo or DTFI, do it the slower way
- if (provider != null) {
- info = provider.GetFormat(typeof(DateTimeFormatInfo)) as DateTimeFormatInfo;
- if (info != null) {
- return info;
- }
- }
- // Couldn't get anything, just use currentInfo as fallback
- return CurrentInfo;
- }
-
-
- public Object GetFormat(Type formatType)
- {
- return (formatType == typeof(DateTimeFormatInfo)? this: null);
- }
-
-
- public Object Clone()
- {
- DateTimeFormatInfo n = (DateTimeFormatInfo)MemberwiseClone();
- // We can use the data member calendar in the setter, instead of the property Calendar,
- // since the cloned copy should have the same state as the original copy.
- n.calendar = (Calendar) this.Calendar.Clone();
- n.m_isReadOnly = false;
- return n;
- }
-
-
- public String AMDesignator
- {
- get
- {
- if (this.amDesignator == null)
- {
- this.amDesignator = this.m_cultureData.SAM1159;
- }
-
- Debug.Assert(this.amDesignator != null, "DateTimeFormatInfo.AMDesignator, amDesignator != null");
- return (this.amDesignator);
- }
-
- set
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
- ClearTokenHashTable();
- amDesignator = value;
- }
- }
-
-
- public Calendar Calendar {
- get {
- Contract.Ensures(Contract.Result<Calendar>() != null);
-
- Debug.Assert(this.calendar != null, "DateTimeFormatInfo.Calendar: calendar != null");
- return (this.calendar);
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Obj"));
- }
- Contract.EndContractBlock();
- if (value == calendar) {
- return;
- }
-
- for (int i = 0; i < this.OptionalCalendars.Length; i++)
- {
- if (this.OptionalCalendars[i] == value.ID)
- {
- // We can use this one, so do so.
-
- // Clean related properties if we already had a calendar set
- if (calendar != null)
- {
- // clean related properties which are affected by the calendar setting,
- // so that they will be refreshed when they are accessed next time.
- //
-
- // These properites are in the order as appearing in calendar.xml.
- m_eraNames = null;
- m_abbrevEraNames = null;
- m_abbrevEnglishEraNames = null;
-
- monthDayPattern = null;
-
- dayNames = null;
- abbreviatedDayNames = null;
- m_superShortDayNames = null;
- monthNames = null;
- abbreviatedMonthNames = null;
- genitiveMonthNames = null;
- m_genitiveAbbreviatedMonthNames = null;
- leapYearMonthNames = null;
- formatFlags = DateTimeFormatFlags.NotInitialized;
-
- allShortDatePatterns = null;
- allLongDatePatterns = null;
- allYearMonthPatterns = null;
- dateTimeOffsetPattern = null;
-
- // The defaults need reset as well:
- longDatePattern = null;
- shortDatePattern = null;
- yearMonthPattern = null;
-
- // These properies are not in the OS data, but they are dependent on the values like shortDatePattern.
- fullDateTimePattern = null; // Long date + long time
- generalShortTimePattern = null; // short date + short time
- generalLongTimePattern = null; // short date + long time
-
- // Derived item that changes
- dateSeparator = null;
-
- // We don't need to do these because they are not changed by changing calendar
- // amDesignator
- // pmDesignator
- // timeSeparator
- // longTimePattern
- // firstDayOfWeek
- // calendarWeekRule
-
- // We don't need to clear these because they're only used for whidbey compat serialization
- // the only values we use are the all...Patterns[0]
- // longDatePattern
- // shortDatePattern
- // yearMonthPattern
-
- // remember to reload tokens
- ClearTokenHashTable();
- }
-
- // Remember the new calendar
- calendar = value;
- InitializeOverridableProperties(m_cultureData, calendar.ID);
-
- // We succeeded, return
- return;
- }
- }
-
- // The assigned calendar is not a valid calendar for this culture, throw
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("Argument_InvalidCalendar"));
- }
- }
-
- private int[] OptionalCalendars {
- get {
- if (this.optionalCalendars == null) {
- this.optionalCalendars = this.m_cultureData.CalendarIds;
- }
- return (this.optionalCalendars);
- }
- }
-
- /*=================================GetEra==========================
- **Action: Get the era value by parsing the name of the era.
- **Returns: The era value for the specified era name.
- ** -1 if the name of the era is not valid or not supported.
- **Arguments: eraName the name of the era.
- **Exceptions: None.
- ============================================================================*/
-
-
- public int GetEra(String eraName) {
- if (eraName == null) {
- throw new ArgumentNullException(nameof(eraName),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
-
- // For Geo-Political reasons, the Era Name and Abbreviated Era Name
- // for Taiwan Calendar on non-Taiwan SKU returns empty string (which
- // would be matched below) but we don't want the empty string to give
- // us an Era number
- // confer 85900 DTFI.GetEra("") should fail on all cultures
- if (eraName.Length == 0) {
- return (-1);
- }
-
- // The following is based on the assumption that the era value is starting from 1, and has a
- // serial values.
- // If that ever changes, the code has to be changed.
-
- // The calls to String.Compare should use the current culture for the string comparisons, but the
- // invariant culture when comparing against the english names.
- for (int i = 0; i < EraNames.Length; i++) {
- // Compare the era name in a case-insensitive way for the appropriate culture.
- if (m_eraNames[i].Length > 0) {
- if (String.Compare(eraName, m_eraNames[i], this.Culture, CompareOptions.IgnoreCase)==0) {
- return (i+1);
- }
- }
- }
- for (int i = 0; i < AbbreviatedEraNames.Length; i++) {
- // Compare the abbreviated era name in a case-insensitive way for the appropriate culture.
- if (String.Compare(eraName, m_abbrevEraNames[i], this.Culture, CompareOptions.IgnoreCase)==0) {
- return (i+1);
- }
- }
- for (int i = 0; i < AbbreviatedEnglishEraNames.Length; i++) {
- // this comparison should use the InvariantCulture. The English name could have linguistically
- // interesting characters.
- if (String.Compare(eraName, m_abbrevEnglishEraNames[i], StringComparison.InvariantCultureIgnoreCase)==0) {
- return (i+1);
- }
- }
- return (-1);
- }
-
- internal String[] EraNames
- {
- get
- {
- if (this.m_eraNames == null)
- {
- this.m_eraNames = this.m_cultureData.EraNames(Calendar.ID);;
- }
- return (this.m_eraNames);
- }
- }
-
- /*=================================GetEraName==========================
- **Action: Get the name of the era for the specified era value.
- **Returns: The name of the specified era.
- **Arguments:
- ** era the era value.
- **Exceptions:
- ** ArguementException if the era valie is invalid.
- ============================================================================*/
-
- // Era names are 1 indexed
- public String GetEraName(int era) {
- if (era == Calendar.CurrentEra) {
- era = Calendar.CurrentEraValue;
- }
-
- // The following is based on the assumption that the era value is starting from 1, and has a
- // serial values.
- // If that ever changes, the code has to be changed.
- if ((--era) < EraNames.Length && (era >= 0)) {
- return (m_eraNames[era]);
- }
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
-
- internal String[] AbbreviatedEraNames
- {
- get
- {
- if (this.m_abbrevEraNames == null)
- {
- this.m_abbrevEraNames = this.m_cultureData.AbbrevEraNames(Calendar.ID);
- }
- return (this.m_abbrevEraNames);
- }
- }
-
- // Era names are 1 indexed
- public String GetAbbreviatedEraName(int era) {
- if (AbbreviatedEraNames.Length == 0) {
- // If abbreviation era name is not used in this culture,
- // return the full era name.
- return (GetEraName(era));
- }
- if (era == Calendar.CurrentEra) {
- era = Calendar.CurrentEraValue;
- }
- if ((--era) < m_abbrevEraNames.Length && (era >= 0)) {
- return (m_abbrevEraNames[era]);
- }
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
-
- internal String[] AbbreviatedEnglishEraNames
- {
- get
- {
- if (this.m_abbrevEnglishEraNames == null)
- {
- Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.AbbreviatedEnglishEraNames] Expected Calendar.ID > 0");
- this.m_abbrevEnglishEraNames = this.m_cultureData.AbbreviatedEnglishEraNames(Calendar.ID);
- }
- return (this.m_abbrevEnglishEraNames);
- }
- }
-
-
- // Note that cultureData derives this from the short date format (unless someone's set this previously)
- // Note that this property is quite undesirable.
- public String DateSeparator
- {
- get
- {
- if (this.dateSeparator == null)
- {
- this.dateSeparator = this.m_cultureData.DateSeparator(Calendar.ID);
- }
-
- Debug.Assert(this.dateSeparator != null, "DateTimeFormatInfo.DateSeparator, dateSeparator != null");
- return (this.dateSeparator);
- }
-
- set
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
- ClearTokenHashTable();
- this.dateSeparator = value;
- }
- }
-
-
- public DayOfWeek FirstDayOfWeek
- {
- get
- {
- if (this.firstDayOfWeek == -1)
- {
- this.firstDayOfWeek = this.m_cultureData.IFIRSTDAYOFWEEK;
- }
-
- Debug.Assert(this.firstDayOfWeek != -1, "DateTimeFormatInfo.FirstDayOfWeek, firstDayOfWeek != -1");
- return ((DayOfWeek)this.firstDayOfWeek);
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value >= DayOfWeek.Sunday && value <= DayOfWeek.Saturday) {
- firstDayOfWeek = (int)value;
- } else {
- throw new ArgumentOutOfRangeException(
- nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range",
- DayOfWeek.Sunday, DayOfWeek.Saturday));
- }
- }
- }
-
-
- public CalendarWeekRule CalendarWeekRule
- {
- get
- {
- if (this.calendarWeekRule == -1)
- {
- this.calendarWeekRule = this.m_cultureData.IFIRSTWEEKOFYEAR;
- }
-
- Debug.Assert(this.calendarWeekRule != -1, "DateTimeFormatInfo.CalendarWeekRule, calendarWeekRule != -1");
- return ((CalendarWeekRule)this.calendarWeekRule);
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value >= CalendarWeekRule.FirstDay && value <= CalendarWeekRule.FirstFourDayWeek) {
- calendarWeekRule = (int)value;
- } else {
- throw new ArgumentOutOfRangeException(
- nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Range",
- CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek));
- }
- }
- }
-
-
-
- public String FullDateTimePattern
- {
- get
- {
- if (fullDateTimePattern == null)
- {
- fullDateTimePattern = LongDatePattern + " " + LongTimePattern;
- }
- return (fullDateTimePattern);
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
- fullDateTimePattern = value;
- }
- }
-
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
- public String LongDatePattern
- {
- get
- {
- // Initialize our long date pattern from the 1st array value if not set
- if (this.longDatePattern == null)
- {
- // Initialize our data
- this.longDatePattern = this.UnclonedLongDatePatterns[0];
- }
-
- return this.longDatePattern;
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
-
- // Remember the new string
- this.longDatePattern = value;
-
- // Clear the token hash table
- ClearTokenHashTable();
-
- // Clean up cached values that will be affected by this property.
- this.fullDateTimePattern = null;
- }
- }
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
- public String LongTimePattern
- {
- get
- {
- // Initialize our long time pattern from the 1st array value if not set
- if (this.longTimePattern == null)
- {
- // Initialize our data
- this.longTimePattern = this.UnclonedLongTimePatterns[0];
- }
-
- return this.longTimePattern;
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
-
- // Remember the new string
- this.longTimePattern = value;
-
- // Clear the token hash table
- ClearTokenHashTable();
-
- // Clean up cached values that will be affected by this property.
- this.fullDateTimePattern = null; // Full date = long date + long Time
- this.generalLongTimePattern = null; // General long date = short date + long Time
- this.dateTimeOffsetPattern = null;
- }
- }
-
-
- // Note: just to be confusing there's only 1 month day pattern, not a whole list
- public String MonthDayPattern
- {
- get
- {
- if (this.monthDayPattern == null)
- {
- Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.MonthDayPattern] Expected calID > 0");
- this.monthDayPattern = this.m_cultureData.MonthDay(Calendar.ID);
- }
- Debug.Assert(this.monthDayPattern != null, "DateTimeFormatInfo.MonthDayPattern, monthDayPattern != null");
- return (this.monthDayPattern);
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
-
- this.monthDayPattern = value;
- }
- }
-
-
- public String PMDesignator
- {
- get
- {
- if (this.pmDesignator == null)
- {
- this.pmDesignator = this.m_cultureData.SPM2359;
- }
-
- Debug.Assert(this.pmDesignator != null, "DateTimeFormatInfo.PMDesignator, pmDesignator != null");
- return (this.pmDesignator);
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
- ClearTokenHashTable();
-
- pmDesignator = value;
- }
-
- }
-
-
- public String RFC1123Pattern
- {
- get
- {
- return (rfc1123Pattern);
- }
- }
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
- public String ShortDatePattern
- {
- get
- {
- // Initialize our short date pattern from the 1st array value if not set
- if (this.shortDatePattern == null)
- {
- // Initialize our data
- this.shortDatePattern = this.UnclonedShortDatePatterns[0];
- }
-
- return this.shortDatePattern;
- }
-
- set
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- Contract.EndContractBlock();
-
- // Remember the new string
- this.shortDatePattern = value;
-
- // Clear the token hash table, note that even short dates could require this
- ClearTokenHashTable();
-
- // Clean up cached values that will be affected by this property.
- generalLongTimePattern = null; // General long time = short date + long time
- generalShortTimePattern = null; // General short time = short date + short Time
- dateTimeOffsetPattern = null;
- }
- }
-
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
- public String ShortTimePattern
- {
- get
- {
- // Initialize our short time pattern from the 1st array value if not set
- if (this.shortTimePattern == null)
- {
- // Initialize our data
- this.shortTimePattern = this.UnclonedShortTimePatterns[0];
- }
- return this.shortTimePattern;
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
-
- // Remember the new string
- this.shortTimePattern= value;
-
- // Clear the token hash table, note that even short times could require this
- ClearTokenHashTable();
-
- // Clean up cached values that will be affected by this property.
- generalShortTimePattern = null; // General short date = short date + short time.
- }
- }
-
-
- public String SortableDateTimePattern {
- get {
- return (sortableDateTimePattern);
- }
- }
-
- /*=================================GeneralShortTimePattern=====================
- **Property: Return the pattern for 'g' general format: shortDate + short time
- **Note: This is used by DateTimeFormat.cs to get the pattern for 'g'
- ** We put this internal property here so that we can avoid doing the
- ** concatation every time somebody asks for the general format.
- ==============================================================================*/
-
- internal String GeneralShortTimePattern {
- get {
- if (generalShortTimePattern == null) {
- generalShortTimePattern = ShortDatePattern + " " + ShortTimePattern;
- }
- return (generalShortTimePattern);
- }
- }
-
- /*=================================GeneralLongTimePattern=====================
- **Property: Return the pattern for 'g' general format: shortDate + Long time
- **Note: This is used by DateTimeFormat.cs to get the pattern for 'g'
- ** We put this internal property here so that we can avoid doing the
- ** concatation every time somebody asks for the general format.
- ==============================================================================*/
-
- internal String GeneralLongTimePattern {
- get {
- if (generalLongTimePattern == null) {
- generalLongTimePattern = ShortDatePattern + " " + LongTimePattern;
- }
- return (generalLongTimePattern);
- }
- }
-
- /*=================================DateTimeOffsetPattern==========================
- **Property: Return the default pattern DateTimeOffset : shortDate + long time + time zone offset
- **Note: This is used by DateTimeFormat.cs to get the pattern for short Date + long time + time zone offset
- ** We put this internal property here so that we can avoid doing the
- ** concatation every time somebody uses this form
- ==============================================================================*/
-
- /*=================================DateTimeOffsetPattern==========================
- **Property: Return the default pattern DateTimeOffset : shortDate + long time + time zone offset
- **Note: This is used by DateTimeFormat.cs to get the pattern for short Date + long time + time zone offset
- ** We put this internal property here so that we can avoid doing the
- ** concatation every time somebody uses this form
- ==============================================================================*/
-
- internal String DateTimeOffsetPattern {
- get {
- if (dateTimeOffsetPattern == null) {
-
- string dateTimePattern = ShortDatePattern + " " + LongTimePattern;
-
- /* LongTimePattern might contain a "z" as part of the format string in which case we don't want to append a time zone offset */
-
- bool foundZ = false;
- bool inQuote = false;
- char quote = '\'';
- for (int i = 0; !foundZ && i < LongTimePattern.Length; i++) {
- switch (LongTimePattern[i]) {
- case 'z':
- /* if we aren't in a quote, we've found a z */
- foundZ = !inQuote;
- /* we'll fall out of the loop now because the test includes !foundZ */
- break;
- case '\'':
- case '\"':
- if (inQuote && (quote == LongTimePattern[i])) {
- /* we were in a quote and found a matching exit quote, so we are outside a quote now */
- inQuote = false;
- } else if (!inQuote) {
- quote = LongTimePattern[i];
- inQuote = true;
- } else {
- /* we were in a quote and saw the other type of quote character, so we are still in a quote */
- }
- break;
- case '%':
- case '\\':
- i++; /* skip next character that is escaped by this backslash */
- break;
- default:
- break;
- }
- }
-
- if (!foundZ) {
- dateTimePattern = dateTimePattern + " zzz";
- }
-
- dateTimeOffsetPattern = dateTimePattern;
- }
- return (dateTimeOffsetPattern);
- }
- }
-
- // Note that cultureData derives this from the long time format (unless someone's set this previously)
- // Note that this property is quite undesirable.
- public String TimeSeparator
- {
- get
- {
- if (timeSeparator == null)
- {
- timeSeparator = this.m_cultureData.TimeSeparator;
- }
-
- Debug.Assert(this.timeSeparator != null, "DateTimeFormatInfo.TimeSeparator, timeSeparator != null");
- return (timeSeparator);
- }
-
- set
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
- ClearTokenHashTable();
-
- timeSeparator = value;
- }
- }
-
-
- public String UniversalSortableDateTimePattern
- {
- get
- {
- return (universalSortableDateTimePattern);
- }
- }
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
- public String YearMonthPattern
- {
- get
- {
- // Initialize our year/month pattern from the 1st array value if not set
- if (this.yearMonthPattern == null)
- {
- // Initialize our data
- this.yearMonthPattern = this.UnclonedYearMonthPatterns[0];
- }
- return this.yearMonthPattern;
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_String"));
- }
- Contract.EndContractBlock();
-
- // Remember the new string
- this.yearMonthPattern = value;
-
- // Clear the token hash table, note that even short times could require this
- ClearTokenHashTable();
- }
- }
-
- //
- // Check if a string array contains a null value, and throw ArgumentNullException with parameter name "value"
- //
- static private void CheckNullValue(String[] values, int length) {
- Contract.Requires(values != null, "value != null");
- Contract.Requires(values.Length >= length);
- for (int i = 0; i < length; i++) {
- if (values[i] == null) {
- throw new ArgumentNullException("value",
- Environment.GetResourceString("ArgumentNull_ArrayValue"));
- }
- }
- }
-
-
- public String[] AbbreviatedDayNames
- {
- get
- {
- return ((String[])internalGetAbbreviatedDayOfWeekNames().Clone());
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 7) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length);
- ClearTokenHashTable();
-
- abbreviatedDayNames = value;
- }
- }
-
-
- // Returns the string array of the one-letter day of week names.
- public String[] ShortestDayNames
- {
- get
- {
- return ((String[])internalGetSuperShortDayNames().Clone());
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 7)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length);
- this.m_superShortDayNames = value;
- }
- }
-
-
- public String[] DayNames
- {
- get
- {
- return ((String[])internalGetDayOfWeekNames().Clone());
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 7)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 7), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length);
- ClearTokenHashTable();
-
- dayNames = value;
- }
- }
-
-
- public String[] AbbreviatedMonthNames {
- get {
- return ((String[])internalGetAbbreviatedMonthNames().Clone());
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 13)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length - 1);
- ClearTokenHashTable();
- abbreviatedMonthNames = value;
- }
- }
-
-
- public String[] MonthNames
- {
- get
- {
- return ((String[])internalGetMonthNames().Clone());
- }
-
- set {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null) {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 13)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length - 1);
- monthNames = value;
- ClearTokenHashTable();
- }
- }
-
- // Whitespaces that we allow in the month names.
- // U+00a0 is non-breaking space.
- static char[] MonthSpaces = {' ', '\u00a0'};
-
- internal bool HasSpacesInMonthNames {
- get {
- return (FormatFlags & DateTimeFormatFlags.UseSpacesInMonthNames) != 0;
- }
- }
-
- internal bool HasSpacesInDayNames {
- get {
- return (FormatFlags & DateTimeFormatFlags.UseSpacesInDayNames) != 0;
- }
- }
-
-
- //
- // internalGetMonthName
- //
- // Actions: Return the month name using the specified MonthNameStyles in either abbreviated form
- // or full form.
- // Arguments:
- // month
- // style To indicate a form like regular/genitive/month name in a leap year.
- // abbreviated When true, return abbreviated form. Otherwise, return a full form.
- // Exceptions:
- // ArgumentOutOfRangeException When month name is invalid.
- //
- internal String internalGetMonthName(int month, MonthNameStyles style, bool abbreviated) {
- //
- // Right now, style is mutual exclusive, but I make the style to be flag so that
- // maybe we can combine flag if there is such a need.
- //
- String[] monthNamesArray = null;
- switch (style) {
- case MonthNameStyles.Genitive:
- monthNamesArray = internalGetGenitiveMonthNames(abbreviated);
- break;
- case MonthNameStyles.LeapYear:
- monthNamesArray = internalGetLeapYearMonthNames(/*abbreviated*/);
- break;
- default:
- monthNamesArray = (abbreviated ? internalGetAbbreviatedMonthNames(): internalGetMonthNames());
- break;
- }
- // The month range is from 1 ~ this.m_monthNames.Length
- // (actually is 13 right now for all cases)
- if ((month < 1) || (month > monthNamesArray.Length)) {
- throw new ArgumentOutOfRangeException(
- nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
- 1, monthNamesArray.Length));
- }
- return (monthNamesArray[month-1]);
- }
-
- //
- // internalGetGenitiveMonthNames
- //
- // Action: Retrieve the array which contains the month names in genitive form.
- // If this culture does not use the gentive form, the normal month name is returned.
- // Arguments:
- // abbreviated When true, return abbreviated form. Otherwise, return a full form.
- //
- private String[] internalGetGenitiveMonthNames(bool abbreviated) {
- if (abbreviated) {
- if (this.m_genitiveAbbreviatedMonthNames == null)
- {
- this.m_genitiveAbbreviatedMonthNames = this.m_cultureData.AbbreviatedGenitiveMonthNames(this.Calendar.ID);
- Debug.Assert(this.m_genitiveAbbreviatedMonthNames.Length == 13,
- "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 abbreviated genitive month names in a year");
- }
- return (this.m_genitiveAbbreviatedMonthNames);
- }
-
- if (this.genitiveMonthNames == null)
- {
- this.genitiveMonthNames = this.m_cultureData.GenitiveMonthNames(this.Calendar.ID);
- Debug.Assert(this.genitiveMonthNames.Length == 13,
- "[DateTimeFormatInfo.GetGenitiveMonthNames] Expected 13 genitive month names in a year");
- }
- return (this.genitiveMonthNames);
- }
-
- //
- // internalGetLeapYearMonthNames
- //
- // Actions: Retrieve the month names used in a leap year.
- // If this culture does not have different month names in a leap year, the normal month name is returned.
- // Agruments: None. (can use abbreviated later if needed)
- //
- internal String[] internalGetLeapYearMonthNames(/*bool abbreviated*/) {
- if (this.leapYearMonthNames == null)
- {
- Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expected Calendar.ID > 0");
- this.leapYearMonthNames = this.m_cultureData.LeapYearMonthNames(Calendar.ID);
- Debug.Assert(this.leapYearMonthNames.Length == 13,
- "[DateTimeFormatInfo.internalGetLeapYearMonthNames] Expepcted 13 leap year month names");
- }
- return (leapYearMonthNames);
- }
-
-
- public String GetAbbreviatedDayName(DayOfWeek dayofweek)
- {
-
- if ((int)dayofweek < 0 || (int)dayofweek > 6) {
- throw new ArgumentOutOfRangeException(
- nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range",
- DayOfWeek.Sunday, DayOfWeek.Saturday));
- }
- Contract.EndContractBlock();
- //
- // Don't call the public property AbbreviatedDayNames here since a clone is needed in that
- // property, so it will be slower. Instead, use GetAbbreviatedDayOfWeekNames() directly.
- //
- return (internalGetAbbreviatedDayOfWeekNames()[(int)dayofweek]);
- }
-
-
- // Returns the super short day of week names for the specified day of week.
- public String GetShortestDayName(DayOfWeek dayOfWeek)
- {
-
- if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6) {
- throw new ArgumentOutOfRangeException(
- nameof(dayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_Range",
- DayOfWeek.Sunday, DayOfWeek.Saturday));
- }
- Contract.EndContractBlock();
- //
- // Don't call the public property SuperShortDayNames here since a clone is needed in that
- // property, so it will be slower. Instead, use internalGetSuperShortDayNames() directly.
- //
- return (internalGetSuperShortDayNames()[(int)dayOfWeek]);
- }
-
- // Get all possible combination of inputs
- static private String[] GetCombinedPatterns(String[] patterns1, String[] patterns2, String connectString)
- {
- Contract.Requires(patterns1 != null);
- Contract.Requires(patterns2 != null);
-
- // Get array size
- String[] result = new String[patterns1.Length * patterns2.Length];
-
- // Counter of actual results
- int k = 0;
- for (int i = 0; i < patterns1.Length; i++)
- {
- for (int j = 0; j < patterns2.Length; j++)
- {
- // Can't combine if null or empty
- result[k++] = patterns1[i] + connectString + patterns2[j];
- }
- }
-
- // Return the combinations
- return (result);
- }
-
-
- public String[] GetAllDateTimePatterns()
- {
- List<String> results = new List<String>(DEFAULT_ALL_DATETIMES_SIZE);
-
- for (int i = 0; i < DateTimeFormat.allStandardFormats.Length; i++)
- {
- String[] strings = GetAllDateTimePatterns(DateTimeFormat.allStandardFormats[i]);
- for (int j = 0; j < strings.Length; j++)
- {
- results.Add(strings[j]);
- }
- }
- return results.ToArray();
- }
-
-
- public String[] GetAllDateTimePatterns(char format)
- {
- Contract.Ensures(Contract.Result<String[]>() != null);
- String [] result = null;
-
- switch (format)
- {
- case 'd':
- result = this.AllShortDatePatterns;
- break;
- case 'D':
- result = this.AllLongDatePatterns;
- break;
- case 'f':
- result = GetCombinedPatterns(AllLongDatePatterns, AllShortTimePatterns, " ");
- break;
- case 'F':
- case 'U':
- result = GetCombinedPatterns(AllLongDatePatterns, AllLongTimePatterns, " ");
- break;
- case 'g':
- result = GetCombinedPatterns(AllShortDatePatterns, AllShortTimePatterns, " ");
- break;
- case 'G':
- result = GetCombinedPatterns(AllShortDatePatterns, AllLongTimePatterns, " ");
- break;
- case 'm':
- case 'M':
- result = new String[] {MonthDayPattern};
- break;
- case 'o':
- case 'O':
- result = new String[] {DateTimeFormat.RoundtripFormat};
- break;
- case 'r':
- case 'R':
- result = new String[] {rfc1123Pattern};
- break;
- case 's':
- result = new String[] {sortableDateTimePattern};
- break;
- case 't':
- result = this.AllShortTimePatterns;
- break;
- case 'T':
- result = this.AllLongTimePatterns;
- break;
- case 'u':
- result = new String[] {UniversalSortableDateTimePattern};
- break;
- case 'y':
- case 'Y':
- result = this.AllYearMonthPatterns;
- break;
- default:
- throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format));
- }
- return (result);
- }
-
-
- public String GetDayName(DayOfWeek dayofweek)
- {
- if ((int)dayofweek < 0 || (int)dayofweek > 6) {
- throw new ArgumentOutOfRangeException(
- nameof(dayofweek), Environment.GetResourceString("ArgumentOutOfRange_Range",
- DayOfWeek.Sunday, DayOfWeek.Saturday));
- }
- Contract.EndContractBlock();
-
- // Use the internal one so that we don't clone the array unnecessarily
- return (internalGetDayOfWeekNames()[(int)dayofweek]);
- }
-
-
-
- public String GetAbbreviatedMonthName(int month)
- {
- if (month < 1 || month > 13) {
- throw new ArgumentOutOfRangeException(
- nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
- 1, 13));
- }
- Contract.EndContractBlock();
- // Use the internal one so we don't clone the array unnecessarily
- return (internalGetAbbreviatedMonthNames()[month-1]);
- }
-
-
- public String GetMonthName(int month)
- {
- if (month < 1 || month > 13) {
- throw new ArgumentOutOfRangeException(
- nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
- 1, 13));
- }
- Contract.EndContractBlock();
- // Use the internal one so we don't clone the array unnecessarily
- return (internalGetMonthNames()[month-1]);
- }
-
- // For our "patterns" arrays we have 2 variables, a string and a string[]
- //
- // The string[] contains the list of patterns, EXCEPT the default may not be included.
- // The string contains the default pattern.
- // When we initially construct our string[], we set the string to string[0]
- //
- // The resulting [] can get returned to the calling app, so clone it.
- private static string[] GetMergedPatterns(string [] patterns, string defaultPattern)
- {
- Debug.Assert(patterns != null && patterns.Length > 0,
- "[DateTimeFormatInfo.GetMergedPatterns]Expected array of at least one pattern");
- Debug.Assert(defaultPattern != null,
- "[DateTimeFormatInfo.GetMergedPatterns]Expected non null default string");
-
- // If the default happens to be the first in the list just return (a cloned) copy
- if (defaultPattern == patterns[0])
- {
- return (string[])patterns.Clone();
- }
-
- // We either need a bigger list, or the pattern from the list.
- int i;
- for (i = 0; i < patterns.Length; i++)
- {
- // Stop if we found it
- if (defaultPattern == patterns[i])
- break;
- }
-
- // Either way we're going to need a new array
- string[] newPatterns;
-
- // Did we find it
- if (i < patterns.Length)
- {
- // Found it, output will be same size
- newPatterns = (string[])patterns.Clone();
-
- // Have to move [0] item to [i] so we can re-write default at [0]
- // (remember defaultPattern == [i] so this is OK)
- newPatterns[i] = newPatterns[0];
- }
- else
- {
- // Not found, make room for it
- newPatterns = new String[patterns.Length + 1];
-
- // Copy existing array
- Array.Copy(patterns, 0, newPatterns, 1, patterns.Length);
- }
-
- // Remember the default
- newPatterns[0] = defaultPattern;
-
- // Return the reconstructed list
- return newPatterns;
- }
-
- // Default string isn't necessarily in our string array, so get the
- // merged patterns of both
- private String[] AllYearMonthPatterns
- {
- get
- {
- return GetMergedPatterns(this.UnclonedYearMonthPatterns, this.YearMonthPattern);
- }
- }
-
- private String[] AllShortDatePatterns
- {
- get
- {
- return GetMergedPatterns(this.UnclonedShortDatePatterns, this.ShortDatePattern);
- }
- }
-
- private String[] AllShortTimePatterns
- {
- get
- {
- return GetMergedPatterns(this.UnclonedShortTimePatterns, this.ShortTimePattern);
- }
- }
-
- private String[] AllLongDatePatterns
- {
- get
- {
- return GetMergedPatterns(this.UnclonedLongDatePatterns, this.LongDatePattern);
- }
- }
-
- private String[] AllLongTimePatterns
- {
- get
- {
- return GetMergedPatterns(this.UnclonedLongTimePatterns, this.LongTimePattern);
- }
- }
-
- // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy.
- // This won't include default, call AllYearMonthPatterns
- private String[] UnclonedYearMonthPatterns
- {
- get
- {
- if (this.allYearMonthPatterns == null)
- {
- Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected Calendar.ID > 0");
- this.allYearMonthPatterns = this.m_cultureData.YearMonths(this.Calendar.ID);
- Debug.Assert(this.allYearMonthPatterns.Length > 0,
- "[DateTimeFormatInfo.UnclonedYearMonthPatterns] Expected some year month patterns");
- }
-
- return this.allYearMonthPatterns;
- }
- }
-
-
- // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy.
- // This won't include default, call AllShortDatePatterns
- private String [] UnclonedShortDatePatterns
- {
- get
- {
- if (allShortDatePatterns == null)
- {
- Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected Calendar.ID > 0");
- this.allShortDatePatterns = this.m_cultureData.ShortDates(this.Calendar.ID);
- Debug.Assert(this.allShortDatePatterns.Length > 0,
- "[DateTimeFormatInfo.UnclonedShortDatePatterns] Expected some short date patterns");
- }
-
- return this.allShortDatePatterns;
- }
- }
-
- // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy.
- // This won't include default, call AllLongDatePatterns
- private String[] UnclonedLongDatePatterns
- {
- get
- {
- if (allLongDatePatterns == null)
- {
- Debug.Assert(Calendar.ID > 0, "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected Calendar.ID > 0");
- this.allLongDatePatterns = this.m_cultureData.LongDates(this.Calendar.ID);
- Debug.Assert(this.allLongDatePatterns.Length > 0,
- "[DateTimeFormatInfo.UnclonedLongDatePatterns] Expected some long date patterns");
- }
-
- return this.allLongDatePatterns;
- }
- }
-
- // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy.
- // This won't include default, call AllShortTimePatterns
- private String[] UnclonedShortTimePatterns
- {
- get
- {
- if (this.allShortTimePatterns == null)
- {
- this.allShortTimePatterns = this.m_cultureData.ShortTimes;
- Debug.Assert(this.allShortTimePatterns.Length > 0,
- "[DateTimeFormatInfo.UnclonedShortTimePatterns] Expected some short time patterns");
- }
-
- return this.allShortTimePatterns;
- }
- }
-
- // NOTE: Clone this string array if you want to return it to user. Otherwise, you are returning a writable cache copy.
- // This won't include default, call AllLongTimePatterns
- private String[] UnclonedLongTimePatterns
- {
- get
- {
- if (this.allLongTimePatterns == null)
- {
- this.allLongTimePatterns = this.m_cultureData.LongTimes;
- Debug.Assert(this.allLongTimePatterns.Length > 0,
- "[DateTimeFormatInfo.UnclonedLongTimePatterns] Expected some long time patterns");
- }
-
- return this.allLongTimePatterns;
- }
- }
-
- public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) {
- if (dtfi == null) {
- throw new ArgumentNullException(nameof(dtfi),
- Environment.GetResourceString("ArgumentNull_Obj"));
- }
- Contract.EndContractBlock();
- if (dtfi.IsReadOnly) {
- return (dtfi);
- }
- DateTimeFormatInfo newInfo = (DateTimeFormatInfo)(dtfi.MemberwiseClone());
- // We can use the data member calendar in the setter, instead of the property Calendar,
- // since the cloned copy should have the same state as the original copy.
- newInfo.calendar = Calendar.ReadOnly(dtfi.Calendar);
- newInfo.m_isReadOnly = true;
- return (newInfo);
- }
-
-
- public bool IsReadOnly {
- get {
- return (m_isReadOnly);
- }
- }
-
- // Return the native name for the calendar in DTFI.Calendar. The native name is referred to
- // the culture used to create the DTFI. E.g. in the following example, the native language is Japanese.
- // DateTimeFormatInfo dtfi = new CultureInfo("ja-JP", false).DateTimeFormat.Calendar = new JapaneseCalendar();
- // String nativeName = dtfi.NativeCalendarName; // Get the Japanese name for the Japanese calendar.
- // DateTimeFormatInfo dtfi = new CultureInfo("ja-JP", false).DateTimeFormat.Calendar = new GregorianCalendar(GregorianCalendarTypes.Localized);
- // String nativeName = dtfi.NativeCalendarName; // Get the Japanese name for the Gregorian calendar.
- public String NativeCalendarName
- {
- get
- {
- return m_cultureData.CalendarName(Calendar.ID);
- }
- }
-
- //
- // Used by custom cultures and others to set the list of available formats. Note that none of them are
- // explicitly used unless someone calls GetAllDateTimePatterns and subsequently uses one of the items
- // from the list.
- //
- // Most of the format characters that can be used in GetAllDateTimePatterns are
- // not really needed since they are one of the following:
- //
- // r/R/s/u locale-independent constants -- cannot be changed!
- // m/M/y/Y fields with a single string in them -- that can be set through props directly
- // f/F/g/G/U derived fields based on combinations of various of the below formats
- //
- // NOTE: No special validation is done here beyond what is done when the actual respective fields
- // are used (what would be the point of disallowing here what we allow in the appropriate property?)
- //
- // WARNING: If more validation is ever done in one place, it should be done in the other.
- //
-
- public void SetAllDateTimePatterns(String[] patterns, char format)
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (patterns == null) {
- throw new ArgumentNullException(nameof(patterns),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
-
- if (patterns.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"), nameof(patterns));
- }
- Contract.EndContractBlock();
-
- for (int i=0; i<patterns.Length; i++)
- {
- if (patterns[i] == null)
- {
- throw new ArgumentNullException("patterns[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayValue"));
- }
- }
-
- // Remember the patterns, and use the 1st as default
- switch (format)
- {
- case 'd':
- this.allShortDatePatterns = patterns;
- this.shortDatePattern = this.allShortDatePatterns[0];
- break;
-
- case 'D':
- this.allLongDatePatterns = patterns;
- this.longDatePattern = this.allLongDatePatterns[0];
- break;
-
- case 't':
- this.allShortTimePatterns = patterns;
- this.shortTimePattern = this.allShortTimePatterns[0];
- break;
-
- case 'T':
- this.allLongTimePatterns = patterns;
- this.longTimePattern = this.allLongTimePatterns[0];
- break;
-
- case 'y':
- case 'Y':
- this.allYearMonthPatterns = patterns;
- this.yearMonthPattern = this.allYearMonthPatterns[0];
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Format_BadFormatSpecifier"), nameof(format));
- }
-
- // Clear the token hash table, note that even short dates could require this
- ClearTokenHashTable();
-
- return;
- }
-
- public String[] AbbreviatedMonthGenitiveNames
- {
- get
- {
- return ((String[])internalGetGenitiveMonthNames(true).Clone());
- }
-
- set
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 13)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length - 1);
- ClearTokenHashTable();
- this.m_genitiveAbbreviatedMonthNames= value;
- }
- }
-
- public String[] MonthGenitiveNames
- {
- get
- {
- return ((String[])internalGetGenitiveMonthNames(false).Clone());
- }
-
- set
- {
- if (IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value),
- Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (value.Length != 13)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidArrayLength", 13), nameof(value));
- }
- Contract.EndContractBlock();
- CheckNullValue(value, value.Length - 1);
- genitiveMonthNames= value;
- ClearTokenHashTable();
- }
- }
-
- //
- // Positive TimeSpan Pattern
- //
- [NonSerialized]
- private string m_fullTimeSpanPositivePattern;
- internal String FullTimeSpanPositivePattern
- {
- get
- {
- if (m_fullTimeSpanPositivePattern == null)
- {
- CultureData cultureDataWithoutUserOverrides;
- if (m_cultureData.UseUserOverride)
- cultureDataWithoutUserOverrides = CultureData.GetCultureData(m_cultureData.CultureName, false);
- else
- cultureDataWithoutUserOverrides = m_cultureData;
- String decimalSeparator = new NumberFormatInfo(cultureDataWithoutUserOverrides).NumberDecimalSeparator;
-
- m_fullTimeSpanPositivePattern = "d':'h':'mm':'ss'" + decimalSeparator + "'FFFFFFF";
- }
- return m_fullTimeSpanPositivePattern;
- }
- }
-
- //
- // Negative TimeSpan Pattern
- //
- [NonSerialized]
- private string m_fullTimeSpanNegativePattern;
- internal String FullTimeSpanNegativePattern
- {
- get
- {
- if (m_fullTimeSpanNegativePattern == null)
- m_fullTimeSpanNegativePattern = "'-'" + FullTimeSpanPositivePattern;
- return m_fullTimeSpanNegativePattern;
- }
- }
-
- //
- // Get suitable CompareInfo from current DTFI object.
- //
- internal CompareInfo CompareInfo
- {
- get
- {
- if (m_compareInfo == null)
- {
- // We use the regular GetCompareInfo here to make sure the created CompareInfo object is stored in the
- // CompareInfo cache. otherwise we would just create CompareInfo using m_cultureData.
- m_compareInfo = CompareInfo.GetCompareInfo(m_cultureData.SCOMPAREINFO);
- }
-
- return m_compareInfo;
- }
- }
-
-
- internal const DateTimeStyles InvalidDateTimeStyles = ~(DateTimeStyles.AllowLeadingWhite | DateTimeStyles.AllowTrailingWhite
- | DateTimeStyles.AllowInnerWhite | DateTimeStyles.NoCurrentDateDefault
- | DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal
- | DateTimeStyles.AssumeUniversal | DateTimeStyles.RoundtripKind);
-
- internal static void ValidateStyles(DateTimeStyles style, String parameterName) {
- if ((style & InvalidDateTimeStyles) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
- }
- if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
- }
- Contract.EndContractBlock();
- if (((style & DateTimeStyles.RoundtripKind) != 0)
- && ((style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)) != 0)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"), parameterName);
- }
- }
-
- //
- // Actions: Return the internal flag used in formatting and parsing.
- // The flag can be used to indicate things like if genitive forms is used in this DTFi, or if leap year gets different month names.
- //
- internal DateTimeFormatFlags FormatFlags
- {
- get
- {
- if (formatFlags == DateTimeFormatFlags.NotInitialized)
- {
- // Build the format flags from the data in this DTFI
- formatFlags = DateTimeFormatFlags.None;
- formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagGenitiveMonth(
- MonthNames, internalGetGenitiveMonthNames(false), AbbreviatedMonthNames, internalGetGenitiveMonthNames(true));
- formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInMonthNames(
- MonthNames, internalGetGenitiveMonthNames(false), AbbreviatedMonthNames, internalGetGenitiveMonthNames(true));
- formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInDayNames(DayNames, AbbreviatedDayNames);
- formatFlags |= (DateTimeFormatFlags)DateTimeFormatInfoScanner.GetFormatFlagUseHebrewCalendar((int)Calendar.ID);
- }
- return (formatFlags);
- }
- }
-
- internal Boolean HasForceTwoDigitYears {
- get {
- switch (calendar.ID)
- {
- // If is y/yy, do not get (year % 100). "y" will print
- // year without leading zero. "yy" will print year with two-digit in leading zero.
- // If pattern is yyy/yyyy/..., print year value with two-digit in leading zero.
- // So year 5 is "05", and year 125 is "125".
- // The reason for not doing (year % 100) is for Taiwan calendar.
- // If year 125, then output 125 and not 25.
- // Note: OS uses "yyyy" for Taiwan calendar by default.
- case (Calendar.CAL_JAPAN):
- case (Calendar.CAL_TAIWAN):
- return true;
- }
- return false;
- }
- }
-
- // Returns whether the YearMonthAdjustment function has any fix-up work to do for this culture/calendar.
- internal Boolean HasYearMonthAdjustment {
- get {
- return ((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0);
- }
- }
-
- // This is a callback that the parser can make back into the DTFI to let it fiddle with special
- // cases associated with that culture or calendar. Currently this only has special cases for
- // the Hebrew calendar, but this could be extended to other cultures.
- //
- // The return value is whether the year and month are actually valid for this calendar.
- internal Boolean YearMonthAdjustment(ref int year, ref int month, Boolean parsedMonthName) {
- if ((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) {
-
- // Special rules to fix up the Hebrew year/month
-
- // 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.
- if (year < 1000) {
- year += 5000;
- }
-
- // Because we need to calculate leap year, we should fall out now for an invalid year.
- if (year < Calendar.GetYear(Calendar.MinSupportedDateTime) || year > Calendar.GetYear(Calendar.MaxSupportedDateTime)) {
- return false;
- }
-
- // To handle leap months, the set of month names in the symbol table does not always correspond to the numbers.
- // For non-leap years, month 7 (Adar Bet) is not present, so we need to make using this month invalid and
- // shuffle the other months down.
- if (parsedMonthName) {
- if (!Calendar.IsLeapYear(year)) {
- if (month >= 8) {
- month--;
- }
- else if (month == 7) {
- return false;
- }
- }
- }
- }
- return true;
- }
-
- //
- // DateTimeFormatInfo tokenizer. This is used by DateTime.Parse() to break input string into tokens.
- //
- [NonSerialized]
- TokenHashValue[] m_dtfiTokenHash;
-
- private const int TOKEN_HASH_SIZE = 199;
- private const int SECOND_PRIME = 197;
- private const String dateSeparatorOrTimeZoneOffset = "-";
- private const String invariantDateSeparator = "/";
- private const String invariantTimeSeparator = ":";
-
- //
- // Common Ignorable Symbols
- //
- internal const String IgnorablePeriod = ".";
- internal const String IgnorableComma = ",";
-
- //
- // Year/Month/Day suffixes
- //
- internal const String CJKYearSuff = "\u5e74";
- internal const String CJKMonthSuff = "\u6708";
- internal const String CJKDaySuff = "\u65e5";
-
- internal const String KoreanYearSuff = "\ub144";
- internal const String KoreanMonthSuff = "\uc6d4";
- internal const String KoreanDaySuff = "\uc77c";
-
- internal const String KoreanHourSuff = "\uc2dc";
- internal const String KoreanMinuteSuff = "\ubd84";
- internal const String KoreanSecondSuff = "\ucd08";
-
- internal const String CJKHourSuff = "\u6642";
- internal const String ChineseHourSuff = "\u65f6";
-
- internal const String CJKMinuteSuff = "\u5206";
- internal const String CJKSecondSuff = "\u79d2";
-
- internal const String LocalTimeMark = "T";
-
- internal const String KoreanLangName = "ko";
- internal const String JapaneseLangName = "ja";
- internal const String EnglishLangName = "en";
-
- private static volatile DateTimeFormatInfo s_jajpDTFI;
- private static volatile DateTimeFormatInfo s_zhtwDTFI;
-
- //
- // Create a Japanese DTFI which uses JapaneseCalendar. This is used to parse
- // date string with Japanese era name correctly even when the supplied DTFI
- // does not use Japanese calendar.
- // The created instance is stored in global s_jajpDTFI.
- //
- internal static DateTimeFormatInfo GetJapaneseCalendarDTFI() {
- DateTimeFormatInfo temp = s_jajpDTFI;
- if (temp == null) {
- temp = new CultureInfo("ja-JP", false).DateTimeFormat;
- temp.Calendar = JapaneseCalendar.GetDefaultInstance();
- s_jajpDTFI = temp;
- }
- return (temp);
- }
- internal static DateTimeFormatInfo GetTaiwanCalendarDTFI() {
- DateTimeFormatInfo temp = s_zhtwDTFI;
- if (temp == null) {
- temp = new CultureInfo("zh-TW", false).DateTimeFormat;
- temp.Calendar = TaiwanCalendar.GetDefaultInstance();
- s_zhtwDTFI = temp;
- }
- return (temp);
- }
-
-
- // DTFI properties should call this when the setter are called.
- private void ClearTokenHashTable()
- {
- m_dtfiTokenHash = null;
- formatFlags = DateTimeFormatFlags.NotInitialized;
- }
-
- internal TokenHashValue[] CreateTokenHashTable() {
- TokenHashValue[] temp = m_dtfiTokenHash;
- if (temp == null) {
- temp = new TokenHashValue[TOKEN_HASH_SIZE];
-
- bool koreanLanguage = LanguageName.Equals(KoreanLangName);
-
- string sep = this.TimeSeparator.Trim();
- if (IgnorableComma != sep) InsertHash(temp, IgnorableComma, TokenType.IgnorableSymbol, 0);
- if (IgnorablePeriod != sep) InsertHash(temp, IgnorablePeriod, TokenType.IgnorableSymbol, 0);
-
- if (KoreanHourSuff != sep && CJKHourSuff != sep && ChineseHourSuff != sep) {
- //
- // On the Macintosh, the default TimeSeparator is identical to the KoreanHourSuff, CJKHourSuff, or ChineseHourSuff for some cultures like
- // ja-JP and ko-KR. In these cases having the same symbol inserted into the hash table with multiple TokenTypes causes undesirable
- // DateTime.Parse behavior. For instance, the DateTimeFormatInfo.Tokenize() method might return SEP_DateOrOffset for KoreanHourSuff
- // instead of SEP_HourSuff.
- //
- InsertHash(temp, this.TimeSeparator, TokenType.SEP_Time, 0);
- }
-
- InsertHash(temp, this.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0);
- InsertHash(temp, this.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1);
-
- if (LanguageName.Equals("sq")) {
- // Albanian allows time formats like "12:00.PD"
- InsertHash(temp, IgnorablePeriod + this.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0);
- InsertHash(temp, IgnorablePeriod + this.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1);
- }
-
- // CJK suffix
- InsertHash(temp, CJKYearSuff, TokenType.SEP_YearSuff, 0);
- InsertHash(temp, KoreanYearSuff, TokenType.SEP_YearSuff, 0);
- InsertHash(temp, CJKMonthSuff, TokenType.SEP_MonthSuff, 0);
- InsertHash(temp, KoreanMonthSuff, TokenType.SEP_MonthSuff, 0);
- InsertHash(temp, CJKDaySuff, TokenType.SEP_DaySuff, 0);
- InsertHash(temp, KoreanDaySuff, TokenType.SEP_DaySuff, 0);
-
- InsertHash(temp, CJKHourSuff, TokenType.SEP_HourSuff, 0);
- InsertHash(temp, ChineseHourSuff, TokenType.SEP_HourSuff, 0);
- InsertHash(temp, CJKMinuteSuff, TokenType.SEP_MinuteSuff, 0);
- InsertHash(temp, CJKSecondSuff, TokenType.SEP_SecondSuff, 0);
-
- if (koreanLanguage) {
- // Korean suffix
- InsertHash(temp, KoreanHourSuff, TokenType.SEP_HourSuff, 0);
- InsertHash(temp, KoreanMinuteSuff, TokenType.SEP_MinuteSuff, 0);
- InsertHash(temp, KoreanSecondSuff, TokenType.SEP_SecondSuff, 0);
- }
-
- if ( LanguageName.Equals("ky")) {
- // For some cultures, the date separator works more like a comma, being allowed before or after any date part
- InsertHash(temp, dateSeparatorOrTimeZoneOffset, TokenType.IgnorableSymbol, 0);
- }
- else {
- InsertHash(temp, dateSeparatorOrTimeZoneOffset, TokenType.SEP_DateOrOffset, 0);
- }
-
- String[] dateWords = null;
- DateTimeFormatInfoScanner scanner = null;
-
- // We need to rescan the date words since we're always synthetic
- scanner = new DateTimeFormatInfoScanner();
- // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
- // The only reason they're being assigned to m_dateWords is for Whidbey Deserialization
- m_dateWords = dateWords = scanner.GetDateWordsOfDTFI(this);
- // Ensure the formatflags is initialized.
- DateTimeFormatFlags flag = FormatFlags;
-
- // For some cultures, the date separator works more like a comma, being allowed before or after any date part.
- // In these cultures, we do not use normal date separator since we disallow date separator after a date terminal state.
- // This is determined in DateTimeFormatInfoScanner. Use this flag to determine if we should treat date separator as ignorable symbol.
- bool useDateSepAsIgnorableSymbol = false;
-
- String monthPostfix = null;
- if (dateWords != null)
- {
- // There are DateWords. It could be a real date word (such as "de"), or a monthPostfix.
- // The monthPostfix starts with '\xfffe' (MonthPostfixChar), followed by the real monthPostfix.
- for (int i = 0; i < dateWords.Length; i++)
- {
- switch (dateWords[i][0])
- {
- // This is a month postfix
- case DateTimeFormatInfoScanner.MonthPostfixChar:
- // Get the real month postfix.
- monthPostfix = dateWords[i].Substring(1);
- // Add the month name + postfix into the token.
- AddMonthNames(temp, monthPostfix);
- break;
- case DateTimeFormatInfoScanner.IgnorableSymbolChar:
- String symbol = dateWords[i].Substring(1);
- InsertHash(temp, symbol, TokenType.IgnorableSymbol, 0);
- if (this.DateSeparator.Trim().Equals(symbol))
- {
- // The date separator is the same as the ingorable symbol.
- useDateSepAsIgnorableSymbol = true;
- }
- break;
- default:
- InsertHash(temp, dateWords[i], TokenType.DateWordToken, 0);
- if (LanguageName.Equals("eu")) {
- // Basque has date words with leading dots
- InsertHash(temp, IgnorablePeriod + dateWords[i], TokenType.DateWordToken, 0);
- }
- break;
- }
- }
- }
-
- if (!useDateSepAsIgnorableSymbol)
- {
- // Use the normal date separator.
- InsertHash(temp, this.DateSeparator, TokenType.SEP_Date, 0);
- }
- // Add the regular month names.
- AddMonthNames(temp, null);
-
- // Add the abbreviated month names.
- for (int i = 1; i <= 13; i++) {
- InsertHash(temp, GetAbbreviatedMonthName(i), TokenType.MonthToken, i);
- }
-
-
- if ((FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) {
- for (int i = 1; i <= 13; i++) {
- String str;
- str = internalGetMonthName(i, MonthNameStyles.Genitive, false);
- InsertHash(temp, str, TokenType.MonthToken, i);
- }
- }
-
- if ((FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) {
- for (int i = 1; i <= 13; i++) {
- String str;
- str = internalGetMonthName(i, MonthNameStyles.LeapYear, false);
- InsertHash(temp, str, TokenType.MonthToken, i);
- }
- }
-
- for (int i = 0; i < 7; i++) {
- //String str = GetDayOfWeekNames()[i];
- // We have to call public methods here to work with inherited DTFI.
- String str = GetDayName((DayOfWeek)i);
- InsertHash(temp, str, TokenType.DayOfWeekToken, i);
-
- str = GetAbbreviatedDayName((DayOfWeek)i);
- InsertHash(temp, str, TokenType.DayOfWeekToken, i);
-
- }
-
- int[] eras = calendar.Eras;
- for (int i = 1; i <= eras.Length; i++) {
- InsertHash(temp, GetEraName(i), TokenType.EraToken, i);
- InsertHash(temp, GetAbbreviatedEraName(i), TokenType.EraToken, i);
- }
-
- if (LanguageName.Equals(JapaneseLangName)) {
- // Japanese allows day of week forms like: "(Tue)"
- for (int i = 0; i < 7; i++) {
- String specialDayOfWeek = "(" + GetAbbreviatedDayName((DayOfWeek)i) + ")";
- InsertHash(temp, specialDayOfWeek, TokenType.DayOfWeekToken, i);
- }
- if (this.Calendar.GetType() != typeof(JapaneseCalendar)) {
- // Special case for Japanese. If this is a Japanese DTFI, and the calendar is not Japanese calendar,
- // we will check Japanese Era name as well when the calendar is Gregorian.
- DateTimeFormatInfo jaDtfi = GetJapaneseCalendarDTFI();
- for (int i = 1; i <= jaDtfi.Calendar.Eras.Length; i++) {
- InsertHash(temp, jaDtfi.GetEraName(i), TokenType.JapaneseEraToken, i);
- InsertHash(temp, jaDtfi.GetAbbreviatedEraName(i), TokenType.JapaneseEraToken, i);
- // m_abbrevEnglishEraNames[0] contains the name for era 1, so the token value is i+1.
- InsertHash(temp, jaDtfi.AbbreviatedEnglishEraNames[i-1], TokenType.JapaneseEraToken, i);
- }
- }
- }
- else if (CultureName.Equals("zh-TW")) {
- DateTimeFormatInfo twDtfi = GetTaiwanCalendarDTFI();
- for (int i = 1; i <= twDtfi.Calendar.Eras.Length; i++) {
- if (twDtfi.GetEraName(i).Length > 0) {
- InsertHash(temp, twDtfi.GetEraName(i), TokenType.TEraToken, i);
- }
- }
- }
-
- InsertHash(temp, InvariantInfo.AMDesignator, TokenType.SEP_Am | TokenType.Am, 0);
- InsertHash(temp, InvariantInfo.PMDesignator, TokenType.SEP_Pm | TokenType.Pm, 1);
-
- // Add invariant month names and day names.
- for (int i = 1; i <= 12; i++) {
- 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
- // month names.
- str = InvariantInfo.GetMonthName(i);
- InsertHash(temp, str, TokenType.MonthToken, i);
- str = InvariantInfo.GetAbbreviatedMonthName(i);
- InsertHash(temp, str, TokenType.MonthToken, i);
- }
-
- for (int i = 0; i < 7; i++) {
- // We have to call public methods here to work with inherited DTFI.
- String str = InvariantInfo.GetDayName((DayOfWeek)i);
- InsertHash(temp, str, TokenType.DayOfWeekToken, i);
-
- str = InvariantInfo.GetAbbreviatedDayName((DayOfWeek)i);
- InsertHash(temp, str, TokenType.DayOfWeekToken, i);
-
- }
-
- for (int i = 0; i < AbbreviatedEnglishEraNames.Length; i++) {
- // m_abbrevEnglishEraNames[0] contains the name for era 1, so the token value is i+1.
- InsertHash(temp, AbbreviatedEnglishEraNames[i], TokenType.EraToken, i + 1);
- }
-
- InsertHash(temp, LocalTimeMark, TokenType.SEP_LocalTimeMark, 0);
- InsertHash(temp, DateTimeParse.GMTName, TokenType.TimeZoneToken, 0);
- InsertHash(temp, DateTimeParse.ZuluName, TokenType.TimeZoneToken, 0);
-
- InsertHash(temp, invariantDateSeparator, TokenType.SEP_Date, 0);
- InsertHash(temp, invariantTimeSeparator, TokenType.SEP_Time, 0);
-
- m_dtfiTokenHash = temp;
- }
- return (temp);
- }
-
- private void AddMonthNames(TokenHashValue[] temp, String monthPostfix)
- {
- for (int i = 1; i <= 13; i++) {
- 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
- // month names.
- str = GetMonthName(i);
- if (str.Length > 0) {
- if (monthPostfix != null) {
- // Insert the month name with the postfix first, so it can be matched first.
- InsertHash(temp, str + monthPostfix, TokenType.MonthToken, i);
- } else
- {
- InsertHash(temp, str, TokenType.MonthToken, i);
- }
- }
- str = GetAbbreviatedMonthName(i);
- InsertHash(temp, str, TokenType.MonthToken, i);
- }
-
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Actions:
- // Try to parse the current word to see if it is a Hebrew number.
- // Tokens will be updated accordingly.
- // This is called by the Lexer of DateTime.Parse().
- //
- // Unlike most of the functions in this class, the return value indicates
- // whether or not it started to parse. The badFormat parameter indicates
- // if parsing began, but the format was bad.
- //
- ////////////////////////////////////////////////////////////////////////
-
- private static bool TryParseHebrewNumber(
- ref __DTString str,
- out Boolean badFormat,
- out int number) {
-
- number = -1;
- badFormat = false;
-
- int i = str.Index;
- if (!HebrewNumber.IsDigit(str.Value[i])) {
- // If the current character is not a Hebrew digit, just return false.
- // There is no chance that we can parse a valid Hebrew number from here.
- return (false);
- }
- // The current character is a Hebrew digit. Try to parse this word as a Hebrew number.
- HebrewNumberParsingContext context = new HebrewNumberParsingContext(0);
- HebrewNumberParsingState state;
-
- do {
- state = HebrewNumber.ParseByChar(str.Value[i++], ref context);
- switch (state) {
- case HebrewNumberParsingState.InvalidHebrewNumber: // Not a valid Hebrew number.
- case HebrewNumberParsingState.NotHebrewDigit: // The current character is not a Hebrew digit character.
- // Break out so that we don't continue to try parse this as a Hebrew number.
- return (false);
- }
- } while (i < str.Value.Length && (state != HebrewNumberParsingState.FoundEndOfHebrewNumber));
-
- // When we are here, we are either at the end of the string, or we find a valid Hebrew number.
- Debug.Assert(state == HebrewNumberParsingState.ContinueParsing || state == HebrewNumberParsingState.FoundEndOfHebrewNumber,
- "Invalid returned state from HebrewNumber.ParseByChar()");
-
- if (state != HebrewNumberParsingState.FoundEndOfHebrewNumber) {
- // We reach end of the string but we can't find a terminal state in parsing Hebrew number.
- return (false);
- }
-
- // We have found a valid Hebrew number. Update the index.
- str.Advance(i - str.Index);
-
- // Get the final Hebrew number value from the HebrewNumberParsingContext.
- number = context.result;
-
- return (true);
- }
-
- private static bool IsHebrewChar(char ch) {
- return (ch >= '\x0590' && ch <= '\x05ff');
- }
-
- internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str) {
- tokenType = TokenType.UnknownToken;
- tokenValue = 0;
-
- TokenHashValue value;
- Debug.Assert(str.Index < str.Value.Length, "DateTimeFormatInfo.Tokenize(): start < value.Length");
-
- char ch = str.m_current;
- bool isLetter = Char.IsLetter(ch);
- if (isLetter) {
- ch = Char.ToLower(ch, this.Culture);
- if (IsHebrewChar(ch) && TokenMask == TokenType.RegularTokenMask) {
- bool badFormat;
- if (TryParseHebrewNumber(ref str, out badFormat, out tokenValue)) {
- if (badFormat) {
- tokenType = TokenType.UnknownToken;
- return (false);
- }
- // This is a Hebrew number.
- // Do nothing here. TryParseHebrewNumber() will update token accordingly.
- tokenType = TokenType.HebrewNumber;
- return (true);
- }
- }
- }
-
-
- int hashcode = ch % TOKEN_HASH_SIZE;
- int hashProbe = 1 + ch % SECOND_PRIME;
- int remaining = str.len - str.Index;
- int i = 0;
-
- TokenHashValue[] hashTable = m_dtfiTokenHash;
- if (hashTable == null) {
- hashTable = CreateTokenHashTable();
- }
- do {
- value = hashTable[hashcode];
- if (value == null) {
- // Not found.
- break;
- }
- // Check this value has the right category (regular token or separator token) that we are looking for.
- if (((int)value.tokenType & (int)TokenMask) > 0 && value.tokenString.Length <= remaining) {
- if (String.Compare(str.Value, str.Index, value.tokenString, 0, value.tokenString.Length, this.Culture, CompareOptions.IgnoreCase)==0) {
- if (isLetter) {
- // If this token starts with a letter, make sure that we won't allow partial match. So you can't tokenize "MarchWed" separately.
- int nextCharIndex;
- if ((nextCharIndex = str.Index + value.tokenString.Length) < str.len) {
- // Check word boundary. The next character should NOT be a letter.
- char nextCh = str.Value[nextCharIndex];
- if (Char.IsLetter(nextCh)) {
- return (false);
- }
- }
- }
- tokenType = value.tokenType & TokenMask;
- tokenValue = value.tokenValue;
- str.Advance(value.tokenString.Length);
- return (true);
- } else if (value.tokenType == TokenType.MonthToken && HasSpacesInMonthNames) {
- // For month token, we will match the month names which have spaces.
- int matchStrLen = 0;
- if (str.MatchSpecifiedWords(value.tokenString, true, ref matchStrLen)) {
- tokenType = value.tokenType & TokenMask;
- tokenValue = value.tokenValue;
- str.Advance(matchStrLen);
- return (true);
- }
- } else if (value.tokenType == TokenType.DayOfWeekToken && HasSpacesInDayNames) {
- // For month token, we will match the month names which have spaces.
- int matchStrLen = 0;
- if (str.MatchSpecifiedWords(value.tokenString, true, ref matchStrLen)) {
- tokenType = value.tokenType & TokenMask;
- tokenValue = value.tokenValue;
- str.Advance(matchStrLen);
- return (true);
- }
- }
- }
- i++;
- hashcode += hashProbe;
- if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
- }while (i < TOKEN_HASH_SIZE);
-
- return (false);
- }
-
- void InsertAtCurrentHashNode(TokenHashValue[] hashTable, String str, char ch, TokenType tokenType, int tokenValue, int pos, int hashcode, int hashProbe) {
- // Remember the current slot.
- TokenHashValue previousNode = hashTable[hashcode];
-
- //// Console.WriteLine(" Insert Key: {0} in {1}", str, slotToInsert);
- // Insert the new node into the current slot.
- hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue);;
-
- while (++pos < TOKEN_HASH_SIZE) {
- hashcode += hashProbe;
- if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
- // Remember this slot
- TokenHashValue temp = hashTable[hashcode];
-
- if (temp != null && Char.ToLower(temp.tokenString[0], this.Culture) != ch) {
- continue;
- }
- // Put the previous slot into this slot.
- hashTable[hashcode] = previousNode;
- //// Console.WriteLine(" Move {0} to slot {1}", previousNode.tokenString, hashcode);
- if (temp == null) {
- // Done
- return;
- }
- previousNode = temp;
- } ;
- Debug.Assert(false, "The hashtable is full. This should not happen.");
- }
-
- void InsertHash(TokenHashValue[] hashTable, String str, TokenType tokenType, int tokenValue) {
- // The month of the 13th month is allowed to be null, so make sure that we ignore null value here.
- if (str == null || str.Length == 0) {
- return;
- }
- TokenHashValue value;
- int i = 0;
- // If there is whitespace characters in the beginning and end of the string, trim them since whitespaces are skipped by
- // DateTime.Parse().
- if (Char.IsWhiteSpace(str[0]) || Char.IsWhiteSpace(str[str.Length - 1])) {
- str = str.Trim(); // Trim white space characters.
- // Could have space for separators
- if (str.Length == 0)
- return;
- }
- char ch = Char.ToLower(str[0], this.Culture);
- int hashcode = ch % TOKEN_HASH_SIZE;
- int hashProbe = 1 + ch % SECOND_PRIME;
- do {
- value = hashTable[hashcode];
- if (value == null) {
- //// Console.WriteLine(" Put Key: {0} in {1}", str, hashcode);
- hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue);
- return;
- } else {
- // Collision happens. Find another slot.
- if (str.Length >= value.tokenString.Length) {
- // If there are two tokens with the same prefix, we have to make sure that the longer token should be at the front of
- // the shorter ones.
- if (String.Compare(str, 0, value.tokenString, 0, value.tokenString.Length, this.Culture, CompareOptions.IgnoreCase) == 0) {
- if (str.Length > value.tokenString.Length) {
- // The str to be inserted has the same prefix as the current token, and str is longer.
- // Insert str into this node, and shift every node behind it.
- InsertAtCurrentHashNode(hashTable, str, ch, tokenType, tokenValue, i, hashcode, hashProbe);
- return;
- } else {
- // Same token. If they have different types (regular token vs separator token). Add them.
- // If we have the same regular token or separator token in the hash already, do NOT update the hash.
- // Therefore, the order of inserting token is significant here regarding what tokenType will be kept in the hash.
-
-
- //
- // Check the current value of RegularToken (stored in the lower 8-bit of tokenType) , and insert the tokenType into the hash ONLY when we don't have a RegularToken yet.
- // Also check the current value of SeparatorToken (stored in the upper 8-bit of token), and insert the tokenType into the hash ONLY when we don't have the SeparatorToken yet.
- //
-
- int nTokenType = (int)tokenType;
- int nCurrentTokenTypeInHash = (int)value.tokenType;
-
- if (((nCurrentTokenTypeInHash & (int)TokenType.RegularTokenMask) == 0) && ((nTokenType & (int)TokenType.RegularTokenMask) != 0) ||
- ((nCurrentTokenTypeInHash & (int)TokenType.SeparatorTokenMask) == 0) && ((nTokenType & (int)TokenType.SeparatorTokenMask) != 0))
- {
- value.tokenType |= tokenType;
- if (tokenValue != 0)
- {
- value.tokenValue = tokenValue;
- }
- }
- // The token to be inserted is already in the table. Skip it.
- }
- }
- }
- }
- //// Console.WriteLine(" COLLISION. Old Key: {0}, New Key: {1}", hashTable[hashcode].tokenString, str);
- i++;
- hashcode += hashProbe;
- if (hashcode >= TOKEN_HASH_SIZE) hashcode -= TOKEN_HASH_SIZE;
- } while (i < TOKEN_HASH_SIZE);
- Debug.Assert(false, "The hashtable is full. This should not happen.");
- }
- } // class DateTimeFormatInfo
-
- internal class TokenHashValue {
- internal String tokenString;
- internal TokenType tokenType;
- internal int tokenValue;
-
- internal TokenHashValue(String tokenString, TokenType tokenType, int tokenValue) {
- this.tokenString = tokenString;
- this.tokenType = tokenType;
- this.tokenValue = tokenValue;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs b/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
deleted file mode 100644
index 4555bb2463..0000000000
--- a/src/mscorlib/src/System/Globalization/DateTimeFormatInfoScanner.cs
+++ /dev/null
@@ -1,747 +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.
-////////////////////////////////////////////////////////////////////////////
-//
-// DateTimeFormatInfoScanner
-//
-// Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse()
-//
-// The data includes:
-//
-// DateWords: such as "de" used in es-ES (Spanish) LongDatePattern.
-// Postfix: such as "ta" used in fi-FI after the month name.
-//
-// This class is shared among mscorlib.dll and sysglobl.dll.
-// Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between
-// methods for mscorlib.dll and sysglobl.dll.
-//
-////////////////////////////////////////////////////////////////////////////
-
-namespace System.Globalization
-{
- using System;
- using System.Globalization;
- using System.Collections;
- using System.Collections.Generic;
- using System.Text;
-
- //
- // from LocaleEx.txt header
- //
- //; IFORMATFLAGS
- //; Parsing/formatting flags.
- internal enum FORMATFLAGS {
- None = 0x00000000,
- UseGenitiveMonth = 0x00000001,
- UseLeapYearMonth = 0x00000002,
- UseSpacesInMonthNames = 0x00000004,
- UseHebrewParsing = 0x00000008,
- UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names.
- UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers.
- }
-
- //
- // To change in CalendarId you have to do the same change in Calendar.cs
- // To do: make the definintion shared between these two files.
- //
-
- internal enum CalendarId : ushort
- {
- GREGORIAN = 1 , // Gregorian (localized) calendar
- GREGORIAN_US = 2 , // Gregorian (U.S.) calendar
- JAPAN = 3 , // Japanese Emperor Era calendar
-/* SSS_WARNINGS_OFF */ TAIWAN = 4 , // Taiwan Era calendar /* SSS_WARNINGS_ON */
- KOREA = 5 , // Korean Tangun Era calendar
- HIJRI = 6 , // Hijri (Arabic Lunar) calendar
- THAI = 7 , // Thai calendar
- HEBREW = 8 , // Hebrew (Lunar) calendar
- GREGORIAN_ME_FRENCH = 9 , // Gregorian Middle East French calendar
- GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar
- GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar
- GREGORIAN_XLIT_FRENCH = 12,
-// Note that all calendars after this point are MANAGED ONLY for now.
- JULIAN = 13,
- JAPANESELUNISOLAR = 14,
- CHINESELUNISOLAR = 15,
- SAKA = 16, // reserved to match Office but not implemented in our code
- LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code
- LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code
- LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code
- KOREANLUNISOLAR = 20,
- TAIWANLUNISOLAR = 21,
- PERSIAN = 22,
- UMALQURA = 23,
- LAST_CALENDAR = 23 // Last calendar ID
- }
-
- internal class DateTimeFormatInfoScanner
- {
- // Special prefix-like flag char in DateWord array.
-
- // Use char in PUA area since we won't be using them in real data.
- // The char used to tell a read date word or a month postfix. A month postfix
- // is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI.
- // In this case, it will be stored as "\xfffeta" in the date word array.
- internal const char MonthPostfixChar = '\xe000';
-
- // Add ignorable symbol in a DateWord array.
-
- // hu-HU has:
- // shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
- // long date pattern: yyyy. MMMM d.
- // Here, "." is the date separator (derived from short date pattern). However,
- // "." also appear at the end of long date pattern. In this case, we just
- // "." as ignorable symbol so that the DateTime.Parse() state machine will not
- // treat the additional date separator at the end of y,m,d pattern as an error
- // condition.
- internal const char IgnorableSymbolChar = '\xe001';
-
- // Known CJK suffix
- internal const String CJKYearSuff = "\u5e74";
- internal const String CJKMonthSuff = "\u6708";
- internal const String CJKDaySuff = "\u65e5";
-
- internal const String KoreanYearSuff = "\ub144";
- internal const String KoreanMonthSuff = "\uc6d4";
- internal const String KoreanDaySuff = "\uc77c";
-
- internal const String KoreanHourSuff = "\uc2dc";
- internal const String KoreanMinuteSuff = "\ubd84";
- internal const String KoreanSecondSuff = "\ucd08";
-
- internal const String CJKHourSuff = "\u6642";
- internal const String ChineseHourSuff = "\u65f6";
-
- internal const String CJKMinuteSuff = "\u5206";
- internal const String CJKSecondSuff = "\u79d2";
-
- // The collection fo date words & postfix.
- internal List<String> m_dateWords = new List<String>();
- // Hashtable for the known words.
- private static volatile Dictionary<String, String> s_knownWords;
-
- static Dictionary<String, String> KnownWords
- {
- get
- {
- if (s_knownWords == null)
- {
- Dictionary<String, String> temp = new Dictionary<String, String>();
- // Add known words into the hash table.
-
- // Skip these special symbols.
- temp.Add("/", String.Empty);
- temp.Add("-", String.Empty);
- temp.Add(".", String.Empty);
- // Skip known CJK suffixes.
- temp.Add(CJKYearSuff, String.Empty);
- temp.Add(CJKMonthSuff, String.Empty);
- temp.Add(CJKDaySuff, String.Empty);
- temp.Add(KoreanYearSuff, String.Empty);
- temp.Add(KoreanMonthSuff, String.Empty);
- temp.Add(KoreanDaySuff, String.Empty);
- temp.Add(KoreanHourSuff, String.Empty);
- temp.Add(KoreanMinuteSuff, String.Empty);
- temp.Add(KoreanSecondSuff, String.Empty);
- temp.Add(CJKHourSuff, String.Empty);
- temp.Add(ChineseHourSuff, String.Empty);
- temp.Add(CJKMinuteSuff, String.Empty);
- temp.Add(CJKSecondSuff, String.Empty);
-
- s_knownWords = temp;
- }
- return (s_knownWords);
- }
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Parameters:
- // pattern: The pattern to be scanned.
- // currentIndex: the current index to start the scan.
- //
- // Returns:
- // Return the index with the first character that is a letter, which will
- // be the start of a date word.
- // Note that the index can be pattern.Length if we reach the end of the string.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static int SkipWhiteSpacesAndNonLetter(String pattern, int currentIndex)
- {
- while (currentIndex < pattern.Length)
- {
- char ch = pattern[currentIndex];
- if (ch == '\\')
- {
- // Escaped character. Look ahead one character.
- currentIndex++;
- if (currentIndex < pattern.Length)
- {
- ch = pattern[currentIndex];
- if (ch == '\'')
- {
- // Skip the leading single quote. We will
- // stop at the first letter.
- continue;
- }
- // Fall thru to check if this is a letter.
- } else
- {
- // End of string
- break;
- }
- }
- if (Char.IsLetter(ch) || ch == '\'' || ch == '.')
- {
- break;
- }
- // Skip the current char since it is not a letter.
- currentIndex++;
- }
- return (currentIndex);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // A helper to add the found date word or month postfix into ArrayList for date words.
- //
- // Parameters:
- // formatPostfix: What kind of postfix this is.
- // Possible values:
- // null: This is a regular date word
- // "MMMM": month postfix
- // word: The date word or postfix to be added.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal void AddDateWordOrPostfix(String formatPostfix, String str)
- {
- if (str.Length > 0)
- {
- // Some cultures use . like an abbreviation
- if (str.Equals("."))
- {
- AddIgnorableSymbols(".");
- return;
- }
- String words;
- if (KnownWords.TryGetValue(str, out words) == false)
- {
- if (m_dateWords == null)
- {
- m_dateWords = new List<String>();
- }
- if (formatPostfix == "MMMM")
- {
- // Add the word into the ArrayList as "\xfffe" + real month postfix.
- String temp = MonthPostfixChar + str;
- if (!m_dateWords.Contains(temp))
- {
- m_dateWords.Add(temp);
- }
- } else
- {
- if (!m_dateWords.Contains(str))
- {
- m_dateWords.Add(str);
- }
- if (str[str.Length - 1] == '.')
- {
- // Old version ignore the trialing dot in the date words. Support this as well.
- String strWithoutDot = str.Substring(0, str.Length - 1);
- if (!m_dateWords.Contains(strWithoutDot))
- {
- m_dateWords.Add(strWithoutDot);
- }
-
- }
- }
- }
- }
-
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Scan the pattern from the specified index and add the date word/postfix
- // when appropriate.
- //
- // Parameters:
- // pattern: The pattern to be scanned.
- // index: The starting index to be scanned.
- // formatPostfix: The kind of postfix to be scanned.
- // Possible values:
- // null: This is a regular date word
- // "MMMM": month postfix
- //
- //
- ////////////////////////////////////////////////////////////////////////////
- internal int AddDateWords(String pattern, int index, String formatPostfix)
- {
- // Skip any whitespaces so we will start from a letter.
- int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index);
- if (newIndex != index && formatPostfix != null)
- {
- // There are whitespaces. This will not be a postfix.
- formatPostfix = null;
- }
- index = newIndex;
-
- // This is the first char added into dateWord.
- // Skip all non-letter character. We will add the first letter into DateWord.
- StringBuilder dateWord = new StringBuilder();
- // We assume that date words should start with a letter.
- // Skip anything until we see a letter.
-
- while (index < pattern.Length)
- {
- char ch = pattern[index];
- if (ch == '\'')
- {
- // We have seen the end of quote. Add the word if we do not see it before,
- // and break the while loop.
- AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
- index++;
- break;
- } else if (ch == '\\')
- {
- //
- // Escaped character. Look ahead one character
- //
-
- // Skip escaped backslash.
- index++;
- if (index < pattern.Length)
- {
- dateWord.Append(pattern[index]);
- index++;
- }
- } else if (Char.IsWhiteSpace(ch))
- {
- // Found a whitespace. We have to add the current date word/postfix.
- AddDateWordOrPostfix(formatPostfix, dateWord.ToString());
- if (formatPostfix != null)
- {
- // Done with postfix. The rest will be regular date word.
- formatPostfix = null;
- }
- // Reset the dateWord.
- dateWord.Length = 0;
- index++;
- } else
- {
- dateWord.Append(ch);
- index++;
- }
- }
- return (index);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // A simple helper to find the repeat count for a specified char.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static int ScanRepeatChar(String pattern, char ch, int index, out int count)
- {
- count = 1;
- while (++index < pattern.Length && pattern[index] == ch) {
- count++;
- }
- // Return the updated position.
- return (index);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Add the text that is a date separator but is treated like ignroable symbol.
- // E.g.
- // hu-HU has:
- // shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd
- // long date pattern: yyyy. MMMM d.
- // Here, "." is the date separator (derived from short date pattern). However,
- // "." also appear at the end of long date pattern. In this case, we just
- // "." as ignorable symbol so that the DateTime.Parse() state machine will not
- // treat the additional date separator at the end of y,m,d pattern as an error
- // condition.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal void AddIgnorableSymbols(String text)
- {
- if (m_dateWords == null)
- {
- // Create the date word array.
- m_dateWords = new List<String>();
- }
- // Add the ingorable symbol into the ArrayList.
- String temp = IgnorableSymbolChar + text;
- if (!m_dateWords.Contains(temp))
- {
- m_dateWords.Add(temp);
- }
- }
-
-
- //
- // Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen.
- //
- enum FoundDatePattern
- {
- None = 0x0000,
- FoundYearPatternFlag = 0x0001,
- FoundMonthPatternFlag = 0x0002,
- FoundDayPatternFlag = 0x0004,
- FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag;
- }
-
- // Check if we have found all of the year/month/day pattern.
- FoundDatePattern m_ymdFlags = FoundDatePattern.None;
-
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Given a date format pattern, scan for date word or postfix.
- //
- // A date word should be always put in a single quoted string. And it will
- // start from a letter, so whitespace and symbols will be ignored before
- // the first letter.
- //
- // Examples of date word:
- // 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy
- // "\x0443." in bg-BG: dd.M.yyyy '\x0433.'
- //
- // Example of postfix:
- // month postfix:
- // "ta" in fi-FI: d. MMMM'ta 'yyyy
- // Currently, only month postfix is supported.
- //
- // Usage:
- // Always call this with Framework-style pattern, instead of Windows style pattern.
- // Windows style pattern uses '' for single quote, while .NET uses \'
- //
- ////////////////////////////////////////////////////////////////////////////
- internal void ScanDateWord(String pattern)
- {
-
- // Check if we have found all of the year/month/day pattern.
- m_ymdFlags = FoundDatePattern.None;
-
- int i = 0;
- while (i < pattern.Length)
- {
- char ch = pattern[i];
- int chCount;
-
- switch (ch)
- {
- case '\'':
- // Find a beginning quote. Search until the end quote.
- i = AddDateWords(pattern, i+1, null);
- break;
- case 'M':
- i = ScanRepeatChar(pattern, 'M', i, out chCount);
- if (chCount >= 4)
- {
- if (i < pattern.Length && pattern[i] == '\'')
- {
- i = AddDateWords(pattern, i+1, "MMMM");
- }
- }
- m_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag;
- break;
- case 'y':
- i = ScanRepeatChar(pattern, 'y', i, out chCount);
- m_ymdFlags |= FoundDatePattern.FoundYearPatternFlag;
- break;
- case 'd':
- i = ScanRepeatChar(pattern, 'd', i, out chCount);
- if (chCount <= 2)
- {
- // Only count "d" & "dd".
- // ddd, dddd are day names. Do not count them.
- m_ymdFlags |= FoundDatePattern.FoundDayPatternFlag;
- }
- break;
- case '\\':
- // Found a escaped char not in a quoted string. Skip the current backslash
- // and its next character.
- i += 2;
- break;
- case '.':
- if (m_ymdFlags == FoundDatePattern.FoundYMDPatternFlag)
- {
- // If we find a dot immediately after the we have seen all of the y, m, d pattern.
- // treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for
- // more details.
- AddIgnorableSymbols(".");
- m_ymdFlags = FoundDatePattern.None;
- }
- i++;
- break;
- default:
- if (m_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch))
- {
- // We are not seeing "." after YMD. Clear the flag.
- m_ymdFlags = FoundDatePattern.None;
- }
- // We are not in quote. Skip the current character.
- i++;
- break;
- }
- }
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Given a DTFI, get all of the date words from date patterns and time patterns.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) {
- // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix.
- String[] datePatterns = dtfi.GetAllDateTimePatterns('D');
- int i;
-
- // Scan the long date patterns
- for (i = 0; i < datePatterns.Length; i++)
- {
- ScanDateWord(datePatterns[i]);
- }
-
- // Scan the short date patterns
- datePatterns = dtfi.GetAllDateTimePatterns('d');
- for (i = 0; i < datePatterns.Length; i++)
- {
- ScanDateWord(datePatterns[i]);
- }
- // Scan the YearMonth patterns.
- datePatterns = dtfi.GetAllDateTimePatterns('y');
- for (i = 0; i < datePatterns.Length; i++)
- {
- ScanDateWord(datePatterns[i]);
- }
-
- // Scan the month/day pattern
- ScanDateWord(dtfi.MonthDayPattern);
-
- // Scan the long time patterns.
- datePatterns = dtfi.GetAllDateTimePatterns('T');
- for (i = 0; i < datePatterns.Length; i++)
- {
- ScanDateWord(datePatterns[i]);
- }
-
- // Scan the short time patterns.
- datePatterns = dtfi.GetAllDateTimePatterns('t');
- for (i = 0; i < datePatterns.Length; i++)
- {
- ScanDateWord(datePatterns[i]);
- }
-
- String[] result = null;
- if (m_dateWords != null && m_dateWords.Count > 0)
- {
- result = new String[m_dateWords.Count];
- for (i = 0; i < m_dateWords.Count; i++)
- {
- result[i] = m_dateWords[i];
- }
- }
- return (result);
- }
-
-#if ADDITIONAL_DTFI_SCANNER_METHODS
- ////////////////////////////////////////////////////////////////////////////
- //
- // Reset the date word ArrayList
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal void Reset()
- {
- m_dateWords.RemoveRange(0, m_dateWords.Count);
- }
-#endif
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Scan the month names to see if genitive month names are used, and return
- // the format flag.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static FORMATFLAGS GetFormatFlagGenitiveMonth(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames)
- {
- // If we have different names in regular and genitive month names, use genitive month flag.
- return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames))
- ? FORMATFLAGS.UseGenitiveMonth: 0);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Scan the month names to see if spaces are used or start with a digit, and return the format flag
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames)
- {
- FORMATFLAGS formatFlags = 0;
- formatFlags |= (ArrayElementsBeginWithDigit(monthNames) ||
- ArrayElementsBeginWithDigit(genitveMonthNames) ||
- ArrayElementsBeginWithDigit(abbrevMonthNames) ||
- ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)
- ? FORMATFLAGS.UseDigitPrefixInTokens : 0);
-
- formatFlags |= (ArrayElementsHaveSpace(monthNames) ||
- ArrayElementsHaveSpace(genitveMonthNames) ||
- ArrayElementsHaveSpace(abbrevMonthNames) ||
- ArrayElementsHaveSpace(genetiveAbbrevMonthNames)
- ? FORMATFLAGS.UseSpacesInMonthNames : 0);
- return (formatFlags);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Scan the day names and set the correct format flag.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames)
- {
- return ((ArrayElementsHaveSpace(dayNames) ||
- ArrayElementsHaveSpace(abbrevDayNames))
- ? FORMATFLAGS.UseSpacesInDayNames : 0);
-
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary.
- //
- ////////////////////////////////////////////////////////////////////////////
- internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID)
- {
- return (calID == (int)CalendarId.HEBREW ?
- FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0);
- }
-
-
- //-----------------------------------------------------------------------------
- // EqualStringArrays
- // compares two string arrays and return true if all elements of the first
- // array equals to all elmentsof the second array.
- // otherwise it returns false.
- //-----------------------------------------------------------------------------
-
- private static bool EqualStringArrays(string [] array1, string [] array2)
- {
- // Shortcut if they're the same array
- if (array1 == array2)
- {
- return true;
- }
-
- // This is effectively impossible
- if (array1.Length != array2.Length)
- {
- return false;
- }
-
- // Check each string
- for (int i=0; i<array1.Length; i++)
- {
- if (!array1[i].Equals(array2[i]))
- {
- return false;
- }
- }
-
- return true;
- }
-
- //-----------------------------------------------------------------------------
- // ArrayElementsHaveSpace
- // It checks all input array elements if any of them has space character
- // returns true if found space character in one of the array elements.
- // otherwise returns false.
- //-----------------------------------------------------------------------------
-
- private static bool ArrayElementsHaveSpace(string [] array)
- {
-
- for (int i=0; i<array.Length; i++)
- {
- // it is faster to check for space character manually instead of calling IndexOf
- // so we don't have to go to native code side.
- for (int j=0; j<array[i].Length; j++)
- {
- if ( Char.IsWhiteSpace(array[i][j]) )
- {
- return true;
- }
- }
- }
-
- return false;
- }
-
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Check if any element of the array start with a digit.
- //
- ////////////////////////////////////////////////////////////////////////////
- private static bool ArrayElementsBeginWithDigit(string [] array)
- {
-
- for (int i=0; i<array.Length; i++)
- {
- // it is faster to check for space character manually instead of calling IndexOf
- // so we don't have to go to native code side.
- if (array[i].Length > 0 &&
- array[i][0] >= '0' && array[i][0] <= '9')
- {
- int index = 1;
- while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9')
- {
- // Skip other digits.
- index++;
- }
- if (index == array[i].Length)
- {
- return (false);
- }
-
- if (index == array[i].Length - 1)
- {
- // Skip known CJK month suffix.
- // CJK uses month name like "1\x6708", since \x6708 is a known month suffix,
- // we don't need the UseDigitPrefixInTokens since it is slower.
- switch (array[i][index])
- {
- case '\x6708': // CJKMonthSuff
- case '\xc6d4': // KoreanMonthSuff
- return (false);
- }
- }
-
- if (index == array[i].Length - 4)
- {
- // Skip known CJK month suffix.
- // Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'"
- // instead of just "1\x6708"
- if(array[i][index] == '\'' && array[i][index + 1] == ' ' &&
- array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'')
- {
- return (false);
- }
-
- }
- return (true);
- }
- }
-
- return false;
- }
-
- }
-}
-
diff --git a/src/mscorlib/src/System/Globalization/DateTimeParse.cs b/src/mscorlib/src/System/Globalization/DateTimeParse.cs
deleted file mode 100644
index 363747cfc3..0000000000
--- a/src/mscorlib/src/System/Globalization/DateTimeParse.cs
+++ /dev/null
@@ -1,5035 +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 DateTime to parse a date/time string.
-//
-////////////////////////////////////////////////////////////////////////////
-
-namespace System {
- using System;
- using System.Text;
- using System.Globalization;
- using System.Threading;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////
-
- //This class contains only static members
-
- internal static
- class DateTimeParse {
-
- internal const Int32 MaxDateTimeNumberDigits = 8;
-
- internal delegate bool MatchNumberDelegate(ref __DTString str, int digitLen, out int result);
-
- internal static MatchNumberDelegate m_hebrewNumberParser = new MatchNumberDelegate(DateTimeParse.MatchHebrewDigits);
-
- internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style) {
- DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
- result.Init();
- if (TryParseExact(s, format, dtfi, style, ref result)) {
- return result.parsedDate;
- }
- else {
- throw GetDateTimeParseException(ref result);
- }
- }
-
- internal static DateTime ParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) {
- DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
- offset = TimeSpan.Zero;
- result.Init();
- result.flags |= ParseFlags.CaptureOffset;
- if (TryParseExact(s, format, dtfi, style, ref result)) {
- offset = result.timeZoneOffset;
- return result.parsedDate;
- }
- else {
- throw GetDateTimeParseException(ref result);
- }
- }
-
- internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) {
- result = DateTime.MinValue;
- DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
- resultData.Init();
- if (TryParseExact(s, format, dtfi, style, ref resultData)) {
- result = resultData.parsedDate;
- return true;
- }
- return false;
- }
-
- internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) {
- result = DateTime.MinValue;
- offset = TimeSpan.Zero;
- DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
- resultData.Init();
- resultData.flags |= ParseFlags.CaptureOffset;
- if (TryParseExact(s, format, dtfi, style, ref resultData)) {
- result = resultData.parsedDate;
- offset = resultData.timeZoneOffset;
- return true;
- }
- return false;
- }
-
- internal static bool TryParseExact(String s, String format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) {
- if (s == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
- return false;
- }
- if (format == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
- return false;
- }
- if (s.Length == 0) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- if (format.Length == 0) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
- return false;
- }
-
- Debug.Assert(dtfi != null, "dtfi == null");
-
- return DoStrictParse(s, format, style, dtfi, ref result);
- }
-
- internal static DateTime ParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style) {
- DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
- result.Init();
- if (TryParseExactMultiple(s, formats, dtfi, style, ref result)) {
- return result.parsedDate;
- }
- else {
- throw GetDateTimeParseException(ref result);
- }
- }
-
-
- internal static DateTime ParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) {
- DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
- offset = TimeSpan.Zero;
- result.Init();
- result.flags |= ParseFlags.CaptureOffset;
- if (TryParseExactMultiple(s, formats, dtfi, style, ref result)) {
- offset = result.timeZoneOffset;
- return result.parsedDate;
- }
- else {
- throw GetDateTimeParseException(ref result);
- }
- }
-
- internal static bool TryParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) {
- result = DateTime.MinValue;
- offset = TimeSpan.Zero;
- DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
- resultData.Init();
- resultData.flags |= ParseFlags.CaptureOffset;
- if (TryParseExactMultiple(s, formats, dtfi, style, ref resultData)) {
- result = resultData.parsedDate;
- offset = resultData.timeZoneOffset;
- return true;
- }
- return false;
- }
-
-
- internal static bool TryParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) {
- result = DateTime.MinValue;
- DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
- resultData.Init();
- if (TryParseExactMultiple(s, formats, dtfi, style, ref resultData)) {
- result = resultData.parsedDate;
- return true;
- }
- return false;
- }
-
- internal static bool TryParseExactMultiple(String s, String[] formats,
- DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) {
- if (s == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
- return false;
- }
- if (formats == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
- return false;
- }
-
- if (s.Length == 0) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- if (formats.Length == 0) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
- return false;
- }
-
- Debug.Assert(dtfi != null, "dtfi == null");
-
- //
- // 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", null);
- return false;
- }
- // Create a new result each time to ensure the runs are independent. Carry through
- // flags from the caller and return the result.
- DateTimeResult innerResult = new DateTimeResult(); // The buffer to store the parsing result.
- innerResult.Init();
- innerResult.flags = result.flags;
- if (TryParseExact(s, formats[i], dtfi, style, ref innerResult)) {
- result.parsedDate = innerResult.parsedDate;
- result.timeZoneOffset = innerResult.timeZoneOffset;
- return (true);
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
-
- ////////////////////////////////////////////////////////////////////////////
- // Date Token Types
- //
- // Following is the set of tokens that can be generated from a date
- // string. Notice that the legal set of trailing separators have been
- // folded in with the date number, and month name tokens. This set
- // of tokens is chosen to reduce the number of date parse states.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal enum DTT: int {
-
- End = 0, // '\0'
- NumEnd = 1, // Num[ ]*[\0]
- NumAmpm = 2, // Num[ ]+AmPm
- NumSpace = 3, // Num[ ]+^[Dsep|Tsep|'0\']
- NumDatesep = 4, // Num[ ]*Dsep
- NumTimesep = 5, // Num[ ]*Tsep
- MonthEnd = 6, // Month[ ]*'\0'
- MonthSpace = 7, // Month[ ]+^[Dsep|Tsep|'\0']
- MonthDatesep = 8, // Month[ ]*Dsep
- NumDatesuff = 9, // Month[ ]*DSuff
- NumTimesuff = 10, // Month[ ]*TSuff
- DayOfWeek = 11, // Day of week name
- YearSpace = 12, // Year+^[Dsep|Tsep|'0\']
- YearDateSep = 13, // Year+Dsep
- YearEnd = 14, // Year+['\0']
- TimeZone = 15, // timezone name
- Era = 16, // era name
- NumUTCTimeMark = 17, // Num + 'Z'
- // When you add a new token which will be in the
- // state table, add it after NumLocalTimeMark.
- Unk = 18, // unknown
- NumLocalTimeMark = 19, // Num + 'T'
- Max = 20, // marker
- }
-
- internal enum TM {
- NotSet = -1,
- AM = 0,
- PM = 1,
- }
-
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // DateTime parsing state enumeration (DS.*)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal enum DS {
- BEGIN = 0,
- N = 1, // have one number
- NN = 2, // have two numbers
-
- // The following are known to be part of a date
-
- D_Nd = 3, // date string: have number followed by date separator
- D_NN = 4, // date string: have two numbers
- D_NNd = 5, // date string: have two numbers followed by date separator
-
- D_M = 6, // date string: have a month
- D_MN = 7, // date string: have a month and a number
- D_NM = 8, // date string: have a number and a month
- D_MNd = 9, // date string: have a month and number followed by date separator
- D_NDS = 10, // date string: have one number followed a date suffix.
-
- D_Y = 11, // date string: have a year.
- D_YN = 12, // date string: have a year and a number
- D_YNd = 13, // date string: have a year and a number and a date separator
- D_YM = 14, // date string: have a year and a month
- D_YMd = 15, // date string: have a year and a month and a date separator
- D_S = 16, // have numbers followed by a date suffix.
- T_S = 17, // have numbers followed by a time suffix.
-
- // The following are known to be part of a time
-
- T_Nt = 18, // have num followed by time separator
- T_NNt = 19, // have two numbers followed by time separator
-
-
- ERROR = 20,
-
- // The following are terminal states. These all have an action
- // associated with them; and transition back to BEGIN.
-
- DX_NN = 21, // day from two numbers
- DX_NNN = 22, // day from three numbers
- DX_MN = 23, // day from month and one number
- DX_NM = 24, // day from month and one number
- DX_MNN = 25, // day from month and two numbers
- DX_DS = 26, // a set of date suffixed numbers.
- DX_DSN = 27, // day from date suffixes and one number.
- DX_NDS = 28, // day from one number and date suffixes .
- DX_NNDS = 29, // day from one number and date suffixes .
-
- DX_YNN = 30, // date string: have a year and two number
- DX_YMN = 31, // date string: have a year, a month, and a number.
- DX_YN = 32, // date string: have a year and one number
- DX_YM = 33, // date string: have a year, a month.
- TX_N = 34, // time from one number (must have ampm)
- TX_NN = 35, // time from two numbers
- TX_NNN = 36, // time from three numbers
- TX_TS = 37, // a set of time suffixed numbers.
- DX_NNY = 38,
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // NOTE: The following state machine table is dependent on the order of the
- // DS and DTT enumerations.
- //
- // For each non terminal state, the following table defines the next state
- // for each given date token type.
- //
- ////////////////////////////////////////////////////////////////////////////
-
-// End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCTimeMark
-private static DS[][] dateParsingStates = {
-// DS.BEGIN // DS.BEGIN
-new DS[] { DS.BEGIN, DS.ERROR, DS.TX_N, DS.N, DS.D_Nd, DS.T_Nt, DS.ERROR, DS.D_M, DS.D_M, DS.D_S, DS.T_S, DS.BEGIN, DS.D_Y, DS.D_Y, DS.ERROR, DS.BEGIN, DS.BEGIN, DS.ERROR},
-
-// DS.N // DS.N
-new DS[] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_NM, DS.D_MNd, DS.D_NDS, DS.ERROR, DS.N, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.N, DS.N, DS.ERROR},
-
-// DS.NN // DS.NN
-new DS[] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.T_S, DS.NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.NN, DS.NN, DS.ERROR},
-
-// DS.D_Nd // DS.D_Nd
-new DS[] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.D_NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.D_Nd, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.ERROR, DS.D_Nd, DS.ERROR},
-
-// DS.D_NN // DS.D_NN
-new DS[] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NN, DS.ERROR},
-
-// DS.D_NNd // DS.D_NNd
-new DS[] { DS.ERROR, DS.DX_NNN, DS.DX_NNN, DS.DX_NNN, DS.ERROR, DS.ERROR, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.ERROR, DS.D_NNd, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NNd, DS.ERROR},
-
-// DS.D_M // DS.D_M
-new DS[] { DS.ERROR, DS.DX_MN, DS.ERROR, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_M, DS.D_YM, DS.D_YMd, DS.DX_YM, DS.ERROR, DS.D_M, DS.ERROR},
-
-// DS.D_MN // DS.D_MN
-new DS[] { DS.DX_MN, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_MN, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MN, DS.ERROR},
-
-// DS.D_NM // DS.D_NM
-new DS[] { DS.DX_NM, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NM, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_NM, DS.ERROR},
-
-// DS.D_MNd // DS.D_MNd
-new DS[] { DS.ERROR, DS.DX_MNN, DS.ERROR, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_MNd, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MNd, DS.ERROR},
-
-// DS.D_NDS, // DS.D_NDS,
-new DS[] { DS.DX_NDS,DS.DX_NNDS, DS.DX_NNDS, DS.DX_NNDS, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.T_S, DS.D_NDS, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.ERROR},
-
-// DS.D_Y // DS.D_Y
-new DS[] { DS.ERROR, DS.DX_YN, DS.ERROR, DS.D_YN, DS.D_YNd, DS.ERROR, DS.DX_YM, DS.D_YM, DS.D_YMd, DS.D_YM, DS.ERROR, DS.D_Y, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_Y, DS.ERROR},
-
-// DS.D_YN // DS.D_YN
-new DS[] { DS.DX_YN, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR},
-
-// DS.D_YNd // DS.D_YNd
-new DS[] { DS.ERROR, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR},
-
-// DS.D_YM // DS.D_YM
-new DS[] { DS.DX_YM, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR},
-
-// DS.D_YMd // DS.D_YMd
-new DS[] { DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR},
-
-// DS.D_S // DS.D_S
-new DS[] { DS.DX_DS, DS.DX_DSN, DS.TX_N, DS.T_Nt, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.D_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.ERROR},
-
-// DS.T_S // DS.T_S
-new DS[] { DS.TX_TS, DS.TX_TS, DS.TX_TS, DS.T_Nt, DS.D_Nd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_S, DS.ERROR},
-
-// DS.T_Nt // DS.T_Nt
-new DS[] { DS.ERROR, DS.TX_NN, DS.TX_NN, DS.TX_NN, DS.ERROR, DS.T_NNt, DS.DX_NM, DS.D_NM, DS.ERROR, DS.ERROR, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_Nt, DS.T_Nt, DS.TX_NN},
-
-// DS.T_NNt // DS.T_NNt
-new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_NNt, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_NNt, DS.T_NNt, DS.TX_NNN},
-
-};
-// End NumEnd NumAmPm NumSpace NumDaySep NumTimesep MonthEnd MonthSpace MonthDSep NumDateSuff NumTimeSuff DayOfWeek YearSpace YearDateSep YearEnd TimeZone Era UTCMark
-
- internal const String GMTName = "GMT";
- internal const String ZuluName = "Z";
-
- //
- // Search from the index of str at str.Index to see if the target string exists in the str.
- //
- private static bool MatchWord(ref __DTString str, String target)
- {
- int length = target.Length;
- if (length > (str.Value.Length - str.Index)) {
- return false;
- }
-
- if (str.CompareInfo.Compare(str.Value, str.Index, length,
- target, 0, length, CompareOptions.IgnoreCase)!=0) {
- return (false);
- }
-
- int nextCharIndex = str.Index + target.Length;
-
- if (nextCharIndex < str.Value.Length) {
- char nextCh = str.Value[nextCharIndex];
- if (Char.IsLetter(nextCh)) {
- return (false);
- }
- }
- str.Index = nextCharIndex;
- if (str.Index < str.len) {
- str.m_current = str.Value[str.Index];
- }
-
- return (true);
- }
-
-
- //
- // Check the word at the current index to see if it matches GMT name or Zulu name.
- //
- private static bool GetTimeZoneName(ref __DTString str)
- {
- if (MatchWord(ref str, GMTName)) {
- return (true);
- }
-
- if (MatchWord(ref str, ZuluName)) {
- return (true);
- }
-
- return (false);
- }
-
- internal static bool IsDigit(char ch) {
- return (ch >= '0' && ch <= '9');
- }
-
-
- /*=================================ParseFraction==========================
- **Action: Starting at the str.Index, which should be a decimal symbol.
- ** if the current character is a digit, parse the remaining
- ** numbers as fraction. For example, if the sub-string starting at str.Index is "123", then
- ** the method will return 0.123
- **Returns: The fraction number.
- **Arguments:
- ** str the parsing string
- **Exceptions:
- ============================================================================*/
-
- private static bool ParseFraction(ref __DTString str, out double result) {
- result = 0;
- double decimalBase = 0.1;
- int digits = 0;
- char ch;
- while (str.GetNext()
- && IsDigit(ch = str.m_current)) {
- result += (ch - '0') * decimalBase;
- decimalBase *= 0.1;
- digits++;
- }
- return (digits > 0);
- }
-
- /*=================================ParseTimeZone==========================
- **Action: Parse the timezone offset in the following format:
- ** "+8", "+08", "+0800", "+0800"
- ** This method is used by DateTime.Parse().
- **Returns: The TimeZone offset.
- **Arguments:
- ** str the parsing string
- **Exceptions:
- ** FormatException if invalid timezone format is found.
- ============================================================================*/
-
- private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result) {
- // The hour/minute offset for timezone.
- int hourOffset = 0;
- int minuteOffset = 0;
- DTSubString sub;
-
- // Consume the +/- character that has already been read
- sub = str.GetSubString();
- if (sub.length != 1) {
- return false;
- }
- char offsetChar = sub[0];
- if (offsetChar != '+' && offsetChar != '-') {
- return false;
- }
- str.ConsumeSubString(sub);
-
- sub = str.GetSubString();
- if (sub.type != DTSubStringType.Number) {
- return false;
- }
- int value = sub.value;
- int length = sub.length;
- if (length == 1 || length == 2) {
- // Parsing "+8" or "+08"
- hourOffset = value;
- str.ConsumeSubString(sub);
- // See if we have minutes
- sub = str.GetSubString();
- if (sub.length == 1 && sub[0] == ':') {
- // Parsing "+8:00" or "+08:00"
- str.ConsumeSubString(sub);
- sub = str.GetSubString();
- if (sub.type != DTSubStringType.Number || sub.length < 1 || sub.length > 2) {
- return false;
- }
- minuteOffset = sub.value;
- str.ConsumeSubString(sub);
- }
- }
- else if (length == 3 || length == 4) {
- // Parsing "+800" or "+0800"
- hourOffset = value / 100;
- minuteOffset = value % 100;
- str.ConsumeSubString(sub);
- }
- else {
- // Wrong number of digits
- return false;
- }
- Debug.Assert(hourOffset >= 0 && hourOffset <= 99, "hourOffset >= 0 && hourOffset <= 99");
- Debug.Assert(minuteOffset >= 0 && minuteOffset <= 99, "minuteOffset >= 0 && minuteOffset <= 99");
- if (minuteOffset < 0 || minuteOffset >= 60) {
- return false;
- }
-
- result = new TimeSpan(hourOffset, minuteOffset, 0);
- if (offsetChar == '-') {
- result = result.Negate();
- }
- return true;
- }
-
- // This is the helper function to handle timezone in string in the format like +/-0800
- private static bool HandleTimeZone(ref __DTString str, ref DateTimeResult result)
- {
- if ((str.Index < str.len - 1)) {
- char nextCh = str.Value[str.Index];
- // Skip whitespace, but don't update the index unless we find a time zone marker
- int whitespaceCount = 0;
- while (Char.IsWhiteSpace(nextCh) && str.Index + whitespaceCount < str.len - 1) {
- whitespaceCount++;
- nextCh = str.Value[str.Index + whitespaceCount];
- }
- if (nextCh == '+' || nextCh == '-') {
- str.Index += whitespaceCount;
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0) {
- // Should not have two timezone offsets.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- result.flags |= ParseFlags.TimeZoneUsed;
- if (!ParseTimeZone(ref str, ref result.timeZoneOffset)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- }
- }
- return true;
- }
-
- //
- // This is the lexer. Check the character at the current index, and put the found token in dtok and
- // some raw date/time information in raw.
- //
- private static Boolean Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles)
- {
-
- TokenType tokenType;
- int tokenValue;
- int indexBeforeSeparator;
- char charBeforeSeparator;
-
- TokenType sep;
- dtok.dtt = DTT.Unk; // Assume the token is unkown.
-
- str.GetRegularToken(out tokenType, out tokenValue, dtfi);
-
-#if _LOGGING
- // Builds with _LOGGING defined (x86dbg, amd64chk, etc) support tracing
- // Set the following internal-only/unsupported environment variables to enable DateTime tracing to the console:
- //
- // COMPlus_LogEnable=1
- // COMPlus_LogToConsole=1
- // COMPlus_LogLevel=9
- // COMPlus_ManagedLogFacility=0x00001000
- if (_tracingEnabled) {
- BCLDebug.Trace("DATETIME", "[DATETIME] Lex({0})\tpos:{1}({2}), {3}, DS.{4}", Hex(str.Value),
- str.Index, Hex(str.m_current), tokenType, dps);
- }
-#endif // _LOGGING
-
- // Look at the regular token.
- switch (tokenType) {
- case TokenType.NumberToken:
- case TokenType.YearNumberToken:
- if (raw.numCount == 3 || tokenValue == -1) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0010", dps);
- return false;
- }
- //
- // This is a digit.
- //
- // If the previous parsing state is DS.T_NNt (like 12:01), and we got another number,
- // so we will have a terminal state DS.TX_NNN (like 12:01:02).
- // If the previous parsing state is DS.T_Nt (like 12:), and we got another number,
- // so we will have a terminal state DS.TX_NN (like 12:01).
- //
- // Look ahead to see if the following character is a decimal point or timezone offset.
- // This enables us to parse time in the forms of:
- // "11:22:33.1234" or "11:22:33-08".
- if (dps == DS.T_NNt) {
- if ((str.Index < str.len - 1)) {
- char nextCh = str.Value[str.Index];
- if (nextCh == '.') {
- // While ParseFraction can fail, it just means that there were no digits after
- // the dot. In this case ParseFraction just removes the dot. This is actually
- // valid for cultures like Albanian, that join the time marker to the time with
- // with a dot: e.g. "9:03.MD"
- ParseFraction(ref str, out raw.fraction);
- }
- }
- }
- if (dps == DS.T_NNt || dps == DS.T_Nt) {
- if ((str.Index < str.len - 1)) {
- if (false == HandleTimeZone(ref str, ref result))
- {
- LexTraceExit("0020 (value like \"12:01\" or \"12:\" followed by a non-TZ number", dps);
- return false;
- }
- }
- }
-
- dtok.num = tokenValue;
- if (tokenType == TokenType.YearNumberToken)
- {
- if (raw.year == -1)
- {
- raw.year = tokenValue;
- //
- // If we have number which has 3 or more digits (like "001" or "0001"),
- // we assume this number is a year. Save the currnet raw.numCount in
- // raw.year.
- //
- switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) {
- case TokenType.SEP_End:
- dtok.dtt = DTT.YearEnd;
- break;
- case TokenType.SEP_Am:
- case TokenType.SEP_Pm:
- if (raw.timeMark == TM.NotSet) {
- raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
- dtok.dtt = DTT.YearSpace;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0030 (TM.AM/TM.PM Happened more than 1x)", dps);
- }
- break;
- case TokenType.SEP_Space:
- dtok.dtt = DTT.YearSpace;
- break;
- case TokenType.SEP_Date:
- dtok.dtt = DTT.YearDateSep;
- break;
- case TokenType.SEP_Time:
- if (!raw.hasSameDateAndTimeSeparators)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0040 (Invalid separator after number)", dps);
- return false;
- }
-
- // we have the date and time separators are same and getting a year number, then change the token to YearDateSep as
- // we are sure we are not parsing time.
- dtok.dtt = DTT.YearDateSep;
- break;
- case TokenType.SEP_DateOrOffset:
- // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
- // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
- if ((dateParsingStates[(int)dps][(int) DTT.YearDateSep] == DS.ERROR)
- && (dateParsingStates[(int)dps][(int) DTT.YearSpace] > DS.ERROR)) {
- str.Index = indexBeforeSeparator;
- str.m_current = charBeforeSeparator;
- dtok.dtt = DTT.YearSpace;
- }
- else {
- dtok.dtt = DTT.YearDateSep;
- }
- break;
- case TokenType.SEP_YearSuff:
- case TokenType.SEP_MonthSuff:
- case TokenType.SEP_DaySuff:
- dtok.dtt = DTT.NumDatesuff;
- dtok.suffix = sep;
- break;
- case TokenType.SEP_HourSuff:
- case TokenType.SEP_MinuteSuff:
- case TokenType.SEP_SecondSuff:
- dtok.dtt = DTT.NumTimesuff;
- dtok.suffix = sep;
- break;
- default:
- // Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0040 (Invalid separator after number)", dps);
- return false;
- }
- //
- // Found the token already. Return now.
- //
- LexTraceExit("0050 (success)", dps);
- return true;
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0060", dps);
- return false;
- }
- switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
- {
- //
- // Note here we check if the numCount is less than three.
- // When we have more than three numbers, it will be caught as error in the state machine.
- //
- case TokenType.SEP_End:
- dtok.dtt = DTT.NumEnd;
- raw.AddNumber(dtok.num);
- break;
- case TokenType.SEP_Am:
- case TokenType.SEP_Pm:
- if (raw.timeMark == TM.NotSet) {
- raw.timeMark = (sep == TokenType.SEP_Am ? TM.AM : TM.PM);
- dtok.dtt = DTT.NumAmpm;
- // Fix AM/PM parsing case, e.g. "1/10 5 AM"
- if (dps == DS.D_NN)
- {
- if (!ProcessTerminaltState(DS.DX_NN, ref result, ref styles, ref raw, dtfi))
- {
- return false;
- }
- }
-
- raw.AddNumber(dtok.num);
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- break;
- }
- if (dps == DS.T_NNt || dps == DS.T_Nt) {
- if (false == HandleTimeZone(ref str, ref result))
- {
- LexTraceExit("0070 (HandleTimeZone returned false)", dps);
- return false;
- }
- }
- break;
- case TokenType.SEP_Space:
- dtok.dtt = DTT.NumSpace;
- raw.AddNumber(dtok.num);
- break;
- case TokenType.SEP_Date:
- dtok.dtt = DTT.NumDatesep;
- raw.AddNumber(dtok.num);
- break;
- case TokenType.SEP_DateOrOffset:
- // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
- // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
- if ((dateParsingStates[(int)dps][(int) DTT.NumDatesep] == DS.ERROR)
- && (dateParsingStates[(int)dps][(int) DTT.NumSpace] > DS.ERROR)) {
- str.Index = indexBeforeSeparator;
- str.m_current = charBeforeSeparator;
- dtok.dtt = DTT.NumSpace;
- }
- else {
- dtok.dtt = DTT.NumDatesep;
- }
- raw.AddNumber(dtok.num);
- break;
- case TokenType.SEP_Time:
- if (raw.hasSameDateAndTimeSeparators &&
- (dps == DS.D_Y || dps == DS.D_YN || dps == DS.D_YNd || dps == DS.D_YM || dps == DS.D_YMd))
- {
- // we are parsing a date and we have the time separator same as date separator, so we mark the token as date separator
- dtok.dtt = DTT.NumDatesep;
- raw.AddNumber(dtok.num);
- break;
- }
- dtok.dtt = DTT.NumTimesep;
- raw.AddNumber(dtok.num);
- break;
- case TokenType.SEP_YearSuff:
- try {
- dtok.num = dtfi.Calendar.ToFourDigitYear(tokenValue);
- }
- catch (ArgumentOutOfRangeException e) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", e);
- LexTraceExit("0075 (Calendar.ToFourDigitYear failed)", dps);
- return false;
- }
- dtok.dtt = DTT.NumDatesuff;
- dtok.suffix = sep;
- break;
- case TokenType.SEP_MonthSuff:
- case TokenType.SEP_DaySuff:
- dtok.dtt = DTT.NumDatesuff;
- dtok.suffix = sep;
- break;
- case TokenType.SEP_HourSuff:
- case TokenType.SEP_MinuteSuff:
- case TokenType.SEP_SecondSuff:
- dtok.dtt = DTT.NumTimesuff;
- dtok.suffix = sep;
- break;
- case TokenType.SEP_LocalTimeMark:
- dtok.dtt = DTT.NumLocalTimeMark;
- raw.AddNumber(dtok.num);
- break;
- default:
- // Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0080", dps);
- return false;
- }
- break;
- case TokenType.HebrewNumber:
- if (tokenValue >= 100) {
- // This is a year number
- if (raw.year == -1) {
- raw.year = tokenValue;
- //
- // If we have number which has 3 or more digits (like "001" or "0001"),
- // we assume this number is a year. Save the currnet raw.numCount in
- // raw.year.
- //
- switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) {
- case TokenType.SEP_End:
- dtok.dtt = DTT.YearEnd;
- break;
- case TokenType.SEP_Space:
- dtok.dtt = DTT.YearSpace;
- break;
- case TokenType.SEP_DateOrOffset:
- // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
- // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
- if (dateParsingStates[(int)dps][(int) DTT.YearSpace] > DS.ERROR) {
- str.Index = indexBeforeSeparator;
- str.m_current = charBeforeSeparator;
- dtok.dtt = DTT.YearSpace;
- break;
- }
- goto default;
- default:
- // Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0090", dps);
- return false;
- }
- } else {
- // Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0100", dps);
- return false;
- }
- } else {
- // This is a day number
- dtok.num = tokenValue;
- raw.AddNumber(dtok.num);
-
- switch (sep = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) {
- //
- // Note here we check if the numCount is less than three.
- // When we have more than three numbers, it will be caught as error in the state machine.
- //
- case TokenType.SEP_End:
- dtok.dtt = DTT.NumEnd;
- break;
- case TokenType.SEP_Space:
- case TokenType.SEP_Date:
- dtok.dtt = DTT.NumDatesep;
- break;
- case TokenType.SEP_DateOrOffset:
- // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
- // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
- if ((dateParsingStates[(int)dps][(int) DTT.NumDatesep] == DS.ERROR)
- && (dateParsingStates[(int)dps][(int) DTT.NumSpace] > DS.ERROR)) {
- str.Index = indexBeforeSeparator;
- str.m_current = charBeforeSeparator;
- dtok.dtt = DTT.NumSpace;
- }
- else {
- dtok.dtt = DTT.NumDatesep;
- }
- break;
- default:
- // Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0110", dps);
- return false;
- }
- }
- break;
- case TokenType.DayOfWeekToken:
- if (raw.dayOfWeek == -1)
- {
- //
- // This is a day of week name.
- //
- raw.dayOfWeek = tokenValue;
- dtok.dtt = DTT.DayOfWeek;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0120 (DayOfWeek seen more than 1x)", dps);
- return false;
- }
- break;
- case TokenType.MonthToken:
- if (raw.month == -1)
- {
- //
- // This is a month name
- //
- switch(sep=str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator))
- {
- case TokenType.SEP_End:
- dtok.dtt = DTT.MonthEnd;
- break;
- case TokenType.SEP_Space:
- dtok.dtt = DTT.MonthSpace;
- break;
- case TokenType.SEP_Date:
- dtok.dtt = DTT.MonthDatesep;
- break;
- case TokenType.SEP_Time:
- if (!raw.hasSameDateAndTimeSeparators)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0130 (Invalid separator after month name)", dps);
- return false;
- }
-
- // we have the date and time separators are same and getting a Month name, then change the token to MonthDatesep as
- // we are sure we are not parsing time.
- dtok.dtt = DTT.MonthDatesep;
- break;
- case TokenType.SEP_DateOrOffset:
- // The separator is either a date separator or the start of a time zone offset. If the token will complete the date then
- // process just the number and roll back the index so that the outer loop can attempt to parse the time zone offset.
- if ((dateParsingStates[(int)dps][(int) DTT.MonthDatesep] == DS.ERROR)
- && (dateParsingStates[(int)dps][(int) DTT.MonthSpace] > DS.ERROR)) {
- str.Index = indexBeforeSeparator;
- str.m_current = charBeforeSeparator;
- dtok.dtt = DTT.MonthSpace;
- }
- else {
- dtok.dtt = DTT.MonthDatesep;
- }
- break;
- default:
- //Invalid separator after month name
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0130 (Invalid separator after month name)", dps);
- return false;
- }
- raw.month = tokenValue;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0140 (MonthToken seen more than 1x)", dps);
- return false;
- }
- break;
- case TokenType.EraToken:
- if (result.era != -1) {
- result.era = tokenValue;
- dtok.dtt = DTT.Era;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0150 (EraToken seen when result.era already set)", dps);
- return false;
- }
- break;
- case TokenType.JapaneseEraToken:
- // Special case for Japanese. We allow Japanese era name to be used even if the calendar is not Japanese Calendar.
- result.calendar = JapaneseCalendar.GetDefaultInstance();
- dtfi = DateTimeFormatInfo.GetJapaneseCalendarDTFI();
- if (result.era != -1) {
- result.era = tokenValue;
- dtok.dtt = DTT.Era;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0160 (JapaneseEraToken seen when result.era already set)", dps);
- return false;
- }
- break;
- case TokenType.TEraToken:
- result.calendar = TaiwanCalendar.GetDefaultInstance();
- dtfi = DateTimeFormatInfo.GetTaiwanCalendarDTFI();
- if (result.era != -1) {
- result.era = tokenValue;
- dtok.dtt = DTT.Era;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0170 (TEraToken seen when result.era already set)", dps);
- return false;
- }
- break;
- case TokenType.TimeZoneToken:
- //
- // This is a timezone designator
- //
- // NOTENOTE : for now, we only support "GMT" and "Z" (for Zulu time).
- //
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0) {
- // Should not have two timezone offsets.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0180 (seen GMT or Z more than 1x)", dps);
- return false;
- }
- dtok.dtt = DTT.TimeZone;
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = new TimeSpan(0);
- result.flags |= ParseFlags.TimeZoneUtc;
- break;
- case TokenType.EndOfString:
- dtok.dtt = DTT.End;
- break;
- case TokenType.DateWordToken:
- case TokenType.IgnorableSymbol:
- // Date words and ignorable symbols can just be skipped over
- break;
- case TokenType.Am:
- case TokenType.Pm:
- if (raw.timeMark == TM.NotSet) {
- raw.timeMark = (TM)tokenValue;
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0190 (AM/PM timeMark already set)", dps);
- return false;
- }
- break;
- case TokenType.UnknownToken:
- if (Char.IsLetter(str.m_current)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_UnknowDateTimeWord", str.Index);
- LexTraceExit("0200", dps);
- return (false);
- }
-
- if ((str.m_current == '-' || str.m_current == '+') && ((result.flags & ParseFlags.TimeZoneUsed) == 0)) {
- Int32 originalIndex = str.Index;
- if (ParseTimeZone(ref str, ref result.timeZoneOffset)) {
- result.flags |= ParseFlags.TimeZoneUsed;
- LexTraceExit("0220 (success)", dps);
- return true;
- }
- else {
- // Time zone parse attempt failed. Fall through to punctuation handling.
- str.Index = originalIndex;
- }
- }
-
- // Visual Basic implements string to date conversions on top of DateTime.Parse:
- // CDate("#10/10/95#")
- //
- if (VerifyValidPunctuation(ref str)) {
- LexTraceExit("0230 (success)", dps);
- return true;
- }
-
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- LexTraceExit("0240", dps);
- return false;
- }
-
- LexTraceExit("0250 (success)", dps);
- return true;
- }
-
- private static Boolean VerifyValidPunctuation(ref __DTString str) {
- // Compatability Behavior. Allow trailing nulls and surrounding hashes
- Char ch = str.Value[str.Index];
- if (ch == '#') {
- bool foundStart = false;
- bool foundEnd = false;
- for (int i = 0; i < str.len; i++) {
- ch = str.Value[i];
- if (ch == '#') {
- if (foundStart) {
- if (foundEnd) {
- // Having more than two hashes is invalid
- return false;
- }
- else {
- foundEnd = true;
- }
- }
- else {
- foundStart = true;
- }
- }
- else if (ch == '\0') {
- // Allow nulls only at the end
- if (!foundEnd) {
- return false;
- }
- }
- else if ((!Char.IsWhiteSpace(ch))) {
- // Anthyhing other than whitespace outside hashes is invalid
- if (!foundStart || foundEnd) {
- return false;
- }
- }
- }
- if (!foundEnd) {
- // The has was un-paired
- return false;
- }
- // Valid Hash usage: eat the hash and continue.
- str.GetNext();
- return true;
- }
- else if (ch == '\0') {
- for (int i = str.Index; i < str.len; i++) {
- if (str.Value[i] != '\0') {
- // Nulls are only valid if they are the only trailing character
- return false;
- }
- }
- // Move to the end of the string
- str.Index = str.len;
- return true;
- }
- return false;
- }
-
- private const int ORDER_YMD = 0; // The order of date is Year/Month/Day.
- private const int ORDER_MDY = 1; // The order of date is Month/Day/Year.
- private const int ORDER_DMY = 2; // The order of date is Day/Month/Year.
- private const int ORDER_YDM = 3; // The order of date is Year/Day/Month
- private const int ORDER_YM = 4; // Year/Month order.
- private const int ORDER_MY = 5; // Month/Year order.
- private const int ORDER_MD = 6; // Month/Day order.
- private const int ORDER_DM = 7; // Day/Month order.
-
- //
- // Decide the year/month/day order from the datePattern.
- //
- // Return 0 for YMD, 1 for MDY, 2 for DMY, otherwise -1.
- //
- private static Boolean GetYearMonthDayOrder(String datePattern, DateTimeFormatInfo dtfi, out int order)
- {
- int yearOrder = -1;
- int monthOrder = -1;
- int dayOrder = -1;
- int orderCount = 0;
-
- bool inQuote = false;
-
- for (int i = 0; i < datePattern.Length && orderCount < 3; i++)
- {
- char ch = datePattern[i];
- if (ch == '\\' || ch == '%')
- {
- i++;
- continue; // Skip next character that is escaped by this backslash
- }
-
- if (ch == '\'' || ch == '"')
- {
- inQuote = !inQuote;
- }
-
- if (!inQuote)
- {
- if (ch == 'y')
- {
- yearOrder = orderCount++;
-
- //
- // Skip all year pattern charaters.
- //
- for(; i+1 < datePattern.Length && datePattern[i+1] == 'y'; i++)
- {
- // Do nothing here.
- }
- }
- else if (ch == 'M')
- {
- monthOrder = orderCount++;
- //
- // Skip all month pattern characters.
- //
- for(; i+1 < datePattern.Length && datePattern[i+1] == 'M'; i++)
- {
- // Do nothing here.
- }
- }
- else if (ch == 'd')
- {
-
- int patternCount = 1;
- //
- // Skip all day pattern characters.
- //
- for(; i+1 < datePattern.Length && datePattern[i+1] == 'd'; i++)
- {
- patternCount++;
- }
- //
- // Make sure this is not "ddd" or "dddd", which means day of week.
- //
- if (patternCount <= 2)
- {
- dayOrder = orderCount++;
- }
- }
- }
- }
-
- if (yearOrder == 0 && monthOrder == 1 && dayOrder == 2)
- {
- order = ORDER_YMD;
- return true;
- }
- if (monthOrder == 0 && dayOrder == 1 && yearOrder == 2)
- {
- order = ORDER_MDY;
- return true;
- }
- if (dayOrder == 0 && monthOrder == 1 && yearOrder == 2)
- {
- order = ORDER_DMY;
- return true;
- }
- if (yearOrder == 0 && dayOrder == 1 && monthOrder == 2)
- {
- order = ORDER_YDM;
- return true;
- }
- order = -1;
- return false;
- }
-
- //
- // Decide the year/month order from the pattern.
- //
- // Return 0 for YM, 1 for MY, otherwise -1.
- //
- private static Boolean GetYearMonthOrder(String pattern, DateTimeFormatInfo dtfi, out int order)
- {
- int yearOrder = -1;
- int monthOrder = -1;
- int orderCount = 0;
-
- bool inQuote = false;
- for (int i = 0; i < pattern.Length && orderCount < 2; i++)
- {
- char ch = pattern[i];
- if (ch == '\\' || ch == '%')
- {
- i++;
- continue; // Skip next character that is escaped by this backslash
- }
-
- if (ch == '\'' || ch == '"')
- {
- inQuote = !inQuote;
- }
-
- if (!inQuote)
- {
- if (ch == 'y')
- {
- yearOrder = orderCount++;
-
- //
- // Skip all year pattern charaters.
- //
- for(; i+1 < pattern.Length && pattern[i+1] == 'y'; i++)
- {
- }
- }
- else if (ch == 'M')
- {
- monthOrder = orderCount++;
- //
- // Skip all month pattern characters.
- //
- for(; i+1 < pattern.Length && pattern[i+1] == 'M'; i++)
- {
- }
- }
- }
- }
-
- if (yearOrder == 0 && monthOrder == 1)
- {
- order = ORDER_YM;
- return true;
- }
- if (monthOrder == 0 && yearOrder == 1)
- {
- order = ORDER_MY;
- return true;
- }
- order = -1;
- return false;
- }
-
- //
- // Decide the month/day order from the pattern.
- //
- // Return 0 for MD, 1 for DM, otherwise -1.
- //
- private static Boolean GetMonthDayOrder(String pattern, DateTimeFormatInfo dtfi, out int order)
- {
- int monthOrder = -1;
- int dayOrder = -1;
- int orderCount = 0;
-
- bool inQuote = false;
- for (int i = 0; i < pattern.Length && orderCount < 2; i++)
- {
- char ch = pattern[i];
- if (ch == '\\' || ch == '%')
- {
- i++;
- continue; // Skip next character that is escaped by this backslash
- }
-
- if (ch == '\'' || ch == '"')
- {
- inQuote = !inQuote;
- }
-
- if (!inQuote)
- {
- if (ch == 'd')
- {
- int patternCount = 1;
- //
- // Skip all day pattern charaters.
- //
- for(; i+1 < pattern.Length && pattern[i+1] == 'd'; i++)
- {
- patternCount++;
- }
-
- //
- // Make sure this is not "ddd" or "dddd", which means day of week.
- //
- if (patternCount <= 2)
- {
- dayOrder = orderCount++;
- }
-
- }
- else if (ch == 'M')
- {
- monthOrder = orderCount++;
- //
- // Skip all month pattern characters.
- //
- for(; i+1 < pattern.Length && pattern[i+1] == 'M'; i++)
- {
- }
- }
- }
- }
-
- if (monthOrder == 0 && dayOrder == 1)
- {
- order = ORDER_MD;
- return true;
- }
- if (dayOrder == 0 && monthOrder == 1)
- {
- order = ORDER_DM;
- return true;
- }
- order = -1;
- return false;
- }
-
- //
- // Adjust the two-digit year if necessary.
- //
- private static bool TryAdjustYear(ref DateTimeResult result, int year, out int adjustedYear)
- {
- if (year < 100)
- {
- try {
- // the Calendar classes need some real work. Many of the calendars that throw
- // don't implement a fast/non-allocating (and non-throwing) IsValid{Year|Day|Month} method.
- // we are making a targeted try/catch fix in the in-place release but will revisit this code
- // in the next side-by-side release.
- year = result.calendar.ToFourDigitYear(year);
- }
- catch (ArgumentOutOfRangeException) {
- adjustedYear = -1;
- return false;
- }
- }
- adjustedYear = year;
- return true;
- }
-
- private static bool SetDateYMD(ref DateTimeResult result, int year, int month, int day)
- {
- // Note, longer term these checks should be done at the end of the parse. This current
- // way of checking creates order dependence with parsing the era name.
- if (result.calendar.IsValidDay(year, month, day, result.era))
- {
- result.SetDate(year, month, day); // YMD
- return (true);
- }
- return (false);
- }
-
- private static bool SetDateMDY(ref DateTimeResult result, int month, int day, int year)
- {
- return (SetDateYMD(ref result, year, month, day));
- }
-
- private static bool SetDateDMY(ref DateTimeResult result, int day, int month, int year)
- {
- return (SetDateYMD(ref result, year, month, day));
- }
-
- private static bool SetDateYDM(ref DateTimeResult result, int year, int day, int month)
- {
- return (SetDateYMD(ref result, year, month, day));
- }
-
- private static void GetDefaultYear(ref DateTimeResult result, ref DateTimeStyles styles) {
- result.Year = result.calendar.GetYear(GetDateTimeNow(ref result, ref styles));
- result.flags |= ParseFlags.YearDefault;
- }
-
- // Processing teriminal case: DS.DX_NN
- private static Boolean GetDayOfNN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- int n1 = raw.GetNumber(0);
- int n2 = raw.GetNumber(1);
-
- GetDefaultYear(ref result, ref styles);
-
- int order;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out order)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
- return false;
- }
-
- if (order == ORDER_MD)
- {
- if (SetDateYMD(ref result, result.Year, n1, n2)) // MD
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- } else {
- // ORDER_DM
- if (SetDateYMD(ref result, result.Year, n2, n1)) // DM
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- // Processing teriminal case: DS.DX_NNN
- private static Boolean GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- int n1 = raw.GetNumber(0);
- int n2 = raw.GetNumber(1);;
- int n3 = raw.GetNumber(2);
-
- int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
- return false;
- }
- int year;
-
- if (order == ORDER_YMD) {
- if (TryAdjustYear(ref result, n1, out year) && SetDateYMD(ref result, year, n2, n3)) // YMD
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- } else if (order == ORDER_MDY) {
- if (TryAdjustYear(ref result, n3, out year) && SetDateMDY(ref result, n1, n2, year)) // MDY
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- } else if (order == ORDER_DMY) {
- if (TryAdjustYear(ref result, n3, out year) && SetDateDMY(ref result, n1, n2, year)) // DMY
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- } else if (order == ORDER_YDM) {
- if (TryAdjustYear(ref result, n1, out year) && SetDateYDM(ref result, year, n2, n3)) // YDM
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static Boolean GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- // The interpretation is based on the MonthDayPattern and YearMonthPattern
- //
- // MonthDayPattern YearMonthPattern Interpretation
- // --------------- ---------------- ---------------
- // MMMM dd MMMM yyyy Day
- // MMMM dd yyyy MMMM Day
- // dd MMMM MMMM yyyy Year
- // dd MMMM yyyy MMMM Day
- //
- // In the first and last cases, it could be either or neither, but a day is a better default interpretation
- // than a 2 digit year.
-
- int monthDayOrder;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
- return false;
- }
- if (monthDayOrder == ORDER_DM) {
- int yearMonthOrder;
- if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern);
- return false;
- }
- if (yearMonthOrder == ORDER_MY) {
- 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);
- return false;
- }
- return true;
- }
- }
-
- GetDefaultYear(ref result, ref styles);
- if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0))) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- return true;
-
- }
-
- ////////////////////////////////////////////////////////////////////////
- // Actions:
- // Deal with the terminal state for Hebrew Month/Day pattern
- //
- ////////////////////////////////////////////////////////////////////////
-
- private static Boolean GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
- int monthDayOrder;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
- return false;
- }
- result.Month = raw.month;
- if (monthDayOrder == ORDER_DM || monthDayOrder == ORDER_MD)
- {
- if (result.calendar.IsValidDay(result.Year, result.Month, raw.GetNumber(0), result.era))
- {
- result.Day = raw.GetNumber(0);
- return true;
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static Boolean GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- // The interpretation is based on the MonthDayPattern and YearMonthPattern
- //
- // MonthDayPattern YearMonthPattern Interpretation
- // --------------- ---------------- ---------------
- // MMMM dd MMMM yyyy Day
- // MMMM dd yyyy MMMM Year
- // dd MMMM MMMM yyyy Day
- // dd MMMM yyyy MMMM Day
- //
- // In the first and last cases, it could be either or neither, but a day is a better default interpretation
- // than a 2 digit year.
-
- int monthDayOrder;
- if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
- return false;
- }
- if (monthDayOrder == ORDER_MD) {
- int yearMonthOrder;
- if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern);
- return false;
- }
- if (yearMonthOrder == ORDER_YM) {
- 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);
- return false;
- }
- return true;
- }
- }
-
- GetDefaultYear(ref result, ref styles);
- if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0))) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- return true;
- }
-
- private static Boolean GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- int n1 = raw.GetNumber(0);
- int n2 = raw.GetNumber(1);
-
- int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
- return false;
- }
- int year;
-
- if (order == ORDER_MDY)
- {
- if (TryAdjustYear(ref result, n2, out year) && result.calendar.IsValidDay(year, raw.month, n1, result.era))
- {
- result.SetDate(year, raw.month, n1); // MDY
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- else if (TryAdjustYear(ref result, n1, out year) && result.calendar.IsValidDay(year, raw.month, n2, result.era))
- {
- result.SetDate(year, raw.month, n2); // YMD
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- }
- else if (order == ORDER_YMD)
- {
- if (TryAdjustYear(ref result, n1, out year) && result.calendar.IsValidDay(year, raw.month, n2, result.era))
- {
- result.SetDate(year, raw.month, n2); // YMD
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- else if (TryAdjustYear(ref result, n2, out year) && result.calendar.IsValidDay(year, raw.month, n1, result.era))
- {
- result.SetDate(year, raw.month, n1); // DMY
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- }
- else if (order == ORDER_DMY)
- {
- if (TryAdjustYear(ref result, n2, out year) && result.calendar.IsValidDay(year, raw.month, n1, result.era))
- {
- result.SetDate(year, raw.month, n1); // DMY
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- else if (TryAdjustYear(ref result, n1, out year) && result.calendar.IsValidDay(year, raw.month, n2, result.era))
- {
- result.SetDate(year, raw.month, n2); // YMD
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- }
-
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static Boolean GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- int n1 = raw.GetNumber(0);
- int n2 = raw.GetNumber(1);
- String pattern = dtfi.ShortDatePattern;
-
- // For compatibility, don't throw if we can't determine the order, but default to YMD instead
- int order;
- if (GetYearMonthDayOrder(pattern, dtfi, out order) && order == ORDER_YDM) {
- if (SetDateYMD(ref result, raw.year, n2, n1)) {
- result.flags |= ParseFlags.HaveDate;
- return true; // Year + DM
- }
- }
- else {
- if (SetDateYMD(ref result, raw.year, n1, n2)) {
- result.flags |= ParseFlags.HaveDate;
- return true; // Year + MD
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static Boolean GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- int n1 = raw.GetNumber(0);
- int n2 = raw.GetNumber(1);
-
- int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
- return false;
- }
-
- if (order == ORDER_MDY || order == ORDER_YMD) {
- if (SetDateYMD(ref result, raw.year, n1, n2)) {
- result.flags |= ParseFlags.HaveDate;
- return true; // MD + Year
- }
- } else {
- if (SetDateYMD(ref result, raw.year, n2, n1)) {
- result.flags |= ParseFlags.HaveDate;
- return true; // DM + Year
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
-
- private static Boolean GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
-
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- if (SetDateYMD(ref result, raw.year, raw.month, raw.GetNumber(0))) {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static Boolean GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- if (SetDateYMD(ref result, raw.year, raw.GetNumber(0), 1))
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static Boolean GetDayOfYM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
- if ((result.flags & ParseFlags.HaveDate) != 0) {
- // Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- if (SetDateYMD(ref result, raw.year, raw.month, 1))
- {
- result.flags |= ParseFlags.HaveDate;
- return true;
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- private static void AdjustTimeMark(DateTimeFormatInfo dtfi, ref DateTimeRawInfo raw) {
- // Specail case for culture which uses AM as empty string.
- // E.g. af-ZA (0x0436)
- // S1159 \x0000
- // S2359 nm
- // In this case, if we are parsing a string like "2005/09/14 12:23", we will assume this is in AM.
-
- if (raw.timeMark == TM.NotSet) {
- if (dtfi.AMDesignator != null && dtfi.PMDesignator != null) {
- if (dtfi.AMDesignator.Length == 0 && dtfi.PMDesignator.Length != 0) {
- raw.timeMark = TM.AM;
- }
- if (dtfi.PMDesignator.Length == 0 && dtfi.AMDesignator.Length != 0) {
- raw.timeMark = TM.PM;
- }
- }
- }
- }
-
- //
- // Adjust hour according to the time mark.
- //
- private static Boolean AdjustHour(ref int hour, TM timeMark) {
- if (timeMark != TM.NotSet) {
-
- if (timeMark == TM.AM) {
- if (hour < 0 || hour > 12) {
- return false;
- }
- hour = (hour == 12) ? 0 : hour;
- }
- else {
- if (hour < 0 || hour > 23) {
- return false;
- }
- if (hour < 12) {
- hour += 12;
- }
- }
- }
- return true;
- }
-
- private static Boolean GetTimeOfN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
- {
- if ((result.flags & ParseFlags.HaveTime) != 0) {
- // Multiple times in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- //
- // In this case, we need a time mark. Check if so.
- //
- if (raw.timeMark == TM.NotSet)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- result.Hour = raw.GetNumber(0);
- result.flags |= ParseFlags.HaveTime;
- return true;
- }
-
- private static Boolean GetTimeOfNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
- {
- Debug.Assert(raw.numCount >= 2, "raw.numCount >= 2");
- if ((result.flags & ParseFlags.HaveTime) != 0) {
- // Multiple times in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- result.Hour = raw.GetNumber(0);
- result.Minute = raw.GetNumber(1);
- result.flags |= ParseFlags.HaveTime;
- return true;
- }
-
- private static Boolean GetTimeOfNNN(DateTimeFormatInfo dtfi, ref DateTimeResult result, ref DateTimeRawInfo raw)
- {
- if ((result.flags & ParseFlags.HaveTime) != 0) {
- // Multiple times in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3");
- result.Hour = raw.GetNumber(0);
- result.Minute = raw.GetNumber(1);
- result.Second = raw.GetNumber(2);
- result.flags |= ParseFlags.HaveTime;
- return true;
- }
-
- //
- // Processing terminal state: A Date suffix followed by one number.
- //
- private static Boolean GetDateOfDSN(ref DateTimeResult result, ref DateTimeRawInfo raw)
- {
- if (raw.numCount != 1 || result.Day != -1)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- result.Day = raw.GetNumber(0);
- return true;
- }
-
- private static Boolean GetDateOfNDS(ref DateTimeResult result, ref DateTimeRawInfo raw)
- {
- if (result.Month == -1)
- {
- //Should have a month suffix
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- if (result.Year != -1)
- {
- // Aleady has a year suffix
- result.SetFailure(ParseFailureKind.Format, "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);
- return false;
- }
- result.Day = 1;
- return true;
- }
-
- private static Boolean GetDateOfNNDS(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
-
- // For partial CJK Dates, the only valid formats are with a specified year, followed by two numbers, which
- // will be the Month and Day, and with a specified Month, when the numbers are either the year and day or
- // day and year, depending on the short date pattern.
-
- if ((result.flags & ParseFlags.HaveYear) != 0) {
- if (((result.flags & ParseFlags.HaveMonth) == 0) && ((result.flags & ParseFlags.HaveDay) == 0)) {
- if (TryAdjustYear(ref result, raw.year, out result.Year) && SetDateYMD(ref result, result.Year, raw.GetNumber(0), raw.GetNumber(1))) {
- return true;
- }
- }
- }
- else if ((result.flags & ParseFlags.HaveMonth) != 0) {
- if (((result.flags & ParseFlags.HaveYear) == 0) && ((result.flags & ParseFlags.HaveDay) == 0)) {
- int order;
- if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order)) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
- return false;
- }
- int year;
- if (order == ORDER_YMD) {
- if (TryAdjustYear(ref result, raw.GetNumber(0), out year) && SetDateYMD(ref result, year, result.Month, raw.GetNumber(1))) {
- return true;
- }
- }
- else {
- if (TryAdjustYear(ref result, raw.GetNumber(1), out year) && SetDateYMD(ref result, year, result.Month, raw.GetNumber(0))){
- return true;
- }
- }
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- //
- // A date suffix is found, use this method to put the number into the result.
- //
- private static bool ProcessDateTimeSuffix(ref DateTimeResult result, ref DateTimeRawInfo raw, ref DateTimeToken dtok)
- {
- switch (dtok.suffix)
- {
- case TokenType.SEP_YearSuff:
- if ((result.flags & ParseFlags.HaveYear) != 0) {
- return false;
- }
- result.flags |= ParseFlags.HaveYear;
- result.Year = raw.year = dtok.num;
- break;
- case TokenType.SEP_MonthSuff:
- if ((result.flags & ParseFlags.HaveMonth) != 0) {
- return false;
- }
- result.flags |= ParseFlags.HaveMonth;
- result.Month= raw.month = dtok.num;
- break;
- case TokenType.SEP_DaySuff:
- if ((result.flags & ParseFlags.HaveDay) != 0) {
- return false;
- }
- result.flags |= ParseFlags.HaveDay;
- result.Day = dtok.num;
- break;
- case TokenType.SEP_HourSuff:
- if ((result.flags & ParseFlags.HaveHour) != 0) {
- return false;
- }
- result.flags |= ParseFlags.HaveHour;
- result.Hour = dtok.num;
- break;
- case TokenType.SEP_MinuteSuff:
- if ((result.flags & ParseFlags.HaveMinute) != 0) {
- return false;
- }
- result.flags |= ParseFlags.HaveMinute;
- result.Minute = dtok.num;
- break;
- case TokenType.SEP_SecondSuff:
- if ((result.flags & ParseFlags.HaveSecond) != 0) {
- return false;
- }
- result.flags |= ParseFlags.HaveSecond;
- result.Second = dtok.num;
- break;
- }
- return true;
-
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Actions:
- // This is used by DateTime.Parse().
- // Process the terminal state for the Hebrew calendar parsing.
- //
- ////////////////////////////////////////////////////////////////////////
-
- internal static Boolean ProcessHebrewTerminalState(DS dps, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) {
- // The following are accepted terminal state for Hebrew date.
- switch (dps) {
- case DS.DX_MNN:
- // Deal with the default long/short date format when the year number is ambigous (i.e. year < 100).
- raw.year = raw.GetNumber(1);
- if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true)) {
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
- return false;
- }
- if (!GetDayOfMNN(ref result, ref raw, dtfi)) {
- return false;
- }
- break;
- case DS.DX_YMN:
- // 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);
- return false;
- }
- if (!GetDayOfYMN(ref result, ref raw, dtfi)) {
- 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);
- return false;
- }
- if (!GetHebrewDayOfNM(ref result, ref raw, dtfi)) {
- return false;
- }
- break;
- case DS.DX_YM:
- // Deal with Year/Month pattern.
- if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true)) {
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
- return false;
- }
- if (!GetDayOfYM(ref result, ref raw, dtfi)) {
- return false;
- }
- break;
- case DS.TX_N:
- // Deal hour + AM/PM
- if (!GetTimeOfN(dtfi, ref result, ref raw)) {
- return false;
- }
- break;
- case DS.TX_NN:
- if (!GetTimeOfNN(dtfi, ref result, ref raw)) {
- return false;
- }
- break;
- case DS.TX_NNN:
- if (!GetTimeOfNNN(dtfi, ref result, ref raw)) {
- return false;
- }
- break;
- default:
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
-
- }
- if (dps > DS.ERROR)
- {
- //
- // We have reached a terminal state. Reset the raw num count.
- //
- raw.numCount = 0;
- }
- return true;
- }
-
- //
- // A terminal state has been reached, call the appropriate function to fill in the parsing result.
- // Return true if the state is a terminal state.
- //
- internal static Boolean ProcessTerminaltState(DS dps, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi)
- {
-
- bool passed = true;
- switch (dps)
- {
- case DS.DX_NN:
- passed = GetDayOfNN(ref result, ref styles, ref raw, dtfi);
- break;
- case DS.DX_NNN:
- passed = GetDayOfNNN(ref result, ref raw, dtfi);
- break;
- case DS.DX_MN:
- passed = GetDayOfMN(ref result, ref styles, ref raw, dtfi);
- break;
- case DS.DX_NM:
- passed = GetDayOfNM(ref result, ref styles, ref raw, dtfi);
- break;
- case DS.DX_MNN:
- passed = GetDayOfMNN(ref result, ref raw, dtfi);
- break;
- case DS.DX_DS:
- // The result has got the correct value. No need to process.
- passed = true;
- break;
- case DS.DX_YNN:
- passed = GetDayOfYNN(ref result, ref raw, dtfi);
- break;
- case DS.DX_NNY:
- passed = GetDayOfNNY(ref result, ref raw, dtfi);
- break;
- case DS.DX_YMN:
- passed = GetDayOfYMN(ref result, ref raw, dtfi);
- break;
- case DS.DX_YN:
- passed = GetDayOfYN(ref result, ref raw, dtfi);
- break;
- case DS.DX_YM:
- passed = GetDayOfYM(ref result, ref raw, dtfi);
- break;
- case DS.TX_N:
- passed = GetTimeOfN(dtfi, ref result, ref raw);
- break;
- case DS.TX_NN:
- passed = GetTimeOfNN(dtfi, ref result, ref raw);
- break;
- case DS.TX_NNN:
- passed = GetTimeOfNNN(dtfi, ref result, ref raw);
- break;
- case DS.TX_TS:
- // The result has got the correct value. Nothing to do.
- passed = true;
- break;
- case DS.DX_DSN:
- passed = GetDateOfDSN(ref result, ref raw);
- break;
- case DS.DX_NDS:
- passed = GetDateOfNDS(ref result, ref raw);
- break;
- case DS.DX_NNDS:
- passed = GetDateOfNNDS(ref result, ref raw, dtfi);
- break;
- }
-
- PTSTraceExit(dps, passed);
- if (!passed) {
- return false;
- }
-
- if (dps > DS.ERROR)
- {
- //
- // We have reached a terminal state. Reset the raw num count.
- //
- raw.numCount = 0;
- }
- return true;
- }
-
- internal static DateTime Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) {
- DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
- result.Init();
- if (TryParse(s, dtfi, styles, ref result)) {
- return result.parsedDate;
- }
- else {
- throw GetDateTimeParseException(ref result);
- }
- }
-
- internal static DateTime Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out TimeSpan offset) {
- DateTimeResult result = new DateTimeResult(); // The buffer to store the parsing result.
- result.Init();
- result.flags |= ParseFlags.CaptureOffset;
- if (TryParse(s, dtfi, styles, ref result)) {
- offset = result.timeZoneOffset;
- return result.parsedDate;
- }
- else {
- throw GetDateTimeParseException(ref result);
- }
- }
-
-
- internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result) {
- result = DateTime.MinValue;
- DateTimeResult resultData = new DateTimeResult(); // The buffer to store the parsing result.
- resultData.Init();
- if (TryParse(s, dtfi, styles, ref resultData)) {
- result = resultData.parsedDate;
- return true;
- }
- return false;
- }
-
- internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result, out TimeSpan offset) {
- result = DateTime.MinValue;
- offset = TimeSpan.Zero;
- DateTimeResult parseResult = new DateTimeResult(); // The buffer to store the parsing result.
- parseResult.Init();
- parseResult.flags |= ParseFlags.CaptureOffset;
- if (TryParse(s, dtfi, styles, ref parseResult)) {
- result = parseResult.parsedDate;
- offset = parseResult.timeZoneOffset;
- return true;
- }
- return false;
- }
-
-
- //
- // This is the real method to do the parsing work.
- //
- internal static bool TryParse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result) {
- if (s == null) {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
- return false;
- }
- if (s.Length == 0) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- Debug.Assert(dtfi != null, "dtfi == null");
-
-#if _LOGGING
- DTFITrace(dtfi);
-#endif
-
- DateTime time;
- //
- // First try the predefined format.
- //
-
- DS dps = DS.BEGIN; // Date Parsing State.
- bool reachTerminalState = false;
-
- DateTimeToken dtok = new DateTimeToken(); // The buffer to store the parsing token.
- dtok.suffix = TokenType.SEP_Unk;
- DateTimeRawInfo raw = new DateTimeRawInfo(); // The buffer to store temporary parsing information.
- unsafe {
- Int32 * numberPointer = stackalloc Int32[3];
- raw.Init(numberPointer);
- }
- raw.hasSameDateAndTimeSeparators = dtfi.DateSeparator.Equals(dtfi.TimeSeparator, StringComparison.Ordinal);
-
- result.calendar = dtfi.Calendar;
- result.era = Calendar.CurrentEra;
-
- //
- // The string to be parsed. Use a __DTString wrapper so that we can trace the index which
- // indicates the begining of next token.
- //
- __DTString str = new __DTString(s, dtfi);
-
- str.GetNext();
-
- //
- // The following loop will break out when we reach the end of the str.
- //
- do {
- //
- // Call the lexer to get the next token.
- //
- // If we find a era in Lex(), the era value will be in raw.era.
- if (!Lex(dps, ref str, ref dtok, ref raw, ref result, ref dtfi, styles))
- {
- TPTraceExit("0000", dps);
- return false;
- }
-
- //
- // If the token is not unknown, process it.
- // Otherwise, just discard it.
- //
- if (dtok.dtt != DTT.Unk)
- {
- //
- // Check if we got any CJK Date/Time suffix.
- // Since the Date/Time suffix tells us the number belongs to year/month/day/hour/minute/second,
- // store the number in the appropriate field in the result.
- //
- if (dtok.suffix != TokenType.SEP_Unk)
- {
- if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- TPTraceExit("0010", dps);
- return false;
- }
-
- dtok.suffix = TokenType.SEP_Unk; // Reset suffix to SEP_Unk;
- }
-
- if (dtok.dtt == DTT.NumLocalTimeMark) {
- if (dps == DS.D_YNd || dps == DS.D_YN) {
- // Consider this as ISO 8601 format:
- // "yyyy-MM-dd'T'HH:mm:ss" 1999-10-31T02:00:00
- TPTraceExit("0020", dps);
- return (ParseISO8601(ref raw, ref str, styles, ref result));
- }
- else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- TPTraceExit("0030", dps);
- return false;
- }
- }
-
- if (raw.hasSameDateAndTimeSeparators)
- {
- if (dtok.dtt == DTT.YearEnd || dtok.dtt == DTT.YearSpace || dtok.dtt == DTT.YearDateSep)
- {
- // When time and date separators are same and we are hitting a year number while the first parsed part of the string was recognized
- // as part of time (and not a date) DS.T_Nt, DS.T_NNt then change the state to be a date so we try to parse it as a date instead
- if (dps == DS.T_Nt)
- {
- dps = DS.D_Nd;
- }
- if (dps == DS.T_NNt)
- {
- dps = DS.D_NNd;
- }
- }
-
- bool atEnd = str.AtEnd();
- if (dateParsingStates[(int)dps][(int)dtok.dtt] == DS.ERROR || atEnd)
- {
- switch (dtok.dtt)
- {
- // we have the case of Serbia have dates in forms 'd.M.yyyy.' so we can expect '.' after the date parts.
- // changing the token to end with space instead of Date Separator will avoid failing the parsing.
-
- case DTT.YearDateSep: dtok.dtt = atEnd ? DTT.YearEnd : DTT.YearSpace; break;
- case DTT.NumDatesep: dtok.dtt = atEnd ? DTT.NumEnd : DTT.NumSpace; break;
- case DTT.NumTimesep: dtok.dtt = atEnd ? DTT.NumEnd : DTT.NumSpace; break;
- case DTT.MonthDatesep: dtok.dtt = atEnd ? DTT.MonthEnd : DTT.MonthSpace; break;
- }
- }
- }
-
- //
- // Advance to the next state, and continue
- //
- dps = dateParsingStates[(int)dps][(int)dtok.dtt];
-
- if (dps == DS.ERROR)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- TPTraceExit("0040 (invalid state transition)", dps);
- return false;
- }
- else if (dps > DS.ERROR)
- {
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) {
- if (!ProcessHebrewTerminalState(dps, ref result, ref styles, ref raw, dtfi)) {
- TPTraceExit("0050 (ProcessHebrewTerminalState)", dps);
- return false;
- }
- } else {
- if (!ProcessTerminaltState(dps, ref result, ref styles, ref raw, dtfi)) {
- TPTraceExit("0060 (ProcessTerminaltState)", dps);
- return false;
- }
- }
- reachTerminalState = true;
-
- //
- // If we have reached a terminal state, start over from DS.BEGIN again.
- // For example, when we parsed "1999-12-23 13:30", we will reach a terminal state at "1999-12-23",
- // and we start over so we can continue to parse "12:30".
- //
- dps = DS.BEGIN;
- }
- }
- } while (dtok.dtt != DTT.End && dtok.dtt != DTT.NumEnd && dtok.dtt != DTT.MonthEnd);
-
- if (!reachTerminalState) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- TPTraceExit("0070 (did not reach terminal state)", dps);
- return false;
- }
-
- AdjustTimeMark(dtfi, ref raw);
- if (!AdjustHour(ref result.Hour, raw.timeMark)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- TPTraceExit("0080 (AdjustHour)", dps);
- return false;
- }
-
- // Check if the parased string only contains hour/minute/second values.
- bool bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
-
- //
- // Check if any year/month/day is missing in the parsing string.
- // If yes, get the default value from today's date.
- //
- if (!CheckDefaultDateTime(ref result, ref result.calendar, styles)) {
- TPTraceExit("0090 (failed to fill in missing year/month/day defaults)", dps);
- return false;
- }
-
- 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);
- TPTraceExit("0100 (result.calendar.TryToDateTime)", dps);
- return false;
- }
- if (raw.fraction > 0) {
- time = time.AddTicks((long)Math.Round(raw.fraction * Calendar.TicksPerSecond));
- }
-
- //
- // We have to check day of week before we adjust to the time zone.
- // Otherwise, the value of day of week may change after adjustting to the time zone.
- //
- if (raw.dayOfWeek != -1) {
- //
- // Check if day of week is correct.
- //
- if (raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(time)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
- TPTraceExit("0110 (dayOfWeek check)", dps);
- return false;
- }
- }
-
- result.parsedDate = time;
-
- if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) {
- TPTraceExit("0120 (DetermineTimeZoneAdjustments)", dps);
- return false;
- }
- TPTraceExit("0130 (success)", dps);
- return true;
- }
-
-
- // Handles time zone adjustments and sets DateTimeKind values as required by the styles
- private static Boolean DetermineTimeZoneAdjustments(ref DateTimeResult result, DateTimeStyles styles, Boolean bTimeOnly) {
-
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- // This is a DateTimeOffset parse, so the offset will actually be captured directly, and
- // no adjustment is required in most cases
- return DateTimeOffsetTimeZonePostProcessing(ref result, styles);
- }
- else {
- Int64 offsetTicks = result.timeZoneOffset.Ticks;
-
- // the DateTime offset must be within +- 14:00 hours.
- if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset) {
- result.SetFailure(ParseFailureKind.Format, "Format_OffsetOutOfRange", null);
- return false;
- }
- }
-
- // The flags AssumeUniveral and AssumeLocal only apply when the input does not have a time zone
- if ((result.flags & ParseFlags.TimeZoneUsed) == 0) {
-
- // If AssumeLocal or AssumeLocal is used, there will always be a kind specified. As in the
- // case when a time zone is present, it will default to being local unless AdjustToUniversal
- // is present. These comparisons determine whether setting the kind is sufficient, or if a
- // time zone adjustment is required. For consistentcy with the rest of parsing, it is desirable
- // to fall through to the Adjust methods below, so that there is consist handling of boundary
- // cases like wrapping around on time-only dates and temporarily allowing an adjusted date
- // to exceed DateTime.MaxValue
- if ((styles & DateTimeStyles.AssumeLocal) != 0) {
- if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
- else {
- result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Local);
- return true;
- }
- }
- else if ((styles & DateTimeStyles.AssumeUniversal) != 0) {
- if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
- result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc);
- return true;
- }
- else {
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = TimeSpan.Zero;
- }
- }
- else {
- // No time zone and no Assume flags, so DateTimeKind.Unspecified is fine
- Debug.Assert(result.parsedDate.Kind == DateTimeKind.Unspecified, "result.parsedDate.Kind == DateTimeKind.Unspecified");
- return true;
- }
- }
-
- if (((styles & DateTimeStyles.RoundtripKind) != 0) && ((result.flags & ParseFlags.TimeZoneUtc) != 0)) {
- result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc);
- return true;
- }
-
- if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
- return (AdjustTimeZoneToUniversal(ref result));
- }
- return (AdjustTimeZoneToLocal(ref result, bTimeOnly));
- }
-
- // Apply validation and adjustments specific to DateTimeOffset
- private static Boolean DateTimeOffsetTimeZonePostProcessing(ref DateTimeResult result, DateTimeStyles styles) {
-
- // For DateTimeOffset, default to the Utc or Local offset when an offset was not specified by
- // the input string.
- if ((result.flags & ParseFlags.TimeZoneUsed) == 0) {
- if ((styles & DateTimeStyles.AssumeUniversal) != 0) {
- // AssumeUniversal causes the offset to default to zero (0)
- result.timeZoneOffset = TimeSpan.Zero;
- }
- else {
- // AssumeLocal causes the offset to default to Local. This flag is on by default for DateTimeOffset.
- result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime);
- }
- }
-
- Int64 offsetTicks = result.timeZoneOffset.Ticks;
-
- // there should be no overflow, because the offset can be no more than -+100 hours and the date already
- // fits within a DateTime.
- Int64 utcTicks = result.parsedDate.Ticks - offsetTicks;
-
- // For DateTimeOffset, both the parsed time and the corresponding UTC value must be within the boundaries
- // of a DateTime instance.
- if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
- result.SetFailure(ParseFailureKind.Format, "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);
- return false;
- }
-
- // DateTimeOffset should still honor the AdjustToUniversal flag for consistency with DateTime. It means you
- // want to return an adjusted UTC value, so store the utcTicks in the DateTime and set the offset to zero
- if ((styles & DateTimeStyles.AdjustToUniversal) != 0) {
- if (((result.flags & ParseFlags.TimeZoneUsed) == 0) && ((styles & DateTimeStyles.AssumeUniversal) == 0)) {
- // Handle the special case where the timeZoneOffset was defaulted to Local
- Boolean toUtcResult = AdjustTimeZoneToUniversal(ref result);
- result.timeZoneOffset = TimeSpan.Zero;
- return toUtcResult;
- }
-
- // The constructor should always succeed because of the range check earlier in the function
- // Althought it is UTC, internally DateTimeOffset does not use this flag
- result.parsedDate = new DateTime(utcTicks, DateTimeKind.Utc);
- result.timeZoneOffset = TimeSpan.Zero;
- }
-
- return true;
- }
-
-
- //
- // Adjust the specified time to universal time based on the supplied timezone.
- // E.g. when parsing "2001/06/08 14:00-07:00",
- // the time is 2001/06/08 14:00, and timeZoneOffset = -07:00.
- // The result will be "2001/06/08 21:00"
- //
- private static Boolean AdjustTimeZoneToUniversal(ref DateTimeResult result) {
- long resultTicks = result.parsedDate.Ticks;
- resultTicks -= result.timeZoneOffset.Ticks;
- if (resultTicks < 0) {
- resultTicks += Calendar.TicksPerDay;
- }
-
- if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) {
- result.SetFailure(ParseFailureKind.Format, "Format_DateOutOfRange", null);
- return false;
- }
- result.parsedDate = new DateTime(resultTicks, DateTimeKind.Utc);
- return true;
- }
-
- //
- // Adjust the specified time to universal time based on the supplied timezone,
- // and then convert to local time.
- // E.g. when parsing "2001/06/08 14:00-04:00", and local timezone is GMT-7.
- // the time is 2001/06/08 14:00, and timeZoneOffset = -05:00.
- // The result will be "2001/06/08 11:00"
- //
- private static Boolean AdjustTimeZoneToLocal(ref DateTimeResult result, bool bTimeOnly) {
- long resultTicks = result.parsedDate.Ticks;
- // Convert to local ticks
- TimeZoneInfo tz = TimeZoneInfo.Local;
- Boolean isAmbiguousLocalDst = false;
- if (resultTicks < Calendar.TicksPerDay) {
- //
- // This is time of day.
- //
-
- // Adjust timezone.
- resultTicks -= result.timeZoneOffset.Ticks;
- // If the time is time of day, use the current timezone offset.
- resultTicks += tz.GetUtcOffset(bTimeOnly ? DateTime.Now: result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
-
- if (resultTicks < 0) {
- resultTicks += Calendar.TicksPerDay;
- }
- } else {
- // Adjust timezone to GMT.
- resultTicks -= result.timeZoneOffset.Ticks;
- if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) {
- // If the result ticks is greater than DateTime.MaxValue, we can not create a DateTime from this ticks.
- // In this case, keep using the old code.
- resultTicks += tz.GetUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
- } else {
- // Convert the GMT time to local time.
- DateTime utcDt = new DateTime(resultTicks, DateTimeKind.Utc);
- Boolean isDaylightSavings = false;
- resultTicks += TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
- }
- }
- if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks) {
- result.parsedDate = DateTime.MinValue;
- result.SetFailure(ParseFailureKind.Format, "Format_DateOutOfRange", null);
- return false;
- }
- result.parsedDate = new DateTime(resultTicks, DateTimeKind.Local, isAmbiguousLocalDst);
- return true;
- }
-
- //
- // Parse the ISO8601 format string found during Parse();
- //
- //
- private static bool ParseISO8601(ref DateTimeRawInfo raw, ref __DTString str, DateTimeStyles styles, ref DateTimeResult result) {
- if (raw.year < 0 || raw.GetNumber(0) < 0 || raw.GetNumber(1) < 0) {
- }
- str.Index--;
- int hour, minute;
- int second = 0;
- double partSecond = 0;
-
- str.SkipWhiteSpaces();
- if (!ParseDigits(ref str, 2, out hour)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- str.SkipWhiteSpaces();
- if (!str.Match(':')) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- str.SkipWhiteSpaces();
- if (!ParseDigits(ref str, 2, out minute)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- str.SkipWhiteSpaces();
- if (str.Match(':')) {
- str.SkipWhiteSpaces();
- if (!ParseDigits(ref str, 2, out second)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- if (str.Match('.')) {
- if (!ParseFraction(ref str, out partSecond)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- str.Index--;
- }
- str.SkipWhiteSpaces();
- }
- if (str.GetNext()) {
- char ch = str.GetChar();
- if (ch == '+' || ch == '-') {
- result.flags |= ParseFlags.TimeZoneUsed;
- if (!ParseTimeZone(ref str, ref result.timeZoneOffset)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- } else if (ch == 'Z' || ch == 'z') {
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = TimeSpan.Zero;
- result.flags |= ParseFlags.TimeZoneUtc;
- } else {
- str.Index--;
- }
- str.SkipWhiteSpaces();
- if (str.Match('#')) {
- if (!VerifyValidPunctuation(ref str)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- str.SkipWhiteSpaces();
- }
- if (str.Match('\0')) {
- if (!VerifyValidPunctuation(ref str)) {
- result.SetFailure(ParseFailureKind.Format, "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);
- return false;
- }
- }
-
- DateTime time;
- Calendar calendar = GregorianCalendar.GetDefaultInstance();
- 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);
- return false;
- }
-
- time = time.AddTicks((long)Math.Round(partSecond * Calendar.TicksPerSecond));
- result.parsedDate = time;
- if (!DetermineTimeZoneAdjustments(ref result, styles, false)) {
- return false;
- }
- return true;
- }
-
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Actions:
- // Parse the current word as a Hebrew number.
- // This is used by DateTime.ParseExact().
- //
- ////////////////////////////////////////////////////////////////////////
-
- internal static bool MatchHebrewDigits(ref __DTString str, int digitLen, out int number) {
- number = 0;
-
- // Create a context object so that we can parse the Hebrew number text character by character.
- HebrewNumberParsingContext context = new HebrewNumberParsingContext(0);
-
- // Set this to ContinueParsing so that we will run the following while loop in the first time.
- HebrewNumberParsingState state = HebrewNumberParsingState.ContinueParsing;
-
- while (state == HebrewNumberParsingState.ContinueParsing && str.GetNext()) {
- state = HebrewNumber.ParseByChar(str.GetChar(), ref context);
- }
-
- if (state == HebrewNumberParsingState.FoundEndOfHebrewNumber) {
- // If we have reached a terminal state, update the result and returns.
- number = context.result;
- return (true);
- }
-
- // If we run out of the character before reaching FoundEndOfHebrewNumber, or
- // the state is InvalidHebrewNumber or ContinueParsing, we fail to match a Hebrew number.
- // Return an error.
- return false;
- }
-
- /*=================================ParseDigits==================================
- **Action: Parse the number string in __DTString that are formatted using
- ** the following patterns:
- ** "0", "00", and "000..0"
- **Returns: the integer value
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if error in parsing number.
- ==============================================================================*/
-
- internal static bool ParseDigits(ref __DTString str, int digitLen, out int result) {
- if (digitLen == 1) {
- // 1 really means 1 or 2 for this call
- return ParseDigits(ref str, 1, 2, out result);
- }
- else {
- return ParseDigits(ref str, digitLen, digitLen, out result);
- }
- }
-
- internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) {
- Debug.Assert(minDigitLen > 0, "minDigitLen > 0");
- Debug.Assert(maxDigitLen < 9, "maxDigitLen < 9");
- Debug.Assert(minDigitLen <= maxDigitLen, "minDigitLen <= maxDigitLen");
- result = 0;
- int startingIndex = str.Index;
- int tokenLength = 0;
- while (tokenLength < maxDigitLen) {
- if (!str.GetNextDigit()) {
- str.Index--;
- break;
- }
- result = result * 10 + str.GetDigit();
- tokenLength++;
- }
- if (tokenLength < minDigitLen) {
- str.Index = startingIndex;
- return false;
- }
- return true;
- }
-
- /*=================================ParseFractionExact==================================
- **Action: Parse the number string in __DTString that are formatted using
- ** the following patterns:
- ** "0", "00", and "000..0"
- **Returns: the fraction value
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if error in parsing number.
- ==============================================================================*/
-
- private static bool ParseFractionExact(ref __DTString str, int maxDigitLen, ref double result) {
- if (!str.GetNextDigit()) {
- str.Index--;
- return false;
- }
- result = str.GetDigit();
-
- int digitLen = 1;
- for (; digitLen < maxDigitLen; digitLen++) {
- if (!str.GetNextDigit()) {
- str.Index--;
- break;
- }
- result = result * 10 + str.GetDigit();
- }
-
- result = ((double)result / Math.Pow(10, digitLen));
- return (digitLen == maxDigitLen);
- }
-
- /*=================================ParseSign==================================
- **Action: Parse a positive or a negative sign.
- **Returns: true if postive sign. flase if negative sign.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if end of string is encountered or a sign
- ** symbol is not found.
- ==============================================================================*/
-
- private static bool ParseSign(ref __DTString str, ref bool result) {
- if (!str.GetNext()) {
- // A sign symbol ('+' or '-') is expected. However, end of string is encountered.
- return false;
- }
- char ch = str.GetChar();
- if (ch == '+') {
- result = true;
- return (true);
- } else if (ch == '-') {
- result = false;
- return (true);
- }
- // A sign symbol ('+' or '-') is expected.
- return false;
- }
-
- /*=================================ParseTimeZoneOffset==================================
- **Action: Parse the string formatted using "z", "zz", "zzz" in DateTime.Format().
- **Returns: the TimeSpan for the parsed timezone offset.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- ** len: the repeated number of the "z"
- **Exceptions: FormatException if errors in parsing.
- ==============================================================================*/
-
- private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result) {
- bool isPositive = true;
- int hourOffset;
- int minuteOffset = 0;
-
- switch (len) {
- case 1:
- case 2:
- if (!ParseSign(ref str, ref isPositive)) {
- return (false);
- }
- if (!ParseDigits(ref str, len, out hourOffset)) {
- return (false);
- }
- break;
- default:
- if (!ParseSign(ref str, ref isPositive)) {
- return (false);
- }
-
- // Parsing 1 digit will actually parse 1 or 2.
- if (!ParseDigits(ref str, 1, out hourOffset)) {
- return (false);
- }
- // ':' is optional.
- if (str.Match(":")) {
- // Found ':'
- if (!ParseDigits(ref str, 2, out minuteOffset)) {
- return (false);
- }
- } else {
- // Since we can not match ':', put the char back.
- str.Index--;
- if (!ParseDigits(ref str, 2, out minuteOffset)) {
- return (false);
- }
- }
- break;
- }
- if (minuteOffset < 0 || minuteOffset >= 60) {
- return false;
- }
-
- result = (new TimeSpan(hourOffset, minuteOffset, 0));
- if (!isPositive) {
- result = result.Negate();
- }
- return (true);
- }
-
- /*=================================MatchAbbreviatedMonthName==================================
- **Action: Parse the abbreviated month name from string starting at str.Index.
- **Returns: A value from 1 to 12 for the first month to the twelveth month.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if an abbreviated month name can not be found.
- ==============================================================================*/
-
- private static bool MatchAbbreviatedMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
- int maxMatchStrLen = 0;
- result = -1;
- if (str.GetNext()) {
- //
- // Scan the month names (note that some calendars has 13 months) and find
- // the matching month name which has the max string length.
- // We need to do this because some cultures (e.g. "cs-CZ") which have
- // abbreviated month names with the same prefix.
- //
- int monthsInYear = (dtfi.GetMonthName(13).Length == 0 ? 12: 13);
- for (int i = 1; i <= monthsInYear; i++) {
- String searchStr = dtfi.GetAbbreviatedMonthName(i);
- int matchStrLen = searchStr.Length;
- if ( dtfi.HasSpacesInMonthNames
- ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
- maxMatchStrLen = matchStrLen;
- result = i;
- }
- }
- }
-
- // Search leap year form.
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) {
- int tempResult = str.MatchLongestWords(dtfi.internalGetLeapYearMonthNames(), ref maxMatchStrLen);
- // We found a longer match in the leap year month name. Use this as the result.
- // The result from MatchLongestWords is 0 ~ length of word array.
- // So we increment the result by one to become the month value.
- if (tempResult >= 0) {
- result = tempResult + 1;
- }
- }
-
-
- }
- if (result > 0) {
- str.Index += (maxMatchStrLen - 1);
- return (true);
- }
- return false;
- }
-
- /*=================================MatchMonthName==================================
- **Action: Parse the month name from string starting at str.Index.
- **Returns: A value from 1 to 12 indicating the first month to the twelveth month.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if a month name can not be found.
- ==============================================================================*/
-
- private static bool MatchMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
- int maxMatchStrLen = 0;
- result = -1;
- if (str.GetNext()) {
- //
- // Scan the month names (note that some calendars has 13 months) and find
- // the matching month name which has the max string length.
- // We need to do this because some cultures (e.g. "vi-VN") which have
- // month names with the same prefix.
- //
- int monthsInYear = (dtfi.GetMonthName(13).Length == 0 ? 12: 13);
- for (int i = 1; i <= monthsInYear; i++) {
- String searchStr = dtfi.GetMonthName(i);
- int matchStrLen = searchStr.Length;
- if ( dtfi.HasSpacesInMonthNames
- ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
- maxMatchStrLen = matchStrLen;
- result = i;
- }
- }
- }
-
- // Search genitive form.
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) {
- int tempResult = str.MatchLongestWords(dtfi.MonthGenitiveNames, ref maxMatchStrLen);
- // We found a longer match in the genitive month name. Use this as the result.
- // The result from MatchLongestWords is 0 ~ length of word array.
- // So we increment the result by one to become the month value.
- if (tempResult >= 0) {
- result = tempResult + 1;
- }
- }
-
- // Search leap year form.
- if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) {
- int tempResult = str.MatchLongestWords(dtfi.internalGetLeapYearMonthNames(), ref maxMatchStrLen);
- // We found a longer match in the leap year month name. Use this as the result.
- // The result from MatchLongestWords is 0 ~ length of word array.
- // So we increment the result by one to become the month value.
- if (tempResult >= 0) {
- result = tempResult + 1;
- }
- }
-
-
- }
-
- if (result > 0) {
- str.Index += (maxMatchStrLen - 1);
- return (true);
- }
- return false;
- }
-
- /*=================================MatchAbbreviatedDayName==================================
- **Action: Parse the abbreviated day of week name from string starting at str.Index.
- **Returns: A value from 0 to 6 indicating Sunday to Saturday.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if a abbreviated day of week name can not be found.
- ==============================================================================*/
-
- private static bool MatchAbbreviatedDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
- int maxMatchStrLen = 0;
- result = -1;
- if (str.GetNext()) {
- for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) {
- String searchStr = dtfi.GetAbbreviatedDayName(i);
- int matchStrLen = searchStr.Length;
- if ( dtfi.HasSpacesInDayNames
- ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
- maxMatchStrLen = matchStrLen;
- result = (int)i;
- }
- }
- }
- }
- if (result >= 0) {
- str.Index += maxMatchStrLen - 1;
- return (true);
- }
- return false;
- }
-
- /*=================================MatchDayName==================================
- **Action: Parse the day of week name from string starting at str.Index.
- **Returns: A value from 0 to 6 indicating Sunday to Saturday.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if a day of week name can not be found.
- ==============================================================================*/
-
- private static bool MatchDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
- // Turkish (tr-TR) got day names with the same prefix.
- int maxMatchStrLen = 0;
- result = -1;
- if (str.GetNext()) {
- for (DayOfWeek i = DayOfWeek.Sunday; i <= DayOfWeek.Saturday; i++) {
- String searchStr = dtfi.GetDayName(i);
- int matchStrLen = searchStr.Length;
- if ( dtfi.HasSpacesInDayNames
- ? str.MatchSpecifiedWords(searchStr, false, ref matchStrLen)
- : str.MatchSpecifiedWord(searchStr)) {
- if (matchStrLen > maxMatchStrLen) {
- maxMatchStrLen = matchStrLen;
- result = (int)i;
- }
- }
- }
- }
- if (result >= 0) {
- str.Index += maxMatchStrLen - 1;
- return (true);
- }
- return false;
- }
-
- /*=================================MatchEraName==================================
- **Action: Parse era name from string starting at str.Index.
- **Returns: An era value.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if an era name can not be found.
- ==============================================================================*/
-
- private static bool MatchEraName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) {
- if (str.GetNext()) {
- int[] eras = dtfi.Calendar.Eras;
-
- if (eras != null) {
- for (int i = 0; i < eras.Length; i++) {
- String searchStr = dtfi.GetEraName(eras[i]);
- if (str.MatchSpecifiedWord(searchStr)) {
- str.Index += (searchStr.Length - 1);
- result = eras[i];
- return (true);
- }
- searchStr = dtfi.GetAbbreviatedEraName(eras[i]);
- if (str.MatchSpecifiedWord(searchStr)) {
- str.Index += (searchStr.Length - 1);
- result = eras[i];
- return (true);
- }
- }
- }
- }
- return false;
- }
-
- /*=================================MatchTimeMark==================================
- **Action: Parse the time mark (AM/PM) from string starting at str.Index.
- **Returns: TM_AM or TM_PM.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if a time mark can not be found.
- ==============================================================================*/
-
- private static bool MatchTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result) {
- result = TM.NotSet;
- // In some cultures have empty strings in AM/PM mark. E.g. af-ZA (0x0436), the AM mark is "", and PM mark is "nm".
- if (dtfi.AMDesignator.Length == 0) {
- result = TM.AM;
- }
- if (dtfi.PMDesignator.Length == 0) {
- result = TM.PM;
- }
-
- if (str.GetNext()) {
- String searchStr = dtfi.AMDesignator;
- if (searchStr.Length > 0) {
- if (str.MatchSpecifiedWord(searchStr)) {
- // Found an AM timemark with length > 0.
- str.Index += (searchStr.Length - 1);
- result = TM.AM;
- return (true);
- }
- }
- searchStr = dtfi.PMDesignator;
- if (searchStr.Length > 0) {
- if (str.MatchSpecifiedWord(searchStr)) {
- // Found a PM timemark with length > 0.
- str.Index += (searchStr.Length - 1);
- result = TM.PM;
- return (true);
- }
- }
- str.Index--; // Undo the GetNext call.
- }
- if (result != TM.NotSet) {
- // If one of the AM/PM marks is empty string, return the result.
- return (true);
- }
- return false;
- }
-
- /*=================================MatchAbbreviatedTimeMark==================================
- **Action: Parse the abbreviated time mark (AM/PM) from string starting at str.Index.
- **Returns: TM_AM or TM_PM.
- **Arguments: str: a __DTString. The parsing will start from the
- ** next character after str.Index.
- **Exceptions: FormatException if a abbreviated time mark can not be found.
- ==============================================================================*/
-
- private static bool MatchAbbreviatedTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result) {
- // NOTENOTE : the assumption here is that abbreviated time mark is the first
- // character of the AM/PM designator. If this invariant changes, we have to
- // change the code below.
- if (str.GetNext())
- {
- if (str.GetChar() == dtfi.AMDesignator[0]) {
- result = TM.AM;
- return (true);
- }
- if (str.GetChar() == dtfi.PMDesignator[0]) {
- result = TM.PM;
- return (true);
- }
- }
- return false;
- }
-
- /*=================================CheckNewValue==================================
- **Action: Check if currentValue is initialized. If not, return the newValue.
- ** If yes, check if the current value is equal to newValue. Return false
- ** if they are not equal. This is used to check the case like "d" and "dd" are both
- ** used to format a string.
- **Returns: the correct value for currentValue.
- **Arguments:
- **Exceptions:
- ==============================================================================*/
-
- private static bool CheckNewValue(ref int currentValue, int newValue, char patternChar, ref DateTimeResult result) {
- if (currentValue == -1) {
- currentValue = newValue;
- return (true);
- } else {
- if (newValue != currentValue) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", patternChar);
- return (false);
- }
- }
- return (true);
- }
-
- private static DateTime GetDateTimeNow(ref DateTimeResult result, ref DateTimeStyles styles) {
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0) {
- // use the supplied offset to calculate 'Now'
- return new DateTime(DateTime.UtcNow.Ticks + result.timeZoneOffset.Ticks, DateTimeKind.Unspecified);
- }
- else if ((styles & DateTimeStyles.AssumeUniversal) != 0) {
- // assume the offset is Utc
- return DateTime.UtcNow;
- }
- }
-
- // assume the offset is Local
- return DateTime.Now;
- }
-
- private static bool CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles) {
-
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- // DateTimeOffset.Parse should allow dates without a year, but only if there is also no time zone marker;
- // e.g. "May 1 5pm" is OK, but "May 1 5pm -08:30" is not. This is somewhat pragmatic, since we would
- // have to rearchitect parsing completely to allow this one case to correctly handle things like leap
- // years and leap months. Is is an extremely corner case, and DateTime is basically incorrect in that
- // case today.
- //
- // values like "11:00Z" or "11:00 -3:00" are also acceptable
- //
- // if ((month or day is set) and (year is not set and time zone is set))
- //
- 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);
- return false;
- }
- }
-
-
- if ((result.Year == -1) || (result.Month == -1) || (result.Day == -1)) {
- /*
- The following table describes the behaviors of getting the default value
- when a certain year/month/day values are missing.
-
- An "X" means that the value exists. And "--" means that value is missing.
-
- Year Month Day => ResultYear ResultMonth ResultDay Note
-
- X X X Parsed year Parsed month Parsed day
- X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month.
- X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year.
- X -- -- Parsed year First month First day If we have only the year, assume the first day of that year.
-
- -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year.
- -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day.
- -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month.
- -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date.
-
- */
-
- DateTime now = GetDateTimeNow(ref result, ref styles);
- if (result.Month == -1 && result.Day == -1) {
- if (result.Year == -1) {
- if ((styles & DateTimeStyles.NoCurrentDateDefault) != 0) {
- // If there is no year/month/day values, and NoCurrentDateDefault flag is used,
- // set the year/month/day value to the beginning year/month/day of DateTime().
- // Note we should be using Gregorian for the year/month/day.
- cal = GregorianCalendar.GetDefaultInstance();
- result.Year = result.Month = result.Day = 1;
- } else {
- // Year/Month/Day are all missing.
- result.Year = cal.GetYear(now);
- result.Month = cal.GetMonth(now);
- result.Day = cal.GetDayOfMonth(now);
- }
- } else {
- // Month/Day are both missing.
- result.Month = 1;
- result.Day = 1;
- }
- } else {
- if (result.Year == -1) {
- result.Year = cal.GetYear(now);
- }
- if (result.Month == -1) {
- result.Month = 1;
- }
- if (result.Day == -1) {
- result.Day = 1;
- }
- }
- }
- // Set Hour/Minute/Second to zero if these value are not in str.
- if (result.Hour == -1) result.Hour = 0;
- if (result.Minute == -1) result.Minute = 0;
- if (result.Second == -1) result.Second = 0;
- if (result.era == -1) result.era = Calendar.CurrentEra;
- return true;
- }
-
- // Expand a pre-defined format string (like "D" for long date) to the real format that
- // we are going to use in the date time parsing.
- // This method also set the dtfi according/parseInfo to some special pre-defined
- // formats.
- //
- private static String ExpandPredefinedFormat(String format, ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result) {
- //
- // Check the format to see if we need to override the dtfi to be InvariantInfo,
- // and see if we need to set up the userUniversalTime flag.
- //
- switch (format[0]) {
- case 'o':
- case 'O': // Round Trip Format
- parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
- dtfi = DateTimeFormatInfo.InvariantInfo;
- break;
- case 'r':
- case 'R': // RFC 1123 Standard. (in Universal time)
- parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
- dtfi = DateTimeFormatInfo.InvariantInfo;
-
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- result.flags |= ParseFlags.Rfc1123Pattern;
- }
- break;
- case 's': // Sortable format (in local time)
- dtfi = DateTimeFormatInfo.InvariantInfo;
- parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
- break;
- case 'u': // Universal time format in sortable format.
- parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
- dtfi = DateTimeFormatInfo.InvariantInfo;
-
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- result.flags |= ParseFlags.UtcSortPattern;
- }
- break;
- case 'U': // Universal time format with culture-dependent format.
- parseInfo.calendar = GregorianCalendar.GetDefaultInstance();
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = new TimeSpan(0);
- result.flags |= ParseFlags.TimeZoneUtc;
- if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) {
- dtfi = (DateTimeFormatInfo)dtfi.Clone();
- dtfi.Calendar = GregorianCalendar.GetDefaultInstance();
- }
- break;
- }
-
- //
- // Expand the pre-defined format character to the real format from DateTimeFormatInfo.
- //
- return (DateTimeFormat.GetRealFormat(format, dtfi));
- }
-
-
-
-
-
- // Given a specified format character, parse and update the parsing result.
- //
- private static bool ParseByFormat(
- ref __DTString str,
- ref __DTString format,
- ref ParsingInfo parseInfo,
- DateTimeFormatInfo dtfi,
- ref DateTimeResult result) {
-
- int tokenLen = 0;
- int tempYear = 0, tempMonth = 0, tempDay = 0, tempDayOfWeek = 0, tempHour = 0, tempMinute = 0, tempSecond = 0;
- double tempFraction = 0;
- TM tempTimeMark = 0;
-
- char ch = format.GetChar();
-
- switch (ch) {
- case 'y':
- tokenLen = format.GetRepeatCount();
- bool parseResult;
- if (dtfi.HasForceTwoDigitYears) {
- parseResult = ParseDigits(ref str, 1, 4, out tempYear);
- }
- else {
- if (tokenLen <= 2) {
- parseInfo.fUseTwoDigitYear = true;
- }
- parseResult = ParseDigits(ref str, tokenLen, out tempYear);
- }
- if (!parseResult && parseInfo.fCustomNumberParser) {
- parseResult = parseInfo.parseNumberDelegate(ref str, tokenLen, out tempYear);
- }
- if (!parseResult) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if (!CheckNewValue(ref result.Year, tempYear, ch, ref result)) {
- return (false);
- }
- break;
- case 'M':
- tokenLen = format.GetRepeatCount();
- if (tokenLen <= 2) {
- if (!ParseDigits(ref str, tokenLen, out tempMonth)) {
- if (!parseInfo.fCustomNumberParser ||
- !parseInfo.parseNumberDelegate(ref str, tokenLen, out tempMonth)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- }
- } else {
- if (tokenLen == 3) {
- if (!MatchAbbreviatedMonthName(ref str, dtfi, ref tempMonth)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- } else {
- if (!MatchMonthName(ref str, dtfi, ref tempMonth)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- }
- result.flags |= ParseFlags.ParsedMonthName;
- }
- if (!CheckNewValue(ref result.Month, tempMonth, ch, ref result)) {
- return (false);
- }
- break;
- case 'd':
- // Day & Day of week
- tokenLen = format.GetRepeatCount();
- if (tokenLen <= 2) {
- // "d" & "dd"
-
- if (!ParseDigits(ref str, tokenLen, out tempDay)) {
- if (!parseInfo.fCustomNumberParser ||
- !parseInfo.parseNumberDelegate(ref str, tokenLen, out tempDay)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- }
- if (!CheckNewValue(ref result.Day, tempDay, ch, ref result)) {
- return (false);
- }
- } else {
- if (tokenLen == 3) {
- // "ddd"
- if (!MatchAbbreviatedDayName(ref str, dtfi, ref tempDayOfWeek)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- } else {
- // "dddd*"
- if (!MatchDayName(ref str, dtfi, ref tempDayOfWeek)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- }
- if (!CheckNewValue(ref parseInfo.dayOfWeek, tempDayOfWeek, ch, ref result)) {
- return (false);
- }
- }
- break;
- case 'g':
- tokenLen = format.GetRepeatCount();
- // Put the era value in result.era.
- if (!MatchEraName(ref str, dtfi, ref result.era)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- break;
- case 'h':
- parseInfo.fUseHour12 = true;
- tokenLen = format.GetRepeatCount();
- if (!ParseDigits(ref str, (tokenLen < 2? 1 : 2), out tempHour)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if (!CheckNewValue(ref result.Hour, tempHour, ch, ref result)) {
- return (false);
- }
- break;
- case 'H':
- tokenLen = format.GetRepeatCount();
- if (!ParseDigits(ref str, (tokenLen < 2? 1 : 2), out tempHour)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if (!CheckNewValue(ref result.Hour, tempHour, ch, ref result)) {
- return (false);
- }
- break;
- case 'm':
- tokenLen = format.GetRepeatCount();
- if (!ParseDigits(ref str, (tokenLen < 2? 1 : 2), out tempMinute)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if (!CheckNewValue(ref result.Minute, tempMinute, ch, ref result)) {
- return (false);
- }
- break;
- case 's':
- tokenLen = format.GetRepeatCount();
- if (!ParseDigits(ref str, (tokenLen < 2? 1 : 2), out tempSecond)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if (!CheckNewValue(ref result.Second, tempSecond, ch, ref result)) {
- return (false);
- }
- break;
- case 'f':
- case 'F':
- tokenLen = format.GetRepeatCount();
- if (tokenLen <= DateTimeFormat.MaxSecondsFractionDigits) {
- if (!ParseFractionExact(ref str, tokenLen, ref tempFraction)) {
- if (ch == 'f') {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- }
- if (result.fraction < 0) {
- result.fraction = tempFraction;
- } else {
- if (tempFraction != result.fraction) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch);
- return (false);
- }
- }
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- break;
- case 't':
- // AM/PM designator
- tokenLen = format.GetRepeatCount();
- if (tokenLen == 1) {
- if (!MatchAbbreviatedTimeMark(ref str, dtfi, ref tempTimeMark)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- } else {
- if (!MatchTimeMark(ref str, dtfi, ref tempTimeMark)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- }
-
- if (parseInfo.timeMark == TM.NotSet) {
- parseInfo.timeMark = tempTimeMark;
- }
- else {
- if (parseInfo.timeMark != tempTimeMark) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch);
- return (false);
- }
- }
- break;
- case 'z':
- // timezone offset
- tokenLen = format.GetRepeatCount();
- {
- TimeSpan tempTimeZoneOffset = new TimeSpan(0);
- if (!ParseTimeZoneOffset(ref str, tokenLen, ref tempTimeZoneOffset)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'z');
- return (false);
- }
- result.timeZoneOffset = tempTimeZoneOffset;
- result.flags |= ParseFlags.TimeZoneUsed;
- }
- break;
- case 'Z':
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'Z');
- return (false);
- }
-
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = new TimeSpan(0);
- result.flags |= ParseFlags.TimeZoneUtc;
-
- // The updating of the indexes is to reflect that ParseExact MatchXXX methods assume that
- // they need to increment the index and Parse GetXXX do not. Since we are calling a Parse
- // method from inside ParseExact we need to adjust this. Long term, we should try to
- // eliminate this discrepancy.
- str.Index++;
- if (!GetTimeZoneName(ref str)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- str.Index--;
- break;
- case 'K':
- // This should parse either as a blank, the 'Z' character or a local offset like "-07:00"
- if (str.Match('Z')) {
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K');
- return (false);
- }
-
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = new TimeSpan(0);
- result.flags |= ParseFlags.TimeZoneUtc;
- }
- else if (str.Match('+') || str.Match('-')) {
- str.Index--; // Put the character back for the parser
- TimeSpan tempTimeZoneOffset = new TimeSpan(0);
- if (!ParseTimeZoneOffset(ref str, 3, ref tempTimeZoneOffset)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return (false);
- }
- if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset) {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K');
- return (false);
- }
- result.timeZoneOffset = tempTimeZoneOffset;
- result.flags |= ParseFlags.TimeZoneUsed;
- }
- // Otherwise it is unspecified and we consume no characters
- break;
- case ':':
- // We match the separator in time pattern with the character in the time string if both equal to ':' or the date separator is matching the characters in the date string
- // We have to exclude the case when the time separator is more than one character and starts with ':' something like "::" for instance.
- if (((dtfi.TimeSeparator.Length > 1 && dtfi.TimeSeparator[0] == ':') || !str.Match(':')) &&
- !str.Match(dtfi.TimeSeparator)) {
- // A time separator is expected.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- break;
- case '/':
- // We match the separator in date pattern with the character in the date string if both equal to '/' or the date separator is matching the characters in the date string
- // We have to exclude the case when the date separator is more than one character and starts with '/' something like "//" for instance.
- if (((dtfi.DateSeparator.Length > 1 && dtfi.DateSeparator[0] == '/') || !str.Match('/')) &&
- !str.Match(dtfi.DateSeparator))
- {
- // A date separator is expected.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- break;
- case '\"':
- case '\'':
- StringBuilder enquotedString = new StringBuilder();
- // 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);
- return (false);
- }
- format.Index += tokenLen - 1;
-
- // Some cultures uses space in the quoted string. E.g. Spanish has long date format as:
- // "dddd, dd' de 'MMMM' de 'yyyy". When inner spaces flag is set, we should skip whitespaces if there is space
- // in the quoted string.
- String quotedStr = enquotedString.ToString();
-
- for (int i = 0; i < quotedStr.Length; i++) {
- if (quotedStr[i] == ' ' && parseInfo.fAllowInnerWhite) {
- str.SkipWhiteSpaces();
- } else if (!str.Match(quotedStr[i])) {
- // Can not find the matching quoted string.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- }
-
- // The "r" and "u" formats incorrectly quoted 'GMT' and 'Z', respectively. We cannot
- // correct this mistake for DateTime.ParseExact for compatibility reasons, but we can
- // fix it for DateTimeOffset.ParseExact as DateTimeOffset has not been publically released
- // with this issue.
- if ((result.flags & ParseFlags.CaptureOffset) != 0) {
- if ((result.flags & ParseFlags.Rfc1123Pattern) != 0 && quotedStr == GMTName) {
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = TimeSpan.Zero;
- }
- else if ((result.flags & ParseFlags.UtcSortPattern) != 0 && quotedStr == ZuluName) {
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = TimeSpan.Zero;
- }
- }
-
- break;
- case '%':
- // Skip this so we can get to the next pattern character.
- // Used in case like "%d", "%y"
-
- // 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);
- return false;
- }
- break;
- case '\\':
- // Escape character. For example, "\d".
- // Get the next character in format, and see if we can
- // find a match in str.
- if (format.GetNext()) {
- if (!str.Match(format.GetChar())) {
- // Can not find a match for the escaped character.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- } else {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
- return false;
- }
- break;
- case '.':
- if (!str.Match(ch)) {
- if (format.GetNext()) {
- // If we encounter the pattern ".F", and the dot is not present, it is an optional
- // second fraction and we can skip this format.
- if (format.Match('F')) {
- format.GetRepeatCount();
- break;
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- break;
- default:
- if (ch == ' ') {
- if (parseInfo.fAllowInnerWhite) {
- // Skip whitespaces if AllowInnerWhite.
- // Do nothing here.
- } else {
- if (!str.Match(ch)) {
- // If the space does not match, and trailing space is allowed, we do
- // one more step to see if the next format character can lead to
- // successful parsing.
- // This is used to deal with special case that a empty string can match
- // a specific pattern.
- // The example here is af-ZA, which has a time format like "hh:mm:ss tt". However,
- // its AM symbol is "" (empty string). If fAllowTrailingWhite is used, and time is in
- // the AM, we will trim the whitespaces at the end, which will lead to a failure
- // when we are trying to match the space before "tt".
- if (parseInfo.fAllowTrailingWhite) {
- if (format.GetNext()) {
- if (ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result)) {
- return (true);
- }
- }
- }
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- // Found a macth.
- }
- } else {
- if (format.MatchSpecifiedWord(GMTName)) {
- format.Index += (GMTName.Length - 1);
- // Found GMT string in format. This means the DateTime string
- // is in GMT timezone.
- result.flags |= ParseFlags.TimeZoneUsed;
- result.timeZoneOffset = TimeSpan.Zero;
- if (!str.Match(GMTName)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- } else if (!str.Match(ch)) {
- // ch is expected.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- }
- break;
- } // switch
- return (true);
- }
-
- //
- // The pos should point to a quote character. This method will
- // get the string enclosed by the quote character.
- //
- internal static bool TryParseQuoteString(String format, int pos, StringBuilder result, out int returnValue) {
- //
- // NOTE : pos will be the index of the quote character in the 'format' string.
- //
- returnValue = 0;
- int formatLen = format.Length;
- int beginPos = pos;
- char quoteChar = format[pos++]; // Get the character used to quote the following string.
-
- bool foundQuote = false;
- while (pos < formatLen) {
- char ch = format[pos++];
- if (ch == quoteChar) {
- foundQuote = true;
- break;
- }
- else if (ch == '\\') {
- // The following are used to support escaped character.
- // Escaped character is also supported in the quoted string.
- // Therefore, someone can use a format like "'minute:' mm\"" to display:
- // minute: 45"
- // because the second double quote is escaped.
- if (pos < formatLen) {
- result.Append(format[pos++]);
- } else {
- //
- // This means that '\' is at the end of the formatting string.
- //
- return false;
- }
- } else {
- result.Append(ch);
- }
- }
-
- if (!foundQuote) {
- // Here we can't find the matching quote.
- return false;
- }
-
- //
- // Return the character count including the begin/end quote characters and enclosed string.
- //
- returnValue = (pos - beginPos);
- return true;
- }
-
-
-
-
- /*=================================DoStrictParse==================================
- **Action: Do DateTime parsing using the format in formatParam.
- **Returns: The parsed DateTime.
- **Arguments:
- **Exceptions:
- **
- **Notes:
- ** When the following general formats are used, InvariantInfo is used in dtfi:
- ** 'r', 'R', 's'.
- ** When the following general formats are used, the time is assumed to be in Universal time.
- **
- **Limitations:
- ** Only GregarianCalendar is supported for now.
- ** Only support GMT timezone.
- ==============================================================================*/
-
- private static bool DoStrictParse(
- String s,
- String formatParam,
- DateTimeStyles styles,
- DateTimeFormatInfo dtfi,
- ref DateTimeResult result) {
-
-
-
- ParsingInfo parseInfo = new ParsingInfo();
- parseInfo.Init();
-
- parseInfo.calendar = dtfi.Calendar;
- parseInfo.fAllowInnerWhite = ((styles & DateTimeStyles.AllowInnerWhite) != 0);
- parseInfo.fAllowTrailingWhite = ((styles & DateTimeStyles.AllowTrailingWhite) != 0);
-
- // We need the original values of the following two below.
- String originalFormat = formatParam;
-
- if (formatParam.Length == 1) {
- if (((result.flags & ParseFlags.CaptureOffset) != 0) && formatParam[0] == 'U') {
- // The 'U' format is not allowed for DateTimeOffset
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
- return false;
- }
- formatParam = ExpandPredefinedFormat(formatParam, ref dtfi, ref parseInfo, ref result);
- }
-
- bool bTimeOnly = false;
- result.calendar = parseInfo.calendar;
-
- if (parseInfo.calendar.ID == Calendar.CAL_HEBREW) {
- parseInfo.parseNumberDelegate = m_hebrewNumberParser;
- parseInfo.fCustomNumberParser = true;
- }
-
- // Reset these values to negative one so that we could throw exception
- // if we have parsed every item twice.
- result.Hour = result.Minute = result.Second = -1;
-
- __DTString format = new __DTString(formatParam, dtfi, false);
- __DTString str = new __DTString(s, dtfi, false);
-
- if (parseInfo.fAllowTrailingWhite) {
- // Trim trailing spaces if AllowTrailingWhite.
- format.TrimTail();
- format.RemoveTrailingInQuoteSpaces();
- str.TrimTail();
- }
-
- if ((styles & DateTimeStyles.AllowLeadingWhite) != 0) {
- format.SkipWhiteSpaces();
- format.RemoveLeadingInQuoteSpaces();
- str.SkipWhiteSpaces();
- }
-
- //
- // Scan every character in format and match the pattern in str.
- //
- while (format.GetNext()) {
- // We trim inner spaces here, so that we will not eat trailing spaces when
- // AllowTrailingWhite is not used.
- if (parseInfo.fAllowInnerWhite) {
- str.SkipWhiteSpaces();
- }
- if (!ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result)) {
- return (false);
- }
- }
-
- if (str.Index < str.Value.Length - 1) {
- // There are still remaining character in str.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
-
- if (parseInfo.fUseTwoDigitYear && ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) == 0)) {
- // 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);
- return false;
- }
- try {
- result.Year = parseInfo.calendar.ToFourDigitYear(result.Year);
- }
- catch (ArgumentOutOfRangeException e) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", e);
- return false;
- }
- }
-
- if (parseInfo.fUseHour12) {
- if (parseInfo.timeMark == TM.NotSet) {
- // hh is used, but no AM/PM designator is specified.
- // Assume the time is AM.
- // Don't throw exceptions in here becasue it is very confusing for the caller.
- // I always got confused myself when I use "hh:mm:ss" to parse a time string,
- // and ParseExact() throws on me (because I didn't use the 24-hour clock 'HH').
- parseInfo.timeMark = TM.AM;
- }
- if (result.Hour > 12) {
- // AM/PM is used, but the value for HH is too big.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- if (parseInfo.timeMark == TM.AM) {
- if (result.Hour == 12) {
- result.Hour = 0;
- }
- } else {
- result.Hour = (result.Hour == 12) ? 12 : result.Hour + 12;
- }
- }
- else
- {
- // Military (24-hour time) mode
- //
- // AM cannot be set with a 24-hour time like 17:15.
- // PM cannot be set with a 24-hour time like 03:15.
- if ( (parseInfo.timeMark == TM.AM && result.Hour >= 12)
- ||(parseInfo.timeMark == TM.PM && result.Hour < 12)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
- return false;
- }
- }
-
-
- // Check if the parased string only contains hour/minute/second values.
- bTimeOnly = (result.Year == -1 && result.Month == -1 && result.Day == -1);
- if (!CheckDefaultDateTime(ref result, ref parseInfo.calendar, styles)) {
- return false;
- }
-
- if (!bTimeOnly && dtfi.HasYearMonthAdjustment) {
- if (!dtfi.YearMonthAdjustment(ref result.Year, ref result.Month, ((result.flags & ParseFlags.ParsedMonthName) != 0))) {
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "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);
- return false;
- }
- if (result.fraction > 0) {
- result.parsedDate = result.parsedDate.AddTicks((long)Math.Round(result.fraction * Calendar.TicksPerSecond));
- }
-
- //
- // We have to check day of week before we adjust to the time zone.
- // It is because the value of day of week may change after adjusting
- // to the time zone.
- //
- if (parseInfo.dayOfWeek != -1) {
- //
- // Check if day of week is correct.
- //
- if (parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(result.parsedDate)) {
- result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
- return false;
- }
- }
-
-
- if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) {
- return false;
- }
- return true;
- }
-
- private static Exception GetDateTimeParseException(ref DateTimeResult result) {
- switch (result.failure) {
- case ParseFailureKind.ArgumentNull:
- return new ArgumentNullException(result.failureArgumentName, Environment.GetResourceString(result.failureMessageID));
- case ParseFailureKind.Format:
- return new FormatException(Environment.GetResourceString(result.failureMessageID));
- case ParseFailureKind.FormatWithParameter:
- return new FormatException(Environment.GetResourceString(result.failureMessageID, result.failureMessageFormatArgument));
- case ParseFailureKind.FormatBadDateTimeCalendar:
- return new FormatException(Environment.GetResourceString(result.failureMessageID, result.calendar));
- default:
- Debug.Assert(false, "Unkown DateTimeParseFailure: " + result);
- return null;
-
- }
- }
-
- // Builds with _LOGGING defined (x86dbg, amd64chk, etc) support tracing
- // Set the following internal-only/unsupported environment variables to enable DateTime tracing to the console:
- //
- // COMPlus_LogEnable=1
- // COMPlus_LogToConsole=1
- // COMPlus_LogLevel=9
- // COMPlus_ManagedLogFacility=0x00001000
- [Pure]
- [Conditional("_LOGGING")]
- internal static void LexTraceExit(string message, DS dps) {
-#if _LOGGING
- if (!_tracingEnabled)
- return;
- BCLDebug.Trace("DATETIME", "[DATETIME] Lex return {0}, DS.{1}", message, dps);
-#endif // _LOGGING
- }
- [Pure]
- [Conditional("_LOGGING")]
- internal static void PTSTraceExit(DS dps, bool passed) {
-#if _LOGGING
- if (!_tracingEnabled)
- return;
- BCLDebug.Trace("DATETIME", "[DATETIME] ProcessTerminalState {0} @ DS.{1}", passed ? "passed" : "failed", dps);
-#endif // _LOGGING
- }
- [Pure]
- [Conditional("_LOGGING")]
- internal static void TPTraceExit(string message, DS dps) {
-#if _LOGGING
- if (!_tracingEnabled)
- return;
- BCLDebug.Trace("DATETIME", "[DATETIME] TryParse return {0}, DS.{1}", message, dps);
-#endif // _LOGGING
- }
- [Pure]
- [Conditional("_LOGGING")]
- internal static void DTFITrace(DateTimeFormatInfo dtfi) {
-#if _LOGGING
- if (!_tracingEnabled)
- return;
-
- BCLDebug.Trace("DATETIME", "[DATETIME] DateTimeFormatInfo Properties");
-#if !FEATURE_COREFX_GLOBALIZATION
- BCLDebug.Trace("DATETIME", " NativeCalendarName {0}", Hex(dtfi.NativeCalendarName));
-#endif
- BCLDebug.Trace("DATETIME", " AMDesignator {0}", Hex(dtfi.AMDesignator));
- BCLDebug.Trace("DATETIME", " PMDesignator {0}", Hex(dtfi.PMDesignator));
- BCLDebug.Trace("DATETIME", " TimeSeparator {0}", Hex(dtfi.TimeSeparator));
- BCLDebug.Trace("DATETIME", " AbbrvDayNames {0}", Hex(dtfi.AbbreviatedDayNames));
- BCLDebug.Trace("DATETIME", " ShortestDayNames {0}", Hex(dtfi.ShortestDayNames));
- BCLDebug.Trace("DATETIME", " DayNames {0}", Hex(dtfi.DayNames));
- BCLDebug.Trace("DATETIME", " AbbrvMonthNames {0}", Hex(dtfi.AbbreviatedMonthNames));
- BCLDebug.Trace("DATETIME", " MonthNames {0}", Hex(dtfi.MonthNames));
- BCLDebug.Trace("DATETIME", " AbbrvMonthGenNames {0}", Hex(dtfi.AbbreviatedMonthGenitiveNames));
- BCLDebug.Trace("DATETIME", " MonthGenNames {0}", Hex(dtfi.MonthGenitiveNames));
-#endif // _LOGGING
- }
-#if _LOGGING
- [Pure]
- // return a string in the form: "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
- internal static string Hex(string[] strs) {
- if (strs == null || strs.Length == 0)
- return String.Empty;
- if (strs.Length == 1)
- return Hex(strs[0]);
-
- int curLineLength = 0;
- int maxLineLength = 55;
- int newLinePadding = 20;
-
-
- //invariant: strs.Length >= 2
- StringBuilder buffer = new StringBuilder();
- buffer.Append(Hex(strs[0]));
- curLineLength = buffer.Length;
- String s;
-
- for (int i = 1; i < strs.Length-1; i++) {
- s = Hex(strs[i]);
-
- if (s.Length > maxLineLength || (curLineLength + s.Length + 2) > maxLineLength) {
- buffer.Append(',');
- buffer.Append(Environment.NewLine);
- buffer.Append(' ', newLinePadding);
- curLineLength = 0;
- }
- else {
- buffer.Append(", ");
- curLineLength += 2;
- }
- buffer.Append(s);
- curLineLength += s.Length;
- }
-
- buffer.Append(',');
- s = Hex(strs[strs.Length-1]);
- if (s.Length > maxLineLength || (curLineLength + s.Length + 6) > maxLineLength) {
- buffer.Append(Environment.NewLine);
- buffer.Append(' ', newLinePadding);
- }
- else {
- buffer.Append(' ');
- }
- buffer.Append(s);
- return buffer.ToString();
- }
- [Pure]
- // return a string in the form: "Sun"
- internal static string Hex(string str) {
- StringBuilder buffer = new StringBuilder();
- buffer.Append("\"");
- for (int i = 0; i < str.Length; i++) {
- if (str[i] <= '\x007f')
- buffer.Append(str[i]);
- else
- buffer.Append("\\u" + ((int)str[i]).ToString("x4", CultureInfo.InvariantCulture));
- }
- buffer.Append("\"");
- return buffer.ToString();
- }
- [Pure]
- // return an unicode escaped string form of char c
- internal static String Hex(char c) {
- if (c <= '\x007f')
- return c.ToString(CultureInfo.InvariantCulture);
- else
- return "\\u" + ((int)c).ToString("x4", CultureInfo.InvariantCulture);
- }
-
- internal static bool _tracingEnabled = BCLDebug.CheckEnabled("DATETIME");
-#endif // _LOGGING
- }
-
-
- //
- // This is a string parsing helper which wraps a String object.
- // It has a Index property which tracks
- // the current parsing pointer of the string.
- //
- internal
- struct __DTString
- {
-
- //
- // Value propery: stores the real string to be parsed.
- //
- internal String Value;
-
- //
- // Index property: points to the character that we are currently parsing.
- //
- internal int Index;
-
- // The length of Value string.
- internal int len;
-
- // The current chracter to be looked at.
- internal char m_current;
-
- private CompareInfo m_info;
- // Flag to indicate if we encouter an digit, we should check for token or not.
- // In some cultures, such as mn-MN, it uses "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440" in month names.
- private bool m_checkDigitToken;
-
- internal __DTString(String str, DateTimeFormatInfo dtfi, bool checkDigitToken) : this (str, dtfi)
- {
- m_checkDigitToken = checkDigitToken;
- }
-
- internal __DTString(String str, DateTimeFormatInfo dtfi)
- {
- Index = -1;
- Value = str;
- len = Value.Length;
-
- m_current = '\0';
- if (dtfi != null)
- {
- m_info = dtfi.CompareInfo;
- m_checkDigitToken = ((dtfi.FormatFlags & DateTimeFormatFlags.UseDigitPrefixInTokens) != 0);
- } else
- {
- m_info = Thread.CurrentThread.CurrentCulture.CompareInfo;
- m_checkDigitToken = false;
- }
- }
-
- internal CompareInfo CompareInfo
- {
- get { return m_info; }
- }
-
- //
- // Advance the Index.
- // Return true if Index is NOT at the end of the string.
- //
- // Typical usage:
- // while (str.GetNext())
- // {
- // char ch = str.GetChar()
- // }
- internal bool GetNext() {
- Index++;
- if (Index < len) {
- m_current = Value[Index];
- return (true);
- }
- return (false);
- }
-
- internal bool AtEnd()
- {
- return Index < len ? false : true;
- }
-
- internal bool Advance(int count) {
- Debug.Assert(Index + count <= len, "__DTString::Advance: Index + count <= len");
- Index += count;
- if (Index < len) {
- m_current = Value[Index];
- return (true);
- }
- return (false);
- }
-
-
- // Used by DateTime.Parse() to get the next token.
- internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi) {
- tokenValue = 0;
- if (Index >= len) {
- tokenType = TokenType.EndOfString;
- return;
- }
-
- tokenType = TokenType.UnknownToken;
-
-Start:
- if (DateTimeParse.IsDigit(m_current)) {
- // This is a digit.
- tokenValue = m_current - '0';
- int value;
- int start = Index;
-
- //
- // Collect other digits.
- //
- while (++Index < len)
- {
- m_current = Value[Index];
- value = m_current - '0';
- if (value >= 0 && value <= 9) {
- tokenValue = tokenValue * 10 + value;
- } else {
- break;
- }
- }
- if (Index - start > DateTimeParse.MaxDateTimeNumberDigits) {
- tokenType = TokenType.NumberToken;
- tokenValue = -1;
- } else if (Index - start < 3) {
- tokenType = TokenType.NumberToken;
- } else {
- // If there are more than 3 digits, assume that it's a year value.
- tokenType = TokenType.YearNumberToken;
- }
- if (m_checkDigitToken)
- {
- int save = Index;
- char saveCh = m_current;
- // Re-scan using the staring Index to see if this is a token.
- Index = start; // To include the first digit.
- m_current = Value[Index];
- TokenType tempType;
- int tempValue;
- // This DTFI has tokens starting with digits.
- // E.g. mn-MN has month name like "\x0031\x00a0\x0434\x04af\x0433\x044d\x044d\x0440\x00a0\x0441\x0430\x0440"
- if (dtfi.Tokenize(TokenType.RegularTokenMask, out tempType, out tempValue, ref this))
- {
- tokenType = tempType;
- tokenValue = tempValue;
- // This is a token, so the Index has been advanced propertly in DTFI.Tokenizer().
- } else
- {
- // Use the number token value.
- // Restore the index.
- Index = save;
- m_current = saveCh;
- }
-
- }
-
- } else if (Char.IsWhiteSpace( m_current)) {
- // Just skip to the next character.
- while (++Index < len) {
- m_current = Value[Index];
- if (!(Char.IsWhiteSpace(m_current))) {
- goto Start;
- }
- }
- // We have reached the end of string.
- tokenType = TokenType.EndOfString;
- } else {
- dtfi.Tokenize(TokenType.RegularTokenMask, out tokenType, out tokenValue, ref this);
- }
- }
-
- internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator) {
- indexBeforeSeparator = Index;
- charBeforeSeparator = m_current;
- TokenType tokenType;
- if (!SkipWhiteSpaceCurrent()) {
- // Reach the end of the string.
- return (TokenType.SEP_End);
- }
- if (!DateTimeParse.IsDigit(m_current)) {
- // Not a digit. Tokenize it.
- int tokenValue;
- bool found = dtfi.Tokenize(TokenType.SeparatorTokenMask, out tokenType, out tokenValue, ref this);
- if (!found) {
- tokenType = TokenType.SEP_Space;
- }
- } else {
- // Do nothing here. If we see a number, it will not be a separator. There is no need wasting time trying to find the
- // separator token.
- tokenType = TokenType.SEP_Space;
- }
- return (tokenType);
- }
-
- internal bool MatchSpecifiedWord(String target) {
- return MatchSpecifiedWord(target, target.Length + Index);
- }
-
- internal bool MatchSpecifiedWord(String target, int endIndex) {
- int count = endIndex - Index;
-
- if (count != target.Length) {
- return false;
- }
-
- if (Index + count > len) {
- return false;
- }
-
- return (m_info.Compare(Value, Index, count, target, 0, count, CompareOptions.IgnoreCase)==0);
- }
-
- private static Char[] WhiteSpaceChecks = new Char[] { ' ', '\u00A0' };
-
- internal bool MatchSpecifiedWords(String target, bool checkWordBoundary, ref int matchLength) {
- int valueRemaining = Value.Length - Index;
- matchLength = target.Length;
-
- if (matchLength > valueRemaining || m_info.Compare(Value, Index, matchLength, target, 0, matchLength, CompareOptions.IgnoreCase) !=0) {
- // Check word by word
- int targetPosition = 0; // Where we are in the target string
- int thisPosition = Index; // Where we are in this string
- int wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition);
- if (wsIndex == -1) {
- return false;
- }
- do {
- int segmentLength = wsIndex - targetPosition;
- if (thisPosition >= Value.Length - segmentLength) { // Subtraction to prevent overflow.
- return false;
- }
- if (segmentLength == 0) {
- // If segmentLength == 0, it means that we have leading space in the target string.
- // In that case, skip the leading spaces in the target and this string.
- matchLength--;
- } else {
- // Make sure we also have whitespace in the input string
- if (!Char.IsWhiteSpace(Value[thisPosition + segmentLength])) {
- return false;
- }
- if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) !=0) {
- return false;
- }
- // Advance the input string
- thisPosition = thisPosition + segmentLength + 1;
- }
- // Advance our target string
- targetPosition = wsIndex + 1;
-
-
- // Skip past multiple whitespace
- while (thisPosition < Value.Length && Char.IsWhiteSpace(Value[thisPosition])) {
- thisPosition++;
- matchLength++;
- }
- } while ((wsIndex = target.IndexOfAny(WhiteSpaceChecks, targetPosition)) >= 0);
- // now check the last segment;
- if (targetPosition < target.Length) {
- int segmentLength = target.Length - targetPosition;
- if (thisPosition > Value.Length - segmentLength) {
- return false;
- }
- if (m_info.Compare(Value, thisPosition, segmentLength, target, targetPosition, segmentLength, CompareOptions.IgnoreCase) !=0) {
- return false;
- }
- }
- }
-
- if (checkWordBoundary) {
- int nextCharIndex = Index + matchLength;
- if (nextCharIndex < Value.Length) {
- if (Char.IsLetter(Value[nextCharIndex])) {
- return (false);
- }
- }
- }
- return (true);
- }
-
- //
- // Check to see if the string starting from Index is a prefix of
- // str.
- // If a match is found, true value is returned and Index is updated to the next character to be parsed.
- // Otherwise, Index is unchanged.
- //
- internal bool Match(String str) {
- if (++Index >= len) {
- return (false);
- }
-
- if (str.Length > (Value.Length - Index)) {
- return false;
- }
-
- if (m_info.Compare(Value, Index, str.Length, str, 0, str.Length, CompareOptions.Ordinal)==0) {
- // Update the Index to the end of the matching string.
- // So the following GetNext()/Match() opeartion will get
- // the next character to be parsed.
- Index += (str.Length - 1);
- return (true);
- }
- return (false);
- }
-
- internal bool Match(char ch) {
- if (++Index >= len) {
- return (false);
- }
- if (Value[Index] == ch) {
- m_current = ch;
- return (true);
- }
- Index--;
- return (false);
- }
-
- //
- // Actions: From the current position, try matching the longest word in the specified string array.
- // E.g. words[] = {"AB", "ABC", "ABCD"}, if the current position points to a substring like "ABC DEF",
- // MatchLongestWords(words, ref MaxMatchStrLen) will return 1 (the index), and maxMatchLen will be 3.
- // Returns:
- // The index that contains the longest word to match
- // Arguments:
- // words The string array that contains words to search.
- // maxMatchStrLen [in/out] the initailized maximum length. This parameter can be used to
- // find the longest match in two string arrays.
- //
- internal int MatchLongestWords(String[] words, ref int maxMatchStrLen) {
- int result = -1;
- for (int i = 0; i < words.Length; i++) {
- String word = words[i];
- int matchLength = word.Length;
- if (MatchSpecifiedWords(word, false, ref matchLength)) {
- if (matchLength > maxMatchStrLen) {
- maxMatchStrLen = matchLength;
- result = i;
- }
- }
- }
-
- return (result);
- }
-
- //
- // Get the number of repeat character after the current character.
- // For a string "hh:mm:ss" at Index of 3. GetRepeatCount() = 2, and Index
- // will point to the second ':'.
- //
- internal int GetRepeatCount() {
- char repeatChar = Value[Index];
- int pos = Index + 1;
- while ((pos < len) && (Value[pos] == repeatChar)) {
- pos++;
- }
- int repeatCount = (pos - Index);
- // Update the Index to the end of the repeated characters.
- // So the following GetNext() opeartion will get
- // the next character to be parsed.
- Index = pos - 1;
- return (repeatCount);
- }
-
- // Return false when end of string is encountered or a non-digit character is found.
- internal bool GetNextDigit() {
- if (++Index >= len) {
- return (false);
- }
- return (DateTimeParse.IsDigit(Value[Index]));
- }
-
- //
- // Get the current character.
- //
- internal char GetChar() {
- Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
- return (Value[Index]);
- }
-
- //
- // Convert the current character to a digit, and return it.
- //
- internal int GetDigit() {
- Debug.Assert(Index >= 0 && Index < len, "Index >= 0 && Index < len");
- Debug.Assert(DateTimeParse.IsDigit(Value[Index]), "IsDigit(Value[Index])");
- return (Value[Index] - '0');
- }
-
- //
- // Eat White Space ahead of the current position
- //
- // Return false if end of string is encountered.
- //
- internal void SkipWhiteSpaces()
- {
- // Look ahead to see if the next character
- // is a whitespace.
- while (Index+1 < len)
- {
- char ch = Value[Index+1];
- if (!Char.IsWhiteSpace(ch)) {
- return;
- }
- Index++;
- }
- return;
- }
-
- //
- // Skip white spaces from the current position
- //
- // Return false if end of string is encountered.
- //
- internal bool SkipWhiteSpaceCurrent()
- {
- if (Index >= len) {
- return (false);
- }
-
- if (!Char.IsWhiteSpace(m_current))
- {
- return (true);
- }
-
- while (++Index < len)
- {
- m_current = Value[Index];
- if (!Char.IsWhiteSpace(m_current))
- {
- return (true);
- }
- // Nothing here.
- }
- return (false);
- }
-
- internal void TrimTail() {
- int i = len - 1;
- while (i >= 0 && Char.IsWhiteSpace(Value[i])) {
- i--;
- }
- Value = Value.Substring(0, i + 1);
- len = Value.Length;
- }
-
- // Trim the trailing spaces within a quoted string.
- // Call this after TrimTail() is done.
- internal void RemoveTrailingInQuoteSpaces() {
- int i = len - 1;
- if (i <= 1) {
- return;
- }
- char ch = Value[i];
- // Check if the last character is a quote.
- if (ch == '\'' || ch == '\"') {
- if (Char.IsWhiteSpace(Value[i-1])) {
- i--;
- while (i >= 1 && Char.IsWhiteSpace(Value[i-1])) {
- i--;
- }
- Value = Value.Remove(i, Value.Length - 1 - i);
- len = Value.Length;
- }
- }
- }
-
- // Trim the leading spaces within a quoted string.
- // Call this after the leading spaces before quoted string are trimmed.
- internal void RemoveLeadingInQuoteSpaces() {
- if (len <= 2) {
- return;
- }
- int i = 0;
- char ch = Value[i];
- // Check if the last character is a quote.
- if (ch == '\'' || ch == '\"') {
- while ((i + 1) < len && Char.IsWhiteSpace(Value[i+1])) {
- i++;
- }
- if (i != 0) {
- Value = Value.Remove(1, i);
- len = Value.Length;
- }
- }
- }
-
- internal DTSubString GetSubString() {
- DTSubString sub = new DTSubString();
- sub.index = Index;
- sub.s = Value;
- while (Index + sub.length < len) {
- DTSubStringType currentType;
- Char ch = Value[Index + sub.length];
- if (ch >= '0' && ch <= '9') {
- currentType = DTSubStringType.Number;
- }
- else {
- currentType = DTSubStringType.Other;
- }
-
- if (sub.length == 0) {
- sub.type = currentType;
- }
- else {
- if (sub.type != currentType) {
- break;
- }
- }
- sub.length++;
- if (currentType == DTSubStringType.Number) {
- // Incorporate the number into the value
- // Limit the digits to prevent overflow
- if (sub.length > DateTimeParse.MaxDateTimeNumberDigits) {
- sub.type = DTSubStringType.Invalid;
- return sub;
- }
- int number = ch - '0';
- Debug.Assert(number >= 0 && number <= 9, "number >= 0 && number <= 9");
- sub.value = sub.value * 10 + number;
- }
- else {
- // For non numbers, just return this length 1 token. This should be expanded
- // to more types of thing if this parsing approach is used for things other
- // than numbers and single characters
- break;
- }
- }
- if (sub.length == 0) {
- sub.type = DTSubStringType.End;
- return sub;
- }
-
- return sub;
- }
-
- internal void ConsumeSubString(DTSubString sub) {
- Debug.Assert(sub.index == Index, "sub.index == Index");
- Debug.Assert(sub.index + sub.length <= len, "sub.index + sub.length <= len");
- Index = sub.index + sub.length;
- if (Index < len) {
- m_current = Value[Index];
- }
- }
- }
-
- internal enum DTSubStringType {
- Unknown = 0,
- Invalid = 1,
- Number = 2,
- End = 3,
- Other = 4,
- }
-
- internal struct DTSubString {
- internal String s;
- internal Int32 index;
- internal Int32 length;
- internal DTSubStringType type;
- internal Int32 value;
-
- internal Char this[Int32 relativeIndex] {
- get {
- return s[index + relativeIndex];
- }
- }
- }
-
- //
- // The buffer to store the parsing token.
- //
- internal
- struct DateTimeToken {
- internal DateTimeParse.DTT dtt; // Store the token
- internal TokenType suffix; // Store the CJK Year/Month/Day suffix (if any)
- internal int num; // Store the number that we are parsing (if any)
- }
-
- //
- // The buffer to store temporary parsing information.
- //
- internal
- unsafe struct DateTimeRawInfo {
- private int* num;
- internal int numCount;
- internal int month;
- internal int year;
- internal int dayOfWeek;
- internal int era;
- internal DateTimeParse.TM timeMark;
- internal double fraction;
- internal bool hasSameDateAndTimeSeparators;
- //
-
- internal bool timeZone;
-
- internal void Init(int * numberBuffer) {
- month = -1;
- year = -1;
- dayOfWeek = -1;
- era = -1;
- timeMark = DateTimeParse.TM.NotSet;
- fraction = -1;
- num = numberBuffer;
- }
- internal unsafe void AddNumber(int value) {
- num[numCount++] = value;
- }
- internal unsafe int GetNumber(int index) {
- return num[index];
- }
- }
-
- internal enum ParseFailureKind {
- None = 0,
- ArgumentNull = 1,
- Format = 2,
- FormatWithParameter = 3,
- FormatBadDateTimeCalendar = 4, // FormatException when ArgumentOutOfRange is thrown by a Calendar.TryToDateTime().
- };
-
- [Flags]
- internal enum ParseFlags {
- HaveYear = 0x00000001,
- HaveMonth = 0x00000002,
- HaveDay = 0x00000004,
- HaveHour = 0x00000008,
- HaveMinute = 0x00000010,
- HaveSecond = 0x00000020,
- HaveTime = 0x00000040,
- HaveDate = 0x00000080,
- TimeZoneUsed = 0x00000100,
- TimeZoneUtc = 0x00000200,
- ParsedMonthName = 0x00000400,
- CaptureOffset = 0x00000800,
- YearDefault = 0x00001000,
- Rfc1123Pattern = 0x00002000,
- UtcSortPattern = 0x00004000,
- }
-
- //
- // This will store the result of the parsing. And it will be eventually
- // used to construct a DateTime instance.
- //
- internal
- struct DateTimeResult
- {
- internal int Year;
- internal int Month;
- internal int Day;
- //
- // Set time defualt to 00:00:00.
- //
- internal int Hour;
- internal int Minute;
- internal int Second;
- internal double fraction;
-
- internal int era;
-
- internal ParseFlags flags;
-
- internal TimeSpan timeZoneOffset;
-
- internal Calendar calendar;
-
- internal DateTime parsedDate;
-
- internal ParseFailureKind failure;
- internal string failureMessageID;
- internal object failureMessageFormatArgument;
- internal string failureArgumentName;
-
- internal void Init() {
- Year = -1;
- Month = -1;
- Day = -1;
- fraction = -1;
- era = -1;
- }
-
- internal void SetDate(int year, int month, int day)
- {
- Year = year;
- Month = month;
- Day = day;
- }
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) {
- this.failure = failure;
- this.failureMessageID = failureMessageID;
- this.failureMessageFormatArgument = failureMessageFormatArgument;
- }
-
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName) {
- this.failure = failure;
- this.failureMessageID = failureMessageID;
- this.failureMessageFormatArgument = failureMessageFormatArgument;
- this.failureArgumentName = failureArgumentName;
- }
-
-
-
-
- }
-
- // This is the helper data structure used in ParseExact().
- internal struct ParsingInfo {
-
- internal Calendar calendar;
- internal int dayOfWeek;
- internal DateTimeParse.TM timeMark;
-
- internal bool fUseHour12;
- internal bool fUseTwoDigitYear;
- internal bool fAllowInnerWhite;
- internal bool fAllowTrailingWhite;
- internal bool fCustomNumberParser;
- internal DateTimeParse.MatchNumberDelegate parseNumberDelegate;
-
- internal void Init() {
- dayOfWeek = -1;
- timeMark = DateTimeParse.TM.NotSet;
- }
-
- }
-
- //
- // The type of token that will be returned by DateTimeFormatInfo.Tokenize().
- //
- internal enum TokenType {
- // The valid token should start from 1.
-
- // Regular tokens. The range is from 0x00 ~ 0xff.
- NumberToken = 1, // The number. E.g. "12"
- YearNumberToken = 2, // The number which is considered as year number, which has 3 or more digits. E.g. "2003"
- Am = 3, // AM timemark. E.g. "AM"
- Pm = 4, // PM timemark. E.g. "PM"
- MonthToken = 5, // A word (or words) that represents a month name. E.g. "March"
- EndOfString = 6, // End of string
- DayOfWeekToken = 7, // A word (or words) that represents a day of week name. E.g. "Monday" or "Mon"
- TimeZoneToken = 8, // A word that represents a timezone name. E.g. "GMT"
- EraToken = 9, // A word that represents a era name. E.g. "A.D."
- DateWordToken = 10, // A word that can appear in a DateTime string, but serves no parsing semantics. E.g. "de" in Spanish culture.
- UnknownToken = 11, // An unknown word, which signals an error in parsing.
- HebrewNumber = 12, // A number that is composed of Hebrew text. Hebrew calendar uses Hebrew digits for year values, month values, and day values.
- JapaneseEraToken= 13, // Era name for JapaneseCalendar
- TEraToken = 14, // Era name for TaiwanCalendar
- IgnorableSymbol = 15, // A separator like "," that is equivalent to whitespace
-
-
- // Separator tokens.
- SEP_Unk = 0x100, // Unknown separator.
- SEP_End = 0x200, // The end of the parsing string.
- SEP_Space = 0x300, // Whitespace (including comma).
- SEP_Am = 0x400, // AM timemark. E.g. "AM"
- SEP_Pm = 0x500, // PM timemark. E.g. "PM"
- SEP_Date = 0x600, // date separator. E.g. "/"
- SEP_Time = 0x700, // time separator. E.g. ":"
- SEP_YearSuff = 0x800, // Chinese/Japanese/Korean year suffix.
- SEP_MonthSuff = 0x900, // Chinese/Japanese/Korean month suffix.
- SEP_DaySuff = 0xa00, // Chinese/Japanese/Korean day suffix.
- SEP_HourSuff = 0xb00, // Chinese/Japanese/Korean hour suffix.
- SEP_MinuteSuff = 0xc00, // Chinese/Japanese/Korean minute suffix.
- SEP_SecondSuff = 0xd00, // Chinese/Japanese/Korean second suffix.
- SEP_LocalTimeMark = 0xe00, // 'T', used in ISO 8601 format.
- SEP_DateOrOffset = 0xf00, // '-' which could be a date separator or start of a time zone offset
-
- RegularTokenMask = 0x00ff,
- SeparatorTokenMask = 0xff00,
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/DateTimeStyles.cs b/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
deleted file mode 100644
index eadeda8e72..0000000000
--- a/src/mscorlib/src/System/Globalization/DateTimeStyles.cs
+++ /dev/null
@@ -1,49 +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: Contains valid formats for DateTime recognized by
-** the DateTime class' parsing code.
-**
-**
-===========================================================*/
-namespace System.Globalization {
-
-
-[Serializable]
- [Flags]
- public enum DateTimeStyles {
- // Bit flag indicating that leading whitespace is allowed. Character values
- // 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be
- // whitespace.
-
-
- None = 0x00000000,
-
- AllowLeadingWhite = 0x00000001,
-
- AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed.
-
- AllowInnerWhite = 0x00000004,
-
- AllowWhiteSpaces = AllowLeadingWhite | AllowInnerWhite | AllowTrailingWhite,
- // When parsing a date/time string, if all year/month/day are missing, set the default date
- // to 0001/1/1, instead of the current year/month/day.
-
- NoCurrentDateDefault = 0x00000008,
- // When parsing a date/time string, if a timezone specifier ("GMT","Z","+xxxx", "-xxxx" exists), we will
- // ajdust the parsed time based to GMT.
-
- AdjustToUniversal = 0x00000010,
-
- AssumeLocal = 0x00000020,
-
- AssumeUniversal = 0x00000040,
- // Attempt to preserve whether the input is unspecified, local or UTC
- RoundtripKind = 0x00000080,
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/DaylightTime.cs b/src/mscorlib/src/System/Globalization/DaylightTime.cs
deleted file mode 100644
index a21e092955..0000000000
--- a/src/mscorlib/src/System/Globalization/DaylightTime.cs
+++ /dev/null
@@ -1,63 +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.Runtime.InteropServices;
-
-namespace System.Globalization
-{
- // This class represents a starting/ending time for a period of daylight saving time.
- [Serializable]
- public class DaylightTime
- {
- internal DateTime m_start;
- internal DateTime m_end;
- internal TimeSpan m_delta;
-
- private DaylightTime() {
- }
-
- public DaylightTime(DateTime start, DateTime end, TimeSpan delta) {
- m_start = start;
- m_end = end;
- m_delta = delta;
- }
-
- // The start date of a daylight saving period.
- public DateTime Start {
- get {
- return m_start;
- }
- }
-
- // The end date of a daylight saving period.
- public DateTime End {
- get {
- return m_end;
- }
- }
-
- // Delta to stardard offset in ticks.
- public TimeSpan Delta {
- get {
- return m_delta;
- }
- }
-
- }
-
- // Value type version of DaylightTime
- internal struct DaylightTimeStruct
- {
- public DaylightTimeStruct(DateTime start, DateTime end, TimeSpan delta)
- {
- Start = start;
- End = end;
- Delta = delta;
- }
-
- public DateTime Start { get; }
- public DateTime End { get; }
- public TimeSpan Delta { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/DigitShapes.cs b/src/mscorlib/src/System/Globalization/DigitShapes.cs
deleted file mode 100644
index 1513d56f5c..0000000000
--- a/src/mscorlib/src/System/Globalization/DigitShapes.cs
+++ /dev/null
@@ -1,21 +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.
-
-//
-// The enumeration constants used in NumberFormatInfo.DigitSubstitution.
-//
-namespace System.Globalization {
-
-
- [Serializable]
- public enum DigitShapes : int {
-
- Context = 0x0000, // The shape depends on the previous text in the same output.
-
- None = 0x0001, // Gives full Unicode compatibility.
-
- NativeNational = 0x0002, // National shapes determined by LOCALE_SNATIVEDIGITS
- }
-}
-
diff --git a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
deleted file mode 100644
index 3f6df52a96..0000000000
--- a/src/mscorlib/src/System/Globalization/EastAsianLunisolarCalendar.cs
+++ /dev/null
@@ -1,643 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about EastAsianLunisolarCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
-
-
- [Serializable]
- public abstract class EastAsianLunisolarCalendar : Calendar {
- internal const int LeapMonth = 0;
- internal const int Jan1Month = 1;
- internal const int Jan1Date = 2;
- internal const int nDaysPerMonth = 3;
-
- // # of days so far in the solar year
- internal static readonly int[] DaysToMonth365 =
- {
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
- };
-
- internal static readonly int[] DaysToMonth366 =
- {
- 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
- };
-
- internal const int DatePartYear = 0;
- internal const int DatePartDayOfYear = 1;
- internal const int DatePartMonth = 2;
- internal const int DatePartDay = 3;
-
- // Return the type of the East Asian Lunisolar calendars.
- //
-
- public override CalendarAlgorithmType AlgorithmType {
- get {
- return CalendarAlgorithmType.LunisolarCalendar;
- }
- }
-
- // Return the year number in the 60-year cycle.
- //
-
- public virtual int GetSexagenaryYear (DateTime time) {
- CheckTicksRange(time.Ticks);
-
- int year = 0, month = 0, day = 0;
- TimeToLunar(time, ref year, ref month, ref day);
-
- return ((year - 4) % 60) + 1;
- }
-
- // Return the celestial year from the 60-year cycle.
- // The returned value is from 1 ~ 10.
- //
-
- public int GetCelestialStem(int sexagenaryYear) {
- if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) {
- throw new ArgumentOutOfRangeException(
- nameof(sexagenaryYear),
- Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60));
- }
- Contract.EndContractBlock();
-
- return ((sexagenaryYear - 1) % 10) + 1;
- }
-
- // Return the Terrestial Branch from the the 60-year cycle.
- // The returned value is from 1 ~ 12.
- //
-
- public int GetTerrestrialBranch(int sexagenaryYear) {
- if ((sexagenaryYear < 1) || (sexagenaryYear > 60)) {
- throw new ArgumentOutOfRangeException(
- nameof(sexagenaryYear),
- Environment.GetResourceString("ArgumentOutOfRange_Range", 1, 60));
- }
- Contract.EndContractBlock();
-
- return ((sexagenaryYear - 1) % 12) + 1;
- }
-
- internal abstract int GetYearInfo(int LunarYear, int Index);
- internal abstract int GetYear(int year, DateTime time);
- internal abstract int GetGregorianYear(int year, int era);
-
- internal abstract int MinCalendarYear {get;}
- internal abstract int MaxCalendarYear {get;}
- internal abstract EraInfo[] CalEraInfo{get;}
- internal abstract DateTime MinDate {get;}
- internal abstract DateTime MaxDate {get;}
-
- internal const int MaxCalendarMonth = 13;
- internal const int MaxCalendarDay = 30;
-
- internal int MinEraCalendarYear (int era) {
- EraInfo[] mEraInfo = CalEraInfo;
- //ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
- if (mEraInfo == null) {
- return MinCalendarYear;
- }
-
- if (era == Calendar.CurrentEra) {
- era = CurrentEraValue;
- }
- //era has to be in the supported range otherwise we will throw exception in CheckEraRange()
- if (era == GetEra(MinDate)) {
- return (GetYear(MinCalendarYear, MinDate));
- }
-
- for (int i = 0; i < mEraInfo.Length; i++) {
- if (era == mEraInfo[i].era) {
- return (mEraInfo[i].minEraYear);
- }
- }
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
-
- internal int MaxEraCalendarYear (int era) {
- EraInfo[] mEraInfo = CalEraInfo;
- //ChineseLunisolarCalendar does not has m_EraInfo it is going to retuen null
- if (mEraInfo == null) {
- return MaxCalendarYear;
- }
-
- if (era == Calendar.CurrentEra) {
- era = CurrentEraValue;
- }
- //era has to be in the supported range otherwise we will throw exception in CheckEraRange()
- if (era == GetEra(MaxDate)) {
- return (GetYear(MaxCalendarYear, MaxDate));
- }
-
- for (int i = 0; i < mEraInfo.Length; i++) {
- if (era == mEraInfo[i].era) {
- return (mEraInfo[i].maxEraYear);
- }
- }
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
-
- // Construct an instance of EastAsianLunisolar calendar.
-
- internal EastAsianLunisolarCalendar() {
- }
-
- internal void CheckTicksRange(long ticks) {
- if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks) {
- throw new ArgumentOutOfRangeException(
- "time",
- String.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
- MinSupportedDateTime, MaxSupportedDateTime));
- }
- Contract.EndContractBlock();
- }
-
- internal void CheckEraRange (int era) {
- if (era == Calendar.CurrentEra) {
- era = CurrentEraValue;
- }
-
- if ((era <GetEra(MinDate)) || (era > GetEra(MaxDate))) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
- }
-
- internal int CheckYearRange(int year, int era) {
- CheckEraRange(era);
- year = GetGregorianYear(year, era);
-
- if ((year < MinCalendarYear) || (year > MaxCalendarYear)) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_Range", MinEraCalendarYear(era), MaxEraCalendarYear(era)));
- }
- return year;
- }
-
- internal int CheckYearMonthRange(int year, int month, int era) {
- year = CheckYearRange(year, era);
-
- if (month == 13)
- {
- //Reject if there is no leap month this year
- if (GetYearInfo(year , LeapMonth) == 0)
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
-
- if (month < 1 || month > 13) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
- return year;
- }
-
- internal int InternalGetDaysInMonth(int year, int month) {
- int nDays;
- int mask; // mask for extracting bits
-
- mask = 0x8000;
- // convert the lunar day into a lunar month/date
- mask >>= (month-1);
- if ((GetYearInfo(year, nDaysPerMonth) & mask)== 0)
- nDays = 29;
- else
- nDays = 30;
- return nDays;
- }
-
- // Returns the number of days in the month given by the year and
- // month arguments.
- //
-
- public override int GetDaysInMonth(int year, int month, int era) {
- year = CheckYearMonthRange(year, month, era);
- return InternalGetDaysInMonth(year, month);
- }
-
- static int GregorianIsLeapYear(int y) {
- return ((((y)%4)!=0)?0:((((y)%100)!=0)?1:((((y)%400)!=0)?0:1)));
- }
-
- // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
- //
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- year = CheckYearMonthRange(year, month, era);
- int daysInMonth = InternalGetDaysInMonth(year, month);
- if (day < 1 || day > daysInMonth) {
- BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
- throw new ArgumentOutOfRangeException(
- nameof(day),
- Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month));
- }
-
- int gy=0; int gm=0; int gd=0;
-
- if (LunarToGregorian(year, month, day, ref gy, ref gm, ref gd)) {
- return new DateTime(gy, gm, gd, hour, minute, second, millisecond);
- } else {
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
- }
-
-
- //
- // GregorianToLunar calculates lunar calendar info for the given gregorian year, month, date.
- // The input date should be validated before calling this method.
- //
- internal void GregorianToLunar(int nSYear, int nSMonth, int nSDate, ref int nLYear, ref int nLMonth, ref int nLDate) {
- // unsigned int nLYear, nLMonth, nLDate; // lunar ymd
- int nSolarDay; // day # in solar year
- int nLunarDay; // day # in lunar year
- int fLeap; // is it a solar leap year?
- int LDpM; // lunar days/month bitfield
- int mask; // mask for extracting bits
- int nDays; // # days this lunar month
- int nJan1Month, nJan1Date;
-
- // calc the solar day of year
- fLeap = GregorianIsLeapYear(nSYear);
- nSolarDay = (fLeap==1) ? DaysToMonth366[nSMonth-1]: DaysToMonth365[nSMonth-1] ;
- nSolarDay += nSDate;
-
- // init lunar year info
- nLunarDay = nSolarDay;
- nLYear = nSYear;
- if (nLYear == (MaxCalendarYear + 1)) {
- nLYear--;
- nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
- nJan1Month = GetYearInfo(nLYear, Jan1Month);
- nJan1Date = GetYearInfo(nLYear,Jan1Date);
- } else {
-
- nJan1Month = GetYearInfo(nLYear, Jan1Month);
- nJan1Date = GetYearInfo(nLYear,Jan1Date);
-
- // check if this solar date is actually part of the previous
- // lunar year
- if ((nSMonth < nJan1Month) ||
- (nSMonth == nJan1Month && nSDate < nJan1Date)) {
- // the corresponding lunar day is actually part of the previous
- // lunar year
- nLYear--;
-
- // add a solar year to the lunar day #
- nLunarDay += ((GregorianIsLeapYear(nLYear) == 1) ? 366 : 365);
-
- // update the new start of year
- nJan1Month = GetYearInfo(nLYear, Jan1Month);
- nJan1Date = GetYearInfo(nLYear, Jan1Date);
- }
- }
-
- // convert solar day into lunar day.
- // subtract off the beginning part of the solar year which is not
- // part of the lunar year. since this part is always in Jan or Feb,
- // we don't need to handle Leap Year (LY only affects March
- // and later).
- nLunarDay -= DaysToMonth365[nJan1Month-1];
- nLunarDay -= (nJan1Date - 1);
-
- // convert the lunar day into a lunar month/date
- mask = 0x8000;
- LDpM = GetYearInfo(nLYear, nDaysPerMonth);
- nDays = ((LDpM & mask) != 0) ? 30 : 29;
- nLMonth = 1;
- while (nLunarDay > nDays) {
- nLunarDay -= nDays;
- nLMonth++;
- mask >>= 1;
- nDays = ((LDpM & mask) != 0) ? 30 : 29;
- }
- nLDate = nLunarDay;
- }
-
- /*
- //Convert from Lunar to Gregorian
- //Highly inefficient, but it works based on the forward conversion
- */
- internal bool LunarToGregorian(int nLYear, int nLMonth, int nLDate, ref int nSolarYear, ref int nSolarMonth, ref int nSolarDay) {
- int numLunarDays;
-
- if (nLDate < 1 || nLDate > 30)
- return false;
-
- numLunarDays = nLDate-1;
-
- //Add previous months days to form the total num of days from the first of the month.
- for (int i = 1; i < nLMonth; i++) {
- numLunarDays += InternalGetDaysInMonth(nLYear, i);
- }
-
- //Get Gregorian First of year
- int nJan1Month = GetYearInfo(nLYear, Jan1Month);
- int nJan1Date = GetYearInfo(nLYear, Jan1Date);
-
- // calc the solar day of year of 1 Lunar day
- int fLeap = GregorianIsLeapYear(nLYear);
- int[] days = (fLeap==1)? DaysToMonth366: DaysToMonth365;
-
- nSolarDay = nJan1Date;
-
- if (nJan1Month > 1)
- nSolarDay += days [nJan1Month-1];
-
- // Add the actual lunar day to get the solar day we want
- nSolarDay = nSolarDay + numLunarDays;// - 1;
-
- if ( nSolarDay > (fLeap + 365)) {
- nSolarYear = nLYear + 1;
- nSolarDay -= (fLeap + 365);
- } else {
- nSolarYear = nLYear;
- }
-
- for (nSolarMonth = 1; nSolarMonth < 12; nSolarMonth++) {
- if (days[nSolarMonth] >= nSolarDay)
- break;
- }
-
- nSolarDay -= days[nSolarMonth-1];
- return true;
- }
-
- internal DateTime LunarToTime(DateTime time, int year, int month, int day) {
- int gy=0; int gm=0; int gd=0;
- LunarToGregorian(year, month, day, ref gy, ref gm, ref gd);
- return (GregorianCalendar.GetDefaultInstance().ToDateTime(gy,gm,gd,time.Hour,time.Minute,time.Second,time.Millisecond));
- }
-
- internal void TimeToLunar(DateTime time, ref int year, ref int month, ref int day) {
- int gy=0; int gm=0; int gd=0;
-
- Calendar Greg = GregorianCalendar.GetDefaultInstance();
- gy = Greg.GetYear(time);
- gm = Greg.GetMonth(time);
- gd = Greg.GetDayOfMonth(time);
-
- GregorianToLunar(gy, gm, gd, ref year, ref month, ref day);
- }
-
- // Returns the DateTime resulting from adding the given number of
- // months to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year and month parts of the specified DateTime by
- // value months, and, if required, adjusting the day part of the
- // resulting date downwards to the last day of the resulting month in the
- // resulting year. The time-of-day part of the result is the same as the
- // time-of-day part of the specified DateTime.
- //
-
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
- throw new ArgumentOutOfRangeException(
- nameof(months),
- Environment.GetResourceString("ArgumentOutOfRange_Range", -120000, 120000));
- }
- Contract.EndContractBlock();
-
- CheckTicksRange(time.Ticks);
-
- int y=0; int m=0; int d=0;
- TimeToLunar(time, ref y, ref m, ref d);
-
- int i = m + months;
- if (i > 0) {
- int monthsInYear = InternalIsLeapYear(y)?13:12;
-
- while (i-monthsInYear > 0) {
- i -= monthsInYear;
- y++;
- monthsInYear = InternalIsLeapYear(y)?13:12;
- }
- m = i;
- } else {
- int monthsInYear;
- while (i <= 0) {
- monthsInYear = InternalIsLeapYear(y-1)?13:12;
- i += monthsInYear;
- y--;
- }
- m = i;
- }
-
- int days = InternalGetDaysInMonth(y, m);
- if (d > days) {
- d = days;
- }
- DateTime dt = LunarToTime(time, y, m, d);
-
- CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (dt);
- }
-
-
- public override DateTime AddYears(DateTime time, int years) {
- CheckTicksRange(time.Ticks);
-
- int y=0; int m=0; int d=0;
- TimeToLunar(time, ref y, ref m, ref d);
-
- y += years;
-
- if (m==13 && !InternalIsLeapYear(y)) {
- m = 12;
- d = InternalGetDaysInMonth(y, m);
- }
- int DaysInMonths = InternalGetDaysInMonth(y, m);
- if (d > DaysInMonths) {
- d = DaysInMonths;
- }
-
- DateTime dt = LunarToTime(time, y, m, d);
- CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (dt);
- }
-
- // Returns the day-of-year part of the specified DateTime. The returned value
- // is an integer between 1 and [354|355 |383|384].
- //
-
- public override int GetDayOfYear(DateTime time) {
- CheckTicksRange(time.Ticks);
-
- int y=0; int m=0; int d=0;
- TimeToLunar(time, ref y, ref m, ref d);
-
- for (int i=1; i<m ;i++)
- {
- d = d + InternalGetDaysInMonth(y, i);
- }
- return d;
- }
-
- // Returns the day-of-month part of the specified DateTime. The returned
- // value is an integer between 1 and 29 or 30.
- //
-
- public override int GetDayOfMonth(DateTime time) {
- CheckTicksRange(time.Ticks);
-
- int y=0; int m=0; int d=0;
- TimeToLunar(time, ref y, ref m, ref d);
-
- return d;
- }
-
- // Returns the number of days in the year given by the year argument for the current era.
- //
-
- public override int GetDaysInYear(int year, int era) {
- year = CheckYearRange(year, era);
-
- int Days = 0;
- int monthsInYear = InternalIsLeapYear(year) ? 13 : 12;
-
- while (monthsInYear != 0)
- Days += InternalGetDaysInMonth(year, monthsInYear--);
-
- return Days;
- }
-
- // Returns the month part of the specified DateTime. The returned value is an
- // integer between 1 and 13.
- //
-
- public override int GetMonth(DateTime time) {
- CheckTicksRange(time.Ticks);
-
- int y=0; int m=0; int d=0;
- TimeToLunar(time, ref y, ref m, ref d);
-
- return m;
- }
-
- // Returns the year part of the specified DateTime. The returned value is an
- // integer between 1 and MaxCalendarYear.
- //
-
- public override int GetYear(DateTime time) {
- CheckTicksRange(time.Ticks);
-
- int y=0; int m=0; int d=0;
- TimeToLunar(time, ref y, ref m, ref d);
-
- return GetYear(y, time);
- }
-
- // Returns the day-of-week part of the specified DateTime. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- CheckTicksRange(time.Ticks);
- return ((DayOfWeek)((int)(time.Ticks / Calendar.TicksPerDay + 1) % 7));
- }
-
- // Returns the number of months in the specified year and era.
-
- public override int GetMonthsInYear(int year, int era) {
- year = CheckYearRange(year, era);
- return (InternalIsLeapYear(year)?13:12);
- }
-
- // Checks whether a given day in the specified era is a leap day. This method returns true if
- // the date is a leap day, or false if not.
- //
-
- public override bool IsLeapDay(int year, int month, int day, int era) {
- year = CheckYearMonthRange(year, month, era);
- int daysInMonth = InternalGetDaysInMonth(year, month);
-
- if (day < 1 || day > daysInMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(day),
- Environment.GetResourceString("ArgumentOutOfRange_Day", daysInMonth, month));
- }
- int m = GetYearInfo(year, LeapMonth);
- return ((m!=0) && (month == (m+1)));
- }
-
- // Checks whether a given month in the specified era is a leap month. This method returns true if
- // month is a leap month, or false if not.
- //
-
- public override bool IsLeapMonth(int year, int month, int era) {
- year = CheckYearMonthRange(year, month, era);
- int m = GetYearInfo(year, LeapMonth);
- return ((m!=0) && (month == (m+1)));
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era) {
- year = CheckYearRange(year, era);
- int month = GetYearInfo(year, LeapMonth);
- if (month>0)
- {
- return (month+1);
- }
- return 0;
- }
-
- internal bool InternalIsLeapYear(int year) {
- return (GetYearInfo(year, LeapMonth)!=0);
- }
- // Checks whether a given year in the specified era is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
-
- public override bool IsLeapYear(int year, int era) {
- year = CheckYearRange(year, era);
- return InternalIsLeapYear(year);
- }
-
- private const int DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX = 2029;
-
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(BaseCalendarID, GetYear(new DateTime(DEFAULT_GREGORIAN_TWO_DIGIT_YEAR_MAX, 1, 1)));
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > MaxCalendarYear)
- {
- throw new ArgumentOutOfRangeException(
- nameof(value),
- Environment.GetResourceString("ArgumentOutOfRange_Range", 99, MaxCalendarYear));
- }
- twoDigitYearMax = value;
- }
- }
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- year = base.ToFourDigitYear(year);
- CheckYearRange(year, CurrentEra);
- return (year);
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs
index 408f6e681e..ffb2d46a9e 100644
--- a/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.Unix.cs
@@ -59,7 +59,7 @@ namespace System.Globalization
{
if (_displayNameResourceKey == null)
{
- _displayNameResourceKey = "Globalization.cp_" + CodePage;
+ _displayNameResourceKey = "Globalization_cp_" + CodePage;
}
return _displayNameResourceKey;
diff --git a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
index 89ac780587..b049eaf45d 100644
--- a/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingDataItem.cs
@@ -2,12 +2,13 @@
// 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.Globalization {
- using System.Text;
- using System.Runtime.Remoting;
- using System;
- using System.Security;
+using System.Text;
+using System.Runtime.Remoting;
+using System;
+using System.Security;
+namespace System.Globalization
+{
//
// Data item for EncodingTable. Along with EncodingTable, they are used by
// System.Text.Encoding.
@@ -16,18 +17,19 @@ namespace System.Globalization {
// where our required information is found. We load the code page, flags and uiFamilyCodePage
// immediately because they don't require creating an object. Creating any of the string
// names is delayed until somebody actually asks for them and the names are then cached.
-
+
[Serializable]
internal class CodePageDataItem
{
- internal int m_dataIndex;
- internal int m_uiFamilyCodePage;
+ internal int m_dataIndex;
+ internal int m_uiFamilyCodePage;
internal String m_webName;
internal String m_headerName;
internal String m_bodyName;
- internal uint m_flags;
-
- unsafe internal CodePageDataItem(int dataIndex) {
+ internal uint m_flags;
+
+ unsafe internal CodePageDataItem(int dataIndex)
+ {
m_dataIndex = dataIndex;
m_uiFamilyCodePage = EncodingTable.codePageDataPtr[dataIndex].uiFamilyCodePage;
m_flags = EncodingTable.codePageDataPtr[dataIndex].flags;
@@ -38,8 +40,8 @@ namespace System.Globalization {
if (pStrings[0] == '|') // |str1|str2|str3
{
int start = 1;
-
- for (int i = 1; true; i ++)
+
+ for (int i = 1; true; i++)
{
sbyte ch = pStrings[i];
@@ -50,7 +52,7 @@ namespace System.Globalization {
return new String(pStrings, start, i - start);
}
- index --;
+ index--;
start = i + 1;
if (ch == 0)
@@ -68,41 +70,54 @@ namespace System.Globalization {
}
}
- unsafe public String WebName {
- get {
- if (m_webName==null) {
+ unsafe public String WebName
+ {
+ get
+ {
+ if (m_webName == null)
+ {
m_webName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 0);
}
return m_webName;
}
}
-
- public virtual int UIFamilyCodePage {
- get {
+
+ public virtual int UIFamilyCodePage
+ {
+ get
+ {
return m_uiFamilyCodePage;
}
}
-
- unsafe public String HeaderName {
- get {
- if (m_headerName==null) {
+
+ unsafe public String HeaderName
+ {
+ get
+ {
+ if (m_headerName == null)
+ {
m_headerName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 1);
}
return m_headerName;
}
}
-
- unsafe public String BodyName {
- get {
- if (m_bodyName==null) {
+
+ unsafe public String BodyName
+ {
+ get
+ {
+ if (m_bodyName == null)
+ {
m_bodyName = CreateString(EncodingTable.codePageDataPtr[m_dataIndex].Names, 2);
}
return m_bodyName;
}
- }
+ }
- unsafe public uint Flags {
- get {
+ unsafe public uint Flags
+ {
+ get
+ {
return (m_flags);
}
}
diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
index 0fce2e58fc..dc61c9f0d9 100644
--- a/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingTable.Unix.cs
@@ -21,7 +21,7 @@ namespace System.Globalization
CodePageDataItem dataItem = s_encodingDataTableItems[i];
arrayEncodingInfo[i] = new EncodingInfo(dataItem.CodePage, dataItem.WebName,
- Environment.GetResourceString(dataItem.DisplayNameResourceKey));
+ SR.GetResourceString(dataItem.DisplayNameResourceKey));
}
return arrayEncodingInfo;
@@ -45,7 +45,7 @@ namespace System.Globalization
throw new ArgumentException(
string.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name));
+ SR.Argument_EncodingNotSupported, name), nameof(name));
}
internal static CodePageDataItem GetCodePageDataItem(int codepage)
diff --git a/src/mscorlib/src/System/Globalization/EncodingTable.cs b/src/mscorlib/src/System/Globalization/EncodingTable.cs
index b7c268a956..6d9cc3127f 100644
--- a/src/mscorlib/src/System/Globalization/EncodingTable.cs
+++ b/src/mscorlib/src/System/Globalization/EncodingTable.cs
@@ -2,44 +2,44 @@
// 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.Collections;
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Security;
+using System.Threading;
+using System.Diagnostics.Contracts;
+
namespace System.Globalization
{
- using System;
- using System.Text;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Threading;
- using System.Diagnostics.Contracts;
//
// Data table for encoding classes. Used by System.Text.Encoding.
// This class contains two hashtables to allow System.Text.Encoding
// to retrieve the data item either by codepage value or by webName.
//
-
+
// Only statics, does not need to be marked with the serializable attribute
internal static class EncodingTable
{
-
//This number is the size of the table in native. The value is retrieved by
//calling the native GetNumEncodingItems().
private static int lastEncodingItem = GetNumEncodingItems() - 1;
//This number is the size of the code page table. Its generated when we walk the table the first time.
private static volatile int lastCodePageItem;
-
+
//
// This points to a native data table which maps an encoding name to the correct code page.
//
- unsafe internal static InternalEncodingDataItem *encodingDataPtr = GetEncodingData();
+ unsafe internal static InternalEncodingDataItem* encodingDataPtr = GetEncodingData();
//
// This points to a native data table which stores the properties for the code page, and
// the table is indexed by code page.
//
- unsafe internal static InternalCodePageDataItem *codePageDataPtr = GetCodePageData();
+ unsafe internal static InternalCodePageDataItem* codePageDataPtr = GetCodePageData();
//
// This caches the mapping of an encoding name to a code page.
//
@@ -49,40 +49,45 @@ namespace System.Globalization
//
private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable());
- static EncodingTable()
- {
- }
-
// Find the data item by binary searching the table that we have in native.
// nativeCompareOrdinalWC is an internal-only function.
- unsafe private static int internalGetCodePageFromName(String name) {
- int left = 0;
+ unsafe private static int internalGetCodePageFromName(String name)
+ {
+ int left = 0;
int right = lastEncodingItem;
int index;
int result;
-
+
//Binary search the array until we have only a couple of elements left and then
//just walk those elements.
- while ((right - left)>3) {
- index = ((right - left)/2) + left;
-
+ while ((right - left) > 3)
+ {
+ index = ((right - left) / 2) + left;
+
result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName);
-
- if (result == 0) {
+
+ if (result == 0)
+ {
//We found the item, return the associated codepage.
return (encodingDataPtr[index].codePage);
- } else if (result<0) {
+ }
+ else if (result < 0)
+ {
//The name that we're looking for is less than our current index.
right = index;
- } else {
+ }
+ else
+ {
//The name that we're looking for is greater than our current index
left = index;
}
}
-
+
//Walk the remaining elements (it'll be 3 or fewer).
- for (; left<=right; left++) {
- if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0) {
+ for (; left <= right; left++)
+ {
+ if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0)
+ {
return (encodingDataPtr[left].codePage);
}
}
@@ -90,7 +95,7 @@ namespace System.Globalization
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name));
+ SR.Argument_EncodingNotSupported, name), nameof(name));
}
// Return a list of all EncodingInfo objects describing all of our encodings
@@ -112,12 +117,12 @@ namespace System.Globalization
for (i = 0; i < lastCodePageItem; i++)
{
arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0),
- Environment.GetResourceString("Globalization.cp_" + codePageDataPtr[i].codePage));
+ SR.GetResourceString("Globalization_cp_" + codePageDataPtr[i].codePage));
}
-
+
return arrayEncodingInfo;
- }
-
+ }
+
/*=================================GetCodePageFromName==========================
**Action: Given a encoding name, return the correct code page number for this encoding.
**Returns: The code page for the encoding.
@@ -127,10 +132,11 @@ namespace System.Globalization
** ArgumentNullException if name is null.
** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name.
============================================================================*/
-
+
internal static int GetCodePageFromName(String name)
- {
- if (name==null) {
+ {
+ if (name == null)
+ {
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
@@ -143,7 +149,8 @@ namespace System.Globalization
//
codePageObj = hashByName[name];
- if (codePageObj!=null) {
+ if (codePageObj != null)
+ {
return ((int)codePageObj);
}
@@ -155,8 +162,9 @@ namespace System.Globalization
return codePage;
}
-
- unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage) {
+
+ unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage)
+ {
CodePageDataItem dataItem;
// We synchronize around dictionary gets/sets. There's still a possibility that two threads
@@ -166,9 +174,10 @@ namespace System.Globalization
//Look up the item in the hashtable.
dataItem = (CodePageDataItem)hashByCodePage[codepage];
-
+
//If we found it, return it.
- if (dataItem!=null) {
+ if (dataItem != null)
+ {
return dataItem;
}
@@ -179,22 +188,24 @@ namespace System.Globalization
//
int i = 0;
int data;
- while ((data = codePageDataPtr[i].codePage) != 0) {
- if (data == codepage) {
+ while ((data = codePageDataPtr[i].codePage) != 0)
+ {
+ if (data == codepage)
+ {
dataItem = new CodePageDataItem(i);
hashByCodePage[codepage] = dataItem;
return (dataItem);
}
i++;
}
-
+
//Nope, we didn't find it.
return null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private unsafe static extern InternalEncodingDataItem *GetEncodingData();
-
+ private unsafe static extern InternalEncodingDataItem* GetEncodingData();
+
//
// Return the number of encoding data items.
//
@@ -204,18 +215,19 @@ namespace System.Globalization
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalCodePageDataItem* GetCodePageData();
}
-
+
/*=================================InternalEncodingDataItem==========================
**Action: This is used to map a encoding name to a correct code page number. By doing this,
** we can get the properties of this encoding via the InternalCodePageDataItem.
**
** We use this structure to access native data exposed by the native side.
============================================================================*/
-
+
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- internal unsafe struct InternalEncodingDataItem {
- internal sbyte * webName;
- internal UInt16 codePage;
+ internal unsafe struct InternalEncodingDataItem
+ {
+ internal sbyte* webName;
+ internal UInt16 codePage;
}
/*=================================InternalCodePageDataItem==========================
@@ -224,11 +236,11 @@ namespace System.Globalization
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- internal unsafe struct InternalCodePageDataItem {
- internal UInt16 codePage;
- internal UInt16 uiFamilyCodePage;
- internal uint flags;
- internal sbyte * Names;
+ internal unsafe struct InternalCodePageDataItem
+ {
+ internal UInt16 codePage;
+ internal UInt16 uiFamilyCodePage;
+ internal uint flags;
+ internal sbyte* Names;
}
-
}
diff --git a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
index e203223eb0..956543524a 100644
--- a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
+++ b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
@@ -3,21 +3,21 @@
// See the LICENSE file in the project root for more information.
-namespace System.Globalization {
- 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;
+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
@@ -32,31 +32,33 @@ namespace System.Globalization {
// 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.");
+ 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) {
+ if (bytesStream != null)
+ {
byte* bytes = bytesStream.PositionPointer;
- if (bytes != null) {
+ if (bytes != null)
+ {
return (bytes);
}
}
-
+
Debug.Assert(
- false,
+ false,
String.Format(
CultureInfo.CurrentCulture,
- "Didn't get the resource table {0} for System.Globalization from {1}",
- tableName,
+ "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/GlobalizationMode.Unix.cs b/src/mscorlib/src/System/Globalization/GlobalizationMode.Unix.cs
new file mode 100644
index 0000000000..6896029047
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/GlobalizationMode.Unix.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.
+
+namespace System.Globalization
+{
+ internal sealed partial class GlobalizationMode
+ {
+ private static bool GetGlobalizationInvariantMode()
+ {
+ bool invariantEnabled = CLRConfig.GetBoolValue(c_InvariantModeConfigSwitch);
+ if (!invariantEnabled)
+ {
+ if (Interop.GlobalizationInterop.LoadICU() == 0)
+ {
+ string message = "Couldn't find a valid ICU package installed on the system. " +
+ "Set the configuration flag System.Globalization.Invariant to true if you want to run with no globalization support.";
+ Environment.FailFast(message);
+ }
+ }
+ return invariantEnabled;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/EventArgs.cs b/src/mscorlib/src/System/Globalization/GlobalizationMode.Windows.cs
index c0356613de..1be79f3507 100644
--- a/src/mscorlib/src/System/EventArgs.cs
+++ b/src/mscorlib/src/System/Globalization/GlobalizationMode.Windows.cs
@@ -2,18 +2,13 @@
// 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
+namespace System.Globalization
{
- // The base class for all event classes.
- [Serializable]
- public class EventArgs
+ internal sealed partial class GlobalizationMode
{
- public static readonly EventArgs Empty = new EventArgs();
-
- public EventArgs()
+ private static bool GetGlobalizationInvariantMode()
{
+ return CLRConfig.GetBoolValue(c_InvariantModeConfigSwitch);
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/GlobalizationMode.cs b/src/mscorlib/src/System/Globalization/GlobalizationMode.cs
new file mode 100644
index 0000000000..8f8309886d
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/GlobalizationMode.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.Globalization
+{
+ internal sealed partial class GlobalizationMode
+ {
+ private const string c_InvariantModeConfigSwitch = "System.Globalization.Invariant";
+ internal static bool Invariant { get; } = GetGlobalizationInvariantMode();
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
index 9083e6de27..6dbf5b2786 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendar.cs
@@ -2,27 +2,20 @@
// 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.Globalization {
- //
- // N.B.:
- // A lot of this code is directly from DateTime.cs. If you update that class,
- // update this one as well.
- // However, we still need these duplicated code because we will add era support
- // in this class.
- //
- //
-
- using System.Threading;
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
-
+using System;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Threading;
+
+namespace System.Globalization
+{
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
[Serializable]
+
public class GregorianCalendar : Calendar
{
/*
@@ -57,24 +50,16 @@ namespace System.Globalization {
private static volatile Calendar s_defaultInstance;
-
-#region Serialization
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
- if (m_type < GregorianCalendarTypes.Localized ||
- m_type > GregorianCalendarTypes.TransliteratedFrench)
+ if (m_type < GregorianCalendarTypes.Localized ||
+ m_type > GregorianCalendarTypes.TransliteratedFrench)
{
throw new SerializationException(
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString(
- "Serialization_MemberOutOfRange"),
- "type",
- "GregorianCalendar"));
+ String.Format(CultureInfo.CurrentCulture, SR.Serialization_MemberOutOfRange, "type", "GregorianCalendar"));
}
}
-#endregion Serialization
public override DateTime MinSupportedDateTime
{
@@ -92,9 +77,6 @@ namespace System.Globalization {
}
}
- // Return the type of the Gregorian calendar.
- //
-
public override CalendarAlgorithmType AlgorithmType
{
get
@@ -111,8 +93,10 @@ namespace System.Globalization {
**Exceptions:
============================================================================*/
- internal static Calendar GetDefaultInstance() {
- if (s_defaultInstance == null) {
+ internal static Calendar GetDefaultInstance()
+ {
+ if (s_defaultInstance == null)
+ {
s_defaultInstance = new GregorianCalendar();
}
return (s_defaultInstance);
@@ -121,30 +105,37 @@ namespace System.Globalization {
// Construct an instance of gregorian calendar.
public GregorianCalendar() :
- this(GregorianCalendarTypes.Localized) {
+ this(GregorianCalendarTypes.Localized)
+ {
}
- public GregorianCalendar(GregorianCalendarTypes type) {
- if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) {
+ public GregorianCalendar(GregorianCalendarTypes type)
+ {
+ if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench)
+ {
throw new ArgumentOutOfRangeException(
nameof(type),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
+ SR.Format(SR.ArgumentOutOfRange_Range,
GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench));
}
Contract.EndContractBlock();
this.m_type = type;
}
- public virtual GregorianCalendarTypes CalendarType {
- get {
+ public virtual GregorianCalendarTypes CalendarType
+ {
+ get
+ {
return (m_type);
}
- set {
+ set
+ {
VerifyWritable();
- switch (value) {
+ switch (value)
+ {
case GregorianCalendarTypes.Localized:
case GregorianCalendarTypes.USEnglish:
case GregorianCalendarTypes.MiddleEastFrench:
@@ -155,18 +146,20 @@ namespace System.Globalization {
break;
default:
- throw new ArgumentOutOfRangeException(nameof(m_type), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum);
}
}
}
- internal override int ID {
- get {
+ internal override CalendarId ID
+ {
+ get
+ {
// By returning different ID for different variations of GregorianCalendar,
// we can support the Transliterated Gregorian calendar.
// DateTimeFormatInfo will use this ID to get formatting information about
// the calendar.
- return ((int)m_type);
+ return ((CalendarId)m_type);
}
}
@@ -210,7 +203,7 @@ namespace System.Globalization {
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
- int[] days = leapYear? DaysToMonth366: DaysToMonth365;
+ int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
@@ -240,23 +233,26 @@ namespace System.Globalization {
**
============================================================================*/
- internal static long GetAbsoluteDate(int year, int month, int day) {
+ internal static long GetAbsoluteDate(int year, int month, int day)
+ {
if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12)
{
- int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365;
- if (day >= 1 && (day <= days[month] - days[month - 1])) {
+ int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
+ if (day >= 1 && (day <= days[month] - days[month - 1]))
+ {
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
+ throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
}
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
- internal virtual long DateToTicks(int year, int month, int day) {
- return (GetAbsoluteDate(year, month, day)* TicksPerDay);
+ internal virtual long DateToTicks(int year, int month, int day)
+ {
+ return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// Returns the DateTime resulting from adding the given number of
@@ -279,12 +275,13 @@ namespace System.Globalization {
public override DateTime AddMonths(DateTime time, int months)
{
- if (months < -120000 || months > 120000) {
+ if (months < -120000 || months > 120000)
+ {
throw new ArgumentOutOfRangeException(
nameof(months),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
-120000,
120000));
}
@@ -303,7 +300,7 @@ namespace System.Globalization {
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
- int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365;
+ int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
int days = (daysArray[m] - daysArray[m - 1]);
if (d > days)
@@ -364,19 +361,23 @@ namespace System.Globalization {
// month arguments.
//
- public override int GetDaysInMonth(int year, int month, int era) {
- if (era == CurrentEra || era == ADEra) {
- if (year < 1 || year > MaxYear) {
- throw new ArgumentOutOfRangeException(nameof(year), Environment.GetResourceString("ArgumentOutOfRange_Range",
+ public override int GetDaysInMonth(int year, int month, int era)
+ {
+ if (era == CurrentEra || era == ADEra)
+ {
+ if (year < 1 || year > MaxYear)
+ {
+ throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range,
1, MaxYear));
}
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ if (month < 1 || month > 12)
+ {
+ throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
- int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365);
+ int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
return (days[month] - days[month - 1]);
}
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the number of days in the year given by the year argument for the current era.
@@ -384,19 +385,21 @@ namespace System.Globalization {
public override int GetDaysInYear(int year, int era)
{
- if (era == CurrentEra || era == ADEra) {
- if (year >= 1 && year <= MaxYear) {
- return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365);
+ if (era == CurrentEra || era == ADEra)
+ {
+ if (year >= 1 && year <= MaxYear)
+ {
+ return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the era for the specified DateTime value.
@@ -407,9 +410,11 @@ namespace System.Globalization {
}
- public override int[] Eras {
- get {
- return (new int[] {ADEra} );
+ public override int[] Eras
+ {
+ get
+ {
+ return (new int[] { ADEra });
}
}
@@ -427,7 +432,8 @@ namespace System.Globalization {
public override int GetMonthsInYear(int year, int era)
{
- if (era == CurrentEra || era == ADEra) {
+ if (era == CurrentEra || era == ADEra)
+ {
if (year >= 1 && year <= MaxYear)
{
return (12);
@@ -436,11 +442,11 @@ namespace System.Globalization {
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
1,
MaxYear));
}
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the year part of the specified DateTime. The returned value is an
@@ -458,30 +464,35 @@ namespace System.Globalization {
public override bool IsLeapDay(int year, int month, int day, int era)
{
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
+ if (month < 1 || month > 12)
+ {
+ throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
Contract.EndContractBlock();
if (era != CurrentEra && era != ADEra)
{
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
- if (year < 1 || year > MaxYear) {
+ if (year < 1 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_Range", 1, MaxYear));
+ SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
- if (day < 1 || day > GetDaysInMonth(year, month)) {
- throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_Range",
+ if (day < 1 || day > GetDaysInMonth(year, month))
+ {
+ throw new ArgumentOutOfRangeException(nameof(day), SR.Format(SR.ArgumentOutOfRange_Range,
1, GetDaysInMonth(year, month)));
}
- if (!IsLeapYear(year)) {
+ if (!IsLeapYear(year))
+ {
return (false);
}
- if (month == 2 && day == 29) {
+ if (month == 2 && day == 29)
+ {
return (true);
}
return (false);
@@ -495,14 +506,15 @@ namespace System.Globalization {
{
if (era != CurrentEra && era != ADEra)
{
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
- if (year < 1 || year > MaxYear) {
+ if (year < 1 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
+ SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
Contract.EndContractBlock();
return (0);
@@ -514,34 +526,39 @@ namespace System.Globalization {
public override bool IsLeapMonth(int year, int month, int era)
{
- if (era != CurrentEra && era != ADEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ if (era != CurrentEra && era != ADEra)
+ {
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
- if (year < 1 || year > MaxYear) {
+ if (year < 1 || year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
+ SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Range",
+ if (month < 1 || month > 12)
+ {
+ throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range,
1, 12));
}
Contract.EndContractBlock();
return (false);
-
}
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
- public override bool IsLeapYear(int year, int era) {
- if (era == CurrentEra || era == ADEra) {
- if (year >= 1 && year <= MaxYear) {
+ public override bool IsLeapYear(int year, int era)
+ {
+ if (era == CurrentEra || era == ADEra)
+ {
+ if (year >= 1 && year <= MaxYear)
+ {
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
@@ -549,9 +566,9 @@ namespace System.Globalization {
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
+ SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
@@ -559,15 +576,32 @@ namespace System.Globalization {
public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
{
- if (era == CurrentEra || era == ADEra) {
+ if (era == CurrentEra || era == ADEra)
+ {
return new DateTime(year, month, day, hour, minute, second, millisecond);
}
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
- internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) {
- if (era == CurrentEra || era == ADEra) {
- return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result);
+ internal override Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result)
+ {
+ if (era == CurrentEra || era == ADEra)
+ {
+ try
+ {
+ result = new DateTime(year, month, day, hour, minute, second, millisecond);
+ return true;
+ }
+ catch (ArgumentOutOfRangeException)
+ {
+ result = DateTime.Now;
+ return false;
+ }
+ catch (ArgumentException)
+ {
+ result = DateTime.Now;
+ return false;
+ }
}
result = DateTime.MinValue;
return false;
@@ -578,43 +612,49 @@ namespace System.Globalization {
public override int TwoDigitYearMax
{
- get {
- if (twoDigitYearMax == -1) {
+ get
+ {
+ if (twoDigitYearMax == -1)
+ {
twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
}
return (twoDigitYearMax);
}
- set {
+ set
+ {
VerifyWritable();
- if (value < 99 || value > MaxYear) {
+ if (value < 99 || value > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
"year",
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
99,
MaxYear));
-
}
twoDigitYearMax = value;
}
}
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
+ public override int ToFourDigitYear(int year)
+ {
+ if (year < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (year > MaxYear) {
+ if (year > MaxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, MaxYear));
+ SR.ArgumentOutOfRange_Range, 1, MaxYear));
}
return (base.ToFourDigitYear(year));
}
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
index 062ae4818a..bdc35f0734 100644
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
+++ b/src/mscorlib/src/System/Globalization/GregorianCalendarHelper.cs
@@ -2,27 +2,25 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Threading;
-namespace System.Globalization {
- using System;
- using System.Runtime.Serialization;
- using System.Threading;
- using System.Diagnostics.Contracts;
-
+namespace System.Globalization
+{
// Gregorian Calendars use Era Info
- // Note: We shouldn't have to serialize this since the info doesn't change, but we have been.
- // (We really only need the calendar #, and maybe culture)
[Serializable]
internal class EraInfo
{
- internal int era; // The value of the era.
+ internal int era; // The value of the era.
internal long ticks; // The time in ticks when the era starts
- internal int yearOffset; // The offset to Gregorian year when the era starts.
- // Gregorian Year = Era Year + yearOffset
- // Era Year = Gregorian Year - yearOffset
- internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may
- // be affected by the DateTime.MinValue;
- internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1)
+ internal int yearOffset; // The offset to Gregorian year when the era starts.
+ // Gregorian Year = Era Year + yearOffset
+ // Era Year = Gregorian Year - yearOffset
+ internal int minEraYear; // Min year value in this era. Generally, this value is 1, but this may
+ // be affected by the DateTime.MinValue;
+ internal int maxEraYear; // Max year value in this era. (== the year length of the era + 1)
[OptionalField(VersionAdded = 4)]
internal String eraName; // The era name
@@ -57,90 +55,85 @@ namespace System.Globalization {
// This calendar recognizes two era values:
// 0 CurrentEra (AD)
// 1 BeforeCurrentEra (BC)
- [Serializable] internal class GregorianCalendarHelper {
-
+ [Serializable]
+ internal class GregorianCalendarHelper
+ {
// 1 tick = 100ns = 10E-7 second
// Number of ticks per time unit
- internal const long TicksPerMillisecond = 10000;
- internal const long TicksPerSecond = TicksPerMillisecond * 1000;
- internal const long TicksPerMinute = TicksPerSecond * 60;
- internal const long TicksPerHour = TicksPerMinute * 60;
- internal const long TicksPerDay = TicksPerHour * 24;
-
+ internal const long TicksPerMillisecond = 10000;
+ internal const long TicksPerSecond = TicksPerMillisecond * 1000;
+ internal const long TicksPerMinute = TicksPerSecond * 60;
+ internal const long TicksPerHour = TicksPerMinute * 60;
+ internal const long TicksPerDay = TicksPerHour * 24;
+
// Number of milliseconds per time unit
- internal const int MillisPerSecond = 1000;
- internal const int MillisPerMinute = MillisPerSecond * 60;
- internal const int MillisPerHour = MillisPerMinute * 60;
- internal const int MillisPerDay = MillisPerHour * 24;
+ internal const int MillisPerSecond = 1000;
+ internal const int MillisPerMinute = MillisPerSecond * 60;
+ internal const int MillisPerHour = MillisPerMinute * 60;
+ internal const int MillisPerDay = MillisPerHour * 24;
// Number of days in a non-leap year
- internal const int DaysPerYear = 365;
+ internal const int DaysPerYear = 365;
// Number of days in 4 years
- internal const int DaysPer4Years = DaysPerYear * 4 + 1;
+ internal const int DaysPer4Years = DaysPerYear * 4 + 1;
// Number of days in 100 years
- internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
+ internal const int DaysPer100Years = DaysPer4Years * 25 - 1;
// Number of days in 400 years
- internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
-
+ internal const int DaysPer400Years = DaysPer100Years * 4 + 1;
+
// Number of days from 1/1/0001 to 1/1/10000
- internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
+ internal const int DaysTo10000 = DaysPer400Years * 25 - 366;
- internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
+ internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
internal const int DatePartYear = 0;
internal const int DatePartDayOfYear = 1;
internal const int DatePartMonth = 2;
- internal const int DatePartDay = 3;
+ internal const int DatePartDay = 3;
//
// This is the max Gregorian year can be represented by DateTime class. The limitation
// is derived from DateTime class.
//
- internal int MaxYear {
- get {
+ internal int MaxYear
+ {
+ get
+ {
return (m_maxYear);
}
}
- internal static readonly int[] DaysToMonth365 =
+ internal static readonly int[] DaysToMonth365 =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
};
-
- internal static readonly int[] DaysToMonth366 =
+
+ internal static readonly int[] DaysToMonth366 =
{
0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
};
- // Strictly these don't need serialized since they can be recreated from the calendar id
[OptionalField(VersionAdded = 1)]
internal int m_maxYear = 9999;
[OptionalField(VersionAdded = 1)]
internal int m_minYear;
internal Calendar m_Cal;
- // Era information doesn't need serialized, its constant for the same calendars (ie: we can recreate it from the calendar id)
[OptionalField(VersionAdded = 1)]
- internal EraInfo[] m_EraInfo;
+ internal EraInfo[] m_EraInfo;
[OptionalField(VersionAdded = 1)]
internal int[] m_eras = null;
- // m_minDate is existing here just to keep the serialization compatibility.
- // it has nothing to do with the code anymore.
- [OptionalField(VersionAdded = 1)]
- internal DateTime m_minDate;
-
+
// Construct an instance of gregorian calendar.
- internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) {
+ internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo)
+ {
m_Cal = cal;
- m_EraInfo = eraInfo;
- // m_minDate is existing here just to keep the serialization compatibility.
- // it has nothing to do with the code anymore.
- m_minDate = m_Cal.MinSupportedDateTime;
+ m_EraInfo = eraInfo;
m_maxYear = m_EraInfo[0].maxEraYear;
- m_minYear = m_EraInfo[0].minEraYear;;
+ m_minYear = m_EraInfo[0].minEraYear; ;
}
-
+
/*=================================GetGregorianYear==========================
**Action: Get the Gregorian year value for the specified year in an era.
**Returns: The Gregorian year value.
@@ -151,58 +144,70 @@ namespace System.Globalization {
** ArgumentOutOfRangeException if year value is invalid or era value is invalid.
============================================================================*/
- internal int GetGregorianYear(int year, int era) {
- if (year < 0) {
+ internal int GetGregorianYear(int year, int era)
+ {
+ if (year < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
+ SR.ArgumentOutOfRange_NeedNonNegNum);
+ }
Contract.EndContractBlock();
- if (era == Calendar.CurrentEra) {
+ if (era == Calendar.CurrentEra)
+ {
era = m_Cal.CurrentEraValue;
}
-
- for (int i = 0; i < m_EraInfo.Length; i++) {
- if (era == m_EraInfo[i].era) {
- if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) {
+
+ for (int i = 0; i < m_EraInfo.Length; i++)
+ {
+ if (era == m_EraInfo[i].era)
+ {
+ if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear)
+ {
throw new ArgumentOutOfRangeException(
- nameof(year),
+ nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- m_EraInfo[i].minEraYear,
+ SR.ArgumentOutOfRange_Range,
+ m_EraInfo[i].minEraYear,
m_EraInfo[i].maxEraYear));
}
return (m_EraInfo[i].yearOffset + year);
}
}
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
+ throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue);
}
-
- internal bool IsValidYear(int year, int era) {
- if (year < 0) {
+
+ internal bool IsValidYear(int year, int era)
+ {
+ if (year < 0)
+ {
return false;
- }
+ }
- if (era == Calendar.CurrentEra) {
+ if (era == Calendar.CurrentEra)
+ {
era = m_Cal.CurrentEraValue;
}
-
- for (int i = 0; i < m_EraInfo.Length; i++) {
- if (era == m_EraInfo[i].era) {
- if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear) {
+
+ for (int i = 0; i < m_EraInfo.Length; i++)
+ {
+ if (era == m_EraInfo[i].era)
+ {
+ if (year < m_EraInfo[i].minEraYear || year > m_EraInfo[i].maxEraYear)
+ {
return false;
}
return true;
}
}
return false;
- }
-
+ }
+
// Returns a given date part of this DateTime. This method is used
// to compute the year, day-of-year, month, or day part.
- internal virtual int GetDatePart(long ticks, int part)
+ internal virtual int GetDatePart(long ticks, int part)
{
CheckTicksRange(ticks);
// n = number of days since 1/1/0001
@@ -214,7 +219,7 @@ namespace System.Globalization {
// y100 = number of whole 100-year periods within 400-year period
int y100 = n / DaysPer100Years;
// Last 100-year period has an extra day, so decrement result if 4
- if (y100 == 4) y100 = 3;
+ if (y100 == 4) y100 = 3;
// n = day number within 100-year period
n -= y100 * DaysPer100Years;
// y4 = number of whole 4-year periods within 100-year period
@@ -224,23 +229,23 @@ namespace System.Globalization {
// y1 = number of whole years within 4-year period
int y1 = n / DaysPerYear;
// Last year has an extra day, so decrement result if 4
- if (y1 == 4) y1 = 3;
+ if (y1 == 4) y1 = 3;
// If year was requested, compute and return it
- if (part == DatePartYear)
+ if (part == DatePartYear)
{
return (y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1);
}
// n = day number within year
n -= y1 * DaysPerYear;
// If day-of-year was requested, return it
- if (part == DatePartDayOfYear)
+ if (part == DatePartDayOfYear)
{
return (n + 1);
}
// Leap year calculation looks different from IsLeapYear since y1, y4,
// and y100 are relative to year 1, not year 0
bool leapYear = (y1 == 3 && (y4 != 24 || y100 == 3));
- int[] days = leapYear? DaysToMonth366: DaysToMonth365;
+ int[] days = leapYear ? DaysToMonth366 : DaysToMonth365;
// All months have less than 32 days, so n >> 5 is a good conservative
// estimate for the month
int m = (n >> 5) + 1;
@@ -270,23 +275,26 @@ namespace System.Globalization {
**
============================================================================*/
- internal static long GetAbsoluteDate(int year, int month, int day) {
- if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
+ internal static long GetAbsoluteDate(int year, int month, int day)
+ {
+ if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
- int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366: DaysToMonth365;
- if (day >= 1 && (day <= days[month] - days[month - 1])) {
+ int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365;
+ if (day >= 1 && (day <= days[month] - days[month - 1]))
+ {
int y = year - 1;
int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
return (absoluteDate);
}
}
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
+ throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
+ }
// Returns the tick count corresponding to the given year, month, and day.
// Will check the if the parameters are valid.
- internal static long DateToTicks(int year, int month, int day) {
- return (GetAbsoluteDate(year, month, day)* TicksPerDay);
+ internal static long DateToTicks(int year, int month, int day)
+ {
+ return (GetAbsoluteDate(year, month, day) * TicksPerDay);
}
// Return the tick count corresponding to the given hour, minute, second.
@@ -295,30 +303,33 @@ namespace System.Globalization {
{
//TimeSpan.TimeToTicks is a family access function which does no error checking, so
//we need to put some error checking out here.
- if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
+ if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
{
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
throw new ArgumentOutOfRangeException(
- nameof(millisecond),
+ nameof(millisecond),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 0,
+ SR.ArgumentOutOfRange_Range,
+ 0,
MillisPerSecond - 1));
- }
- return (TimeSpan.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond);;
+ }
+ return (InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond); ;
}
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
+ throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
}
-
- internal void CheckTicksRange(long ticks) {
- if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) {
+
+ internal void CheckTicksRange(long ticks)
+ {
+ if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks)
+ {
throw new ArgumentOutOfRangeException(
- "time",
+ "time",
String.Format(
- CultureInfo.InvariantCulture,
- Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
+ CultureInfo.InvariantCulture,
+ SR.ArgumentOutOfRange_CalendarRange,
m_Cal.MinSupportedDateTime,
m_Cal.MaxSupportedDateTime));
}
@@ -342,15 +353,16 @@ namespace System.Globalization {
// or equal to d that denotes a valid day in month m1 of year
// y1.
//
- public DateTime AddMonths(DateTime time, int months)
+ public DateTime AddMonths(DateTime time, int months)
{
- if (months < -120000 || months > 120000) {
+ if (months < -120000 || months > 120000)
+ {
throw new ArgumentOutOfRangeException(
- nameof(months),
+ nameof(months),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- -120000,
+ SR.ArgumentOutOfRange_Range,
+ -120000,
120000));
}
Contract.EndContractBlock();
@@ -360,20 +372,20 @@ namespace System.Globalization {
int m = GetDatePart(time.Ticks, DatePartMonth);
int d = GetDatePart(time.Ticks, DatePartDay);
int i = m - 1 + months;
- if (i >= 0)
+ if (i >= 0)
{
m = i % 12 + 1;
y = y + i / 12;
}
- else
+ else
{
m = 12 + (i + 1) % 12;
y = y + (i - 11) / 12;
}
- int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365;
- int days = (daysArray[m] - daysArray[m - 1]);
-
- if (d > days)
+ int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365;
+ int days = (daysArray[m] - daysArray[m - 1]);
+
+ if (d > days)
{
d = days;
}
@@ -381,7 +393,7 @@ namespace System.Globalization {
Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime);
return (new DateTime(ticks));
}
-
+
// Returns the DateTime resulting from adding the given number of
// years to the specified DateTime. The result is computed by incrementing
// (or decrementing) the year part of the specified DateTime by value
@@ -390,11 +402,11 @@ namespace System.Globalization {
// DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of the specified DateTime.
//
- public DateTime AddYears(DateTime time, int years)
+ public DateTime AddYears(DateTime time, int years)
{
return (AddMonths(time, years * 12));
}
-
+
// Returns the day-of-month part of the specified DateTime. The returned
// value is an integer between 1 and 31.
//
@@ -402,18 +414,18 @@ namespace System.Globalization {
{
return (GetDatePart(time.Ticks, DatePartDay));
}
-
+
// Returns the day-of-week part of the specified DateTime. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
- public DayOfWeek GetDayOfWeek(DateTime time)
+ public DayOfWeek GetDayOfWeek(DateTime time)
{
CheckTicksRange(time.Ticks);
return ((DayOfWeek)((time.Ticks / TicksPerDay + 1) % 7));
}
-
+
// Returns the day-of-year part of the specified DateTime. The returned value
// is an integer between 1 and 366.
//
@@ -426,18 +438,20 @@ namespace System.Globalization {
// month arguments.
//
[Pure]
- public int GetDaysInMonth(int year, int month, int era) {
+ public int GetDaysInMonth(int year, int month, int era)
+ {
//
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
+ if (month < 1 || month > 12)
+ {
+ throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
}
- int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366: DaysToMonth365);
- return (days[month] - days[month - 1]);
+ int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365);
+ return (days[month] - days[month - 1]);
}
-
+
// Returns the number of days in the year given by the year argument for the current era.
//
@@ -447,83 +461,93 @@ namespace System.Globalization {
// Convert year/era value to Gregorain year value.
//
year = GetGregorianYear(year, era);
- return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366:365);
+ return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365);
}
-
+
// Returns the era for the specified DateTime value.
public int GetEra(DateTime time)
{
long ticks = time.Ticks;
// The assumption here is that m_EraInfo is listed in reverse order.
- for (int i = 0; i < m_EraInfo.Length; i++) {
- if (ticks >= m_EraInfo[i].ticks) {
+ for (int i = 0; i < m_EraInfo.Length; i++)
+ {
+ if (ticks >= m_EraInfo[i].ticks)
+ {
return (m_EraInfo[i].era);
}
}
- throw new ArgumentOutOfRangeException(nameof(time), Environment.GetResourceString("ArgumentOutOfRange_Era"));
+ throw new ArgumentOutOfRangeException(nameof(time), SR.ArgumentOutOfRange_Era);
}
- public int[] Eras {
- get {
- if (m_eras == null) {
+ public int[] Eras
+ {
+ get
+ {
+ if (m_eras == null)
+ {
m_eras = new int[m_EraInfo.Length];
- for (int i = 0; i < m_EraInfo.Length; i++) {
+ for (int i = 0; i < m_EraInfo.Length; i++)
+ {
m_eras[i] = m_EraInfo[i].era;
}
}
return ((int[])m_eras.Clone());
}
}
-
+
// Returns the month part of the specified DateTime. The returned value is an
// integer between 1 and 12.
//
- public int GetMonth(DateTime time)
+ public int GetMonth(DateTime time)
{
return (GetDatePart(time.Ticks, DatePartMonth));
}
-
+
// Returns the number of months in the specified year and era.
public int GetMonthsInYear(int year, int era)
{
year = GetGregorianYear(year, era);
return (12);
}
-
+
// Returns the year part of the specified DateTime. The returned value is an
// integer between 1 and 9999.
//
- public int GetYear(DateTime time)
+ public int GetYear(DateTime time)
{
long ticks = time.Ticks;
int year = GetDatePart(ticks, DatePartYear);
- for (int i = 0; i < m_EraInfo.Length; i++) {
- if (ticks >= m_EraInfo[i].ticks) {
+ for (int i = 0; i < m_EraInfo.Length; i++)
+ {
+ if (ticks >= m_EraInfo[i].ticks)
+ {
return (year - m_EraInfo[i].yearOffset);
}
}
- throw new ArgumentException(Environment.GetResourceString("Argument_NoEra"));
- }
-
+ throw new ArgumentException(SR.Argument_NoEra);
+ }
+
// Returns the year that match the specified Gregorian year. The returned value is an
// integer between 1 and 9999.
//
- public int GetYear(int year, DateTime time)
+ public int GetYear(int year, DateTime time)
{
long ticks = time.Ticks;
- for (int i = 0; i < m_EraInfo.Length; i++) {
- // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
- // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
- // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
+ for (int i = 0; i < m_EraInfo.Length; i++)
+ {
+ // while calculating dates with JapaneseLuniSolarCalendar, we can run into cases right after the start of the era
+ // and still belong to the month which is started in previous era. Calculating equivalent calendar date will cause
+ // using the new era info which will have the year offset equal to the year we are calculating year = m_EraInfo[i].yearOffset
// which will end up with zero as calendar year.
// We should use the previous era info instead to get the right year number. Example of such date is Feb 2nd 1989
- if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) {
+ if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset)
+ {
return (year - m_EraInfo[i].yearOffset);
}
}
- throw new ArgumentException(Environment.GetResourceString("Argument_NoEra"));
- }
+ throw new ArgumentException(SR.Argument_NoEra);
+ }
// Checks whether a given day in the specified era is a leap day. This method returns true if
// the date is a leap day, or false if not.
@@ -531,35 +555,38 @@ namespace System.Globalization {
public bool IsLeapDay(int year, int month, int day, int era)
{
// year/month/era checking is done in GetDaysInMonth()
- if (day < 1 || day > GetDaysInMonth(year, month, era)) {
+ if (day < 1 || day > GetDaysInMonth(year, month, era))
+ {
throw new ArgumentOutOfRangeException(
- nameof(day),
+ nameof(day),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- GetDaysInMonth(year, month, era)));
+ SR.ArgumentOutOfRange_Range,
+ 1,
+ GetDaysInMonth(year, month, era)));
}
Contract.EndContractBlock();
-
- if (!IsLeapYear(year, era)) {
+
+ if (!IsLeapYear(year, era))
+ {
return (false);
}
-
- if (month == 2 && day == 29) {
+
+ if (month == 2 && day == 29)
+ {
return (true);
}
-
- return (false);
+
+ return (false);
}
-
+
// Returns the leap month in a calendar year of the specified era. This method returns 0
// if this calendar does not have leap month, or this year is not a leap year.
//
public int GetLeapMonth(int year, int era)
{
year = GetGregorianYear(year, era);
- return (0);
+ return (0);
}
// Checks whether a given month in the specified era is a leap month. This method returns true if
@@ -568,36 +595,40 @@ namespace System.Globalization {
public bool IsLeapMonth(int year, int month, int era)
{
year = GetGregorianYear(year, era);
- if (month < 1 || month > 12) {
+ if (month < 1 || month > 12)
+ {
throw new ArgumentOutOfRangeException(
- nameof(month),
+ nameof(month),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- 12));
- }
- return (false);
+ SR.ArgumentOutOfRange_Range,
+ 1,
+ 12));
+ }
+ return (false);
}
-
+
// Checks whether a given year in the specified era is a leap year. This method returns true if
// year is a leap year, or false if not.
//
- public bool IsLeapYear(int year, int era) {
+ public bool IsLeapYear(int year, int era)
+ {
year = GetGregorianYear(year, era);
return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
}
-
+
// Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
//
- public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
+ public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
+ {
year = GetGregorianYear(year, era);
long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond);
CheckTicksRange(ticks);
return (new DateTime(ticks));
}
- public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) {
+ public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
+ {
CheckTicksRange(time.Ticks);
// Use GregorianCalendar to get around the problem that the implmentation in Calendar.GetWeekOfYear()
// can call GetYear() that exceeds the supported range of the Gregorian-based calendars.
@@ -605,29 +636,33 @@ namespace System.Globalization {
}
- public int ToFourDigitYear(int year, int twoDigitYearMax) {
- if (year < 0) {
+ public int ToFourDigitYear(int year, int twoDigitYearMax)
+ {
+ if (year < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ SR.ArgumentOutOfRange_NeedPosNum);
}
Contract.EndContractBlock();
-
- if (year < 100) {
+
+ if (year < 100)
+ {
int y = year % 100;
- return ((twoDigitYearMax/100 - ( y > twoDigitYearMax % 100 ? 1 : 0))*100 + y);
+ return ((twoDigitYearMax / 100 - (y > twoDigitYearMax % 100 ? 1 : 0)) * 100 + y);
}
-
- if (year < m_minYear || year > m_maxYear) {
+
+ if (year < m_minYear || year > m_maxYear)
+ {
throw new ArgumentOutOfRangeException(
nameof(year),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), m_minYear, m_maxYear));
+ SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear));
}
// If the year value is above 100, just return the year value. Don't have to do
// the TwoDigitYearMax comparison.
return (year);
}
- }
+ }
}
diff --git a/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs b/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
deleted file mode 100644
index 1af5e9221c..0000000000
--- a/src/mscorlib/src/System/Globalization/GregorianCalendarTypes.cs
+++ /dev/null
@@ -1,17 +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.
-
-namespace System.Globalization {
- using System;
-
- [Serializable]
- public enum GregorianCalendarTypes {
- Localized = Calendar.CAL_GREGORIAN,
- USEnglish = Calendar.CAL_GREGORIAN_US,
- MiddleEastFrench = Calendar.CAL_GREGORIAN_ME_FRENCH,
- Arabic = Calendar.CAL_GREGORIAN_ARABIC,
- TransliteratedEnglish = Calendar.CAL_GREGORIAN_XLIT_ENGLISH,
- TransliteratedFrench = Calendar.CAL_GREGORIAN_XLIT_FRENCH,
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs b/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
deleted file mode 100644
index 190c3f17d2..0000000000
--- a/src/mscorlib/src/System/Globalization/HebrewCalendar.cs
+++ /dev/null
@@ -1,1084 +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.
-
-namespace System.Globalization {
- using System;
- using System.Text;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Rules for the Hebrew calendar:
- // - The Hebrew calendar is both a Lunar (months) and Solar (years)
- // calendar, but allows for a week of seven days.
- // - Days begin at sunset.
- // - Leap Years occur in the 3, 6, 8, 11, 14, 17, & 19th years of a
- // 19-year cycle. Year = leap iff ((7y+1) mod 19 < 7).
- // - There are 12 months in a common year and 13 months in a leap year.
- // - In a common year, the 6th month, Adar, has 29 days. In a leap
- // year, the 6th month, Adar I, has 30 days and the leap month,
- // Adar II, has 29 days.
- // - Common years have 353-355 days. Leap years have 383-385 days.
- // - The Hebrew new year (Rosh HaShanah) begins on the 1st of Tishri,
- // the 7th month in the list below.
- // - The new year may not begin on Sunday, Wednesday, or Friday.
- // - If the new year would fall on a Tuesday and the conjunction of
- // the following year were at midday or later, the new year is
- // delayed until Thursday.
- // - If the new year would fall on a Monday after a leap year, the
- // new year is delayed until Tuesday.
- // - The length of the 8th and 9th months vary from year to year,
- // depending on the overall length of the year.
- // - The length of a year is determined by the dates of the new
- // years (Tishri 1) preceding and following the year in question.
- // - The 2th month is long (30 days) if the year has 355 or 385 days.
- // - The 3th month is short (29 days) if the year has 353 or 383 days.
- // - The Hebrew months are:
- // 1. Tishri (30 days)
- // 2. Heshvan (29 or 30 days)
- // 3. Kislev (29 or 30 days)
- // 4. Teveth (29 days)
- // 5. Shevat (30 days)
- // 6. Adar I (30 days)
- // 7. Adar {II} (29 days, this only exists if that year is a leap year)
- // 8. Nisan (30 days)
- // 9. Iyyar (29 days)
- // 10. Sivan (30 days)
- // 11. Tammuz (29 days)
- // 12. Av (30 days)
- // 13. Elul (29 days)
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1583/01/01 2239/09/29
- ** Hebrew 5343/04/07 5999/13/29
- */
-
-// Includes CHebrew implemetation;i.e All the code necessary for converting
-// Gregorian to Hebrew Lunar from 1583 to 2239.
-
-
- [Serializable]
- public class HebrewCalendar : Calendar {
-
-
- public static readonly int HebrewEra = 1;
-
- internal const int DatePartYear = 0;
- internal const int DatePartDayOfYear = 1;
- internal const int DatePartMonth = 2;
- internal const int DatePartDay = 3;
- internal const int DatePartDayOfWeek = 4;
-
- //
- // Hebrew Translation Table.
- //
- // This table is used to get the following Hebrew calendar information for a
- // given Gregorian year:
- // 1. The day of the Hebrew month corresponding to Gregorian January 1st
- // for a given Gregorian year.
- // 2. The month of the Hebrew month corresponding to Gregorian January 1st
- // for a given Gregorian year.
- // The information is not directly in the table. Instead, the info is decoded
- // by special values (numbers above 29 and below 1).
- // 3. The type of the Hebrew year for a given Gregorian year.
- //
-
- /*
- More notes:
-
- This table includes 2 numbers for each year.
- The offset into the table determines the year. (offset 0 is Gregorian year 1500)
- 1st number determines the day of the Hebrew month coresponeds to January 1st.
- 2nd number determines the type of the Hebrew year. (the type determines how
- many days are there in the year.)
-
- normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
- Leap years : 4 = 383 5 384 6 = 385 days.
-
- A 99 means the year is not supported for translation.
- for convenience the table was defined for 750 year,
- but only 640 years are supported. (from 1583 to 2239)
- the years before 1582 (starting of Georgian calander)
- and after 2239, are filled with 99.
-
- Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days.
- That's why, there no nead to specify the lunar month in the table.
- There are exceptions, these are coded by giving numbers above 29 and below 1.
- Actual decoding is takenig place whenever fetching information from the table.
- The function for decoding is in GetLunarMonthDay().
-
- Example:
- The data for 2000 - 2005 A.D. is:
-
- 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004
-
- For year 2000, we know it has a Hebrew year type 6, which means it has 385 days.
- And 1/1/2000 A.D. is Hebrew year 5760, 23rd day of 4th month.
- */
-
- //
- // Jewish Era in use today is dated from the supposed year of the
- // Creation with its beginning in 3761 B.C.
- //
-
- // The Hebrew year of Gregorian 1st year AD.
- // 0001/01/01 AD is Hebrew 3760/01/01
- private const int HebrewYearOf1AD = 3760;
-
- // The first Gregorian year in HebrewTable.
- private const int FirstGregorianTableYear = 1583; // == Hebrew Year 5343
- // The last Gregorian year in HebrewTable.
- private const int LastGregorianTableYear = 2239; // == Hebrew Year 5999
- private const int TABLESIZE = (LastGregorianTableYear-FirstGregorianTableYear);
-
- private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343
- private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999
-
- private static readonly int[] HebrewTable = {
- 7,3,17,3, // 1583-1584 (Hebrew year: 5343 - 5344)
- 0,4,11,2,21,6,1,3,13,2, // 1585-1589
- 25,4,5,3,16,2,27,6,9,1, // 1590-1594
- 20,2,0,6,11,3,23,4,4,2, // 1595-1599
- 14,3,27,4,8,2,18,3,28,6, // 1600
- 11,1,22,5,2,3,12,3,25,4, // 1605
- 6,2,16,3,26,6,8,2,20,1, // 1610
- 0,6,11,2,24,4,4,3,15,2, // 1615
- 25,6,8,1,19,2,29,6,9,3, // 1620
- 22,4,3,2,13,3,25,4,6,3, // 1625
- 17,2,27,6,7,3,19,2,31,4, // 1630
- 11,3,23,4,5,2,15,3,25,6, // 1635
- 6,2,19,1,29,6,10,2,22,4, // 1640
- 3,3,14,2,24,6,6,1,17,3, // 1645
- 28,5,8,3,20,1,32,5,12,3, // 1650
- 22,6,4,1,16,2,26,6,6,3, // 1655
- 17,2,0,4,10,3,22,4,3,2, // 1660
- 14,3,24,6,5,2,17,1,28,6, // 1665
- 9,2,19,3,31,4,13,2,23,6, // 1670
- 3,3,15,1,27,5,7,3,17,3, // 1675
- 29,4,11,2,21,6,3,1,14,2, // 1680
- 25,6,5,3,16,2,28,4,9,3, // 1685
- 20,2,0,6,12,1,23,6,4,2, // 1690
- 14,3,26,4,8,2,18,3,0,4, // 1695
- 10,3,21,5,1,3,13,1,24,5, // 1700
- 5,3,15,3,27,4,8,2,19,3, // 1705
- 29,6,10,2,22,4,3,3,14,2, // 1710
- 26,4,6,3,18,2,28,6,10,1, // 1715
- 20,6,2,2,12,3,24,4,5,2, // 1720
- 16,3,28,4,8,3,19,2,0,6, // 1725
- 12,1,23,5,3,3,14,3,26,4, // 1730
- 7,2,17,3,28,6,9,2,21,4, // 1735
- 1,3,13,2,25,4,5,3,16,2, // 1740
- 27,6,9,1,19,3,0,5,11,3, // 1745
- 23,4,4,2,14,3,25,6,7,1, // 1750
- 18,2,28,6,9,3,21,4,2,2, // 1755
- 12,3,25,4,6,2,16,3,26,6, // 1760
- 8,2,20,1,0,6,11,2,22,6, // 1765
- 4,1,15,2,25,6,6,3,18,1, // 1770
- 29,5,9,3,22,4,2,3,13,2, // 1775
- 23,6,4,3,15,2,27,4,7,3, // 1780
- 19,2,31,4,11,3,21,6,3,2, // 1785
- 15,1,25,6,6,2,17,3,29,4, // 1790
- 10,2,20,6,3,1,13,3,24,5, // 1795
- 4,3,16,1,27,5,7,3,17,3, // 1800
- 0,4,11,2,21,6,1,3,13,2, // 1805
- 25,4,5,3,16,2,29,4,9,3, // 1810
- 19,6,30,2,13,1,23,6,4,2, // 1815
- 14,3,27,4,8,2,18,3,0,4, // 1820
- 11,3,22,5,2,3,14,1,26,5, // 1825
- 6,3,16,3,28,4,10,2,20,6, // 1830
- 30,3,11,2,24,4,4,3,15,2, // 1835
- 25,6,8,1,19,2,29,6,9,3, // 1840
- 22,4,3,2,13,3,25,4,7,2, // 1845
- 17,3,27,6,9,1,21,5,1,3, // 1850
- 11,3,23,4,5,2,15,3,25,6, // 1855
- 6,2,19,1,29,6,10,2,22,4, // 1860
- 3,3,14,2,24,6,6,1,18,2, // 1865
- 28,6,8,3,20,4,2,2,12,3, // 1870
- 24,4,4,3,16,2,26,6,6,3, // 1875
- 17,2,0,4,10,3,22,4,3,2, // 1880
- 14,3,24,6,5,2,17,1,28,6, // 1885
- 9,2,21,4,1,3,13,2,23,6, // 1890
- 5,1,15,3,27,5,7,3,19,1, // 1895
- 0,5,10,3,22,4,2,3,13,2, // 1900
- 24,6,4,3,15,2,27,4,8,3, // 1905
- 20,4,1,2,11,3,22,6,3,2, // 1910
- 15,1,25,6,7,2,17,3,29,4, // 1915
- 10,2,21,6,1,3,13,1,24,5, // 1920
- 5,3,15,3,27,4,8,2,19,6, // 1925
- 1,1,12,2,22,6,3,3,14,2, // 1930
- 26,4,6,3,18,2,28,6,10,1, // 1935
- 20,6,2,2,12,3,24,4,5,2, // 1940
- 16,3,28,4,9,2,19,6,30,3, // 1945
- 12,1,23,5,3,3,14,3,26,4, // 1950
- 7,2,17,3,28,6,9,2,21,4, // 1955
- 1,3,13,2,25,4,5,3,16,2, // 1960
- 27,6,9,1,19,6,30,2,11,3, // 1965
- 23,4,4,2,14,3,27,4,7,3, // 1970
- 18,2,28,6,11,1,22,5,2,3, // 1975
- 12,3,25,4,6,2,16,3,26,6, // 1980
- 8,2,20,4,30,3,11,2,24,4, // 1985
- 4,3,15,2,25,6,8,1,18,3, // 1990
- 29,5,9,3,22,4,3,2,13,3, // 1995
- 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004
- 20,4,1,2,11,3,23,4,5,2, // 2005 - 2009
- 15,3,25,6,6,2,19,1,29,6, // 2010
- 10,2,20,6,3,1,14,2,24,6, // 2015
- 4,3,17,1,28,5,8,3,20,4, // 2020
- 1,3,12,2,22,6,2,3,14,2, // 2025
- 26,4,6,3,17,2,0,4,10,3, // 2030
- 20,6,1,2,14,1,24,6,5,2, // 2035
- 15,3,28,4,9,2,19,6,1,1, // 2040
- 12,3,23,5,3,3,15,1,27,5, // 2045
- 7,3,17,3,29,4,11,2,21,6, // 2050
- 1,3,12,2,25,4,5,3,16,2, // 2055
- 28,4,9,3,19,6,30,2,12,1, // 2060
- 23,6,4,2,14,3,26,4,8,2, // 2065
- 18,3,0,4,10,3,22,5,2,3, // 2070
- 14,1,25,5,6,3,16,3,28,4, // 2075
- 9,2,20,6,30,3,11,2,23,4, // 2080
- 4,3,15,2,27,4,7,3,19,2, // 2085
- 29,6,11,1,21,6,3,2,13,3, // 2090
- 25,4,6,2,17,3,27,6,9,1, // 2095
- 20,5,30,3,10,3,22,4,3,2, // 2100
- 14,3,24,6,5,2,17,1,28,6, // 2105
- 9,2,21,4,1,3,13,2,23,6, // 2110
- 5,1,16,2,27,6,7,3,19,4, // 2115
- 30,2,11,3,23,4,3,3,14,2, // 2120
- 25,6,5,3,16,2,28,4,9,3, // 2125
- 21,4,2,2,12,3,23,6,4,2, // 2130
- 16,1,26,6,8,2,20,4,30,3, // 2135
- 11,2,22,6,4,1,14,3,25,5, // 2140
- 6,3,18,1,29,5,9,3,22,4, // 2145
- 2,3,13,2,23,6,4,3,15,2, // 2150
- 27,4,7,3,20,4,1,2,11,3, // 2155
- 21,6,3,2,15,1,25,6,6,2, // 2160
- 17,3,29,4,10,2,20,6,3,1, // 2165
- 13,3,24,5,4,3,17,1,28,5, // 2170
- 8,3,18,6,1,1,12,2,22,6, // 2175
- 2,3,14,2,26,4,6,3,17,2, // 2180
- 28,6,10,1,20,6,1,2,12,3, // 2185
- 24,4,5,2,15,3,28,4,9,2, // 2190
- 19,6,33,3,12,1,23,5,3,3, // 2195
- 13,3,25,4,6,2,16,3,26,6, // 2200
- 8,2,20,4,30,3,11,2,24,4, // 2205
- 4,3,15,2,25,6,8,1,18,6, // 2210
- 33,2,9,3,22,4,3,2,13,3, // 2215
- 25,4,6,3,17,2,27,6,9,1, // 2220
- 21,5,1,3,11,3,23,4,5,2, // 2225
- 15,3,25,6,6,2,19,4,33,3, // 2230
- 10,2,22,4,3,3,14,2,24,6, // 2235
- 6,1 // 2240 (Hebrew year: 6000)
- };
-
- //
- // The lunar calendar has 6 different variations of month lengths
- // within a year.
- //
- private static readonly int[,] LunarMonthLen = {
- {0,00,00,00,00,00,00,00,00,00,00,00,00,0},
- {0,30,29,29,29,30,29,30,29,30,29,30,29,0}, // 3 common year variations
- {0,30,29,30,29,30,29,30,29,30,29,30,29,0},
- {0,30,30,30,29,30,29,30,29,30,29,30,29,0},
- {0,30,29,29,29,30,30,29,30,29,30,29,30,29}, // 3 leap year variations
- {0,30,29,30,29,30,30,29,30,29,30,29,30,29},
- {0,30,30,30,29,30,30,29,30,29,30,29,30,29}
- };
-
- //internal static Calendar m_defaultInstance;
-
- internal static readonly DateTime calendarMinValue = new DateTime(1583, 1, 1);
- // Gregorian 2239/9/29 = Hebrew 5999/13/29 (last day in Hebrew year 5999).
- // We can only format/parse Hebrew numbers up to 999, so we limit the max range to Hebrew year 5999.
- internal static readonly DateTime calendarMaxValue = new DateTime((new DateTime(2239, 9, 29, 23, 59, 59, 999)).Ticks + 9999);
-
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (calendarMinValue);
- }
- }
-
-
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (calendarMaxValue);
- }
- }
-
-
- // Return the type of the Hebrew calendar.
- //
-
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.LunisolarCalendar;
- }
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of HebrewCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
-
- /*
- internal static Calendar GetDefaultInstance() {
- if (m_defaultInstance == null) {
- m_defaultInstance = new HebrewCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
-
- // Construct an instance of gregorian calendar.
-
- public HebrewCalendar() {
- }
-
- internal override int ID {
- get {
- return (CAL_HEBREW);
- }
- }
-
-
- /*=================================CheckHebrewYearValue==========================
- **Action: Check if the Hebrew year value is supported in this class.
- **Returns: None.
- **Arguments: y Hebrew year value
- ** ear Hebrew era value
- **Exceptions: ArgumentOutOfRange_Range if the year value is not supported.
- **Note:
- ** We use a table for the Hebrew calendar calculation, so the year supported is limited.
- ============================================================================*/
-
- static private void CheckHebrewYearValue(int y, int era, String varName) {
- CheckEraRange(era);
- if (y > MaxHebrewYear || y < MinHebrewYear) {
- throw new ArgumentOutOfRangeException(
- varName,
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MinHebrewYear,
- MaxHebrewYear));
- }
- }
-
- /*=================================CheckHebrewMonthValue==========================
- **Action: Check if the Hebrew month value is valid.
- **Returns: None.
- **Arguments: year Hebrew year value
- ** month Hebrew month value
- **Exceptions: ArgumentOutOfRange_Range if the month value is not valid.
- **Note:
- ** Call CheckHebrewYearValue() before calling this to verify the year value is supported.
- ============================================================================*/
-
- private void CheckHebrewMonthValue(int year, int month, int era) {
- int monthsInYear = GetMonthsInYear(year, era);
- if (month < 1 || month > monthsInYear) {
- throw new ArgumentOutOfRangeException(
- nameof(month),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- monthsInYear));
- }
- }
-
- /*=================================CheckHebrewDayValue==========================
- **Action: Check if the Hebrew day value is valid.
- **Returns: None.
- **Arguments: year Hebrew year value
- ** month Hebrew month value
- ** day Hebrew day value.
- **Exceptions: ArgumentOutOfRange_Range if the day value is not valid.
- **Note:
- ** Call CheckHebrewYearValue()/CheckHebrewMonthValue() before calling this to verify the year/month values are valid.
- ============================================================================*/
-
- private void CheckHebrewDayValue(int year, int month, int day, int era) {
- int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- daysInMonth));
- }
- }
-
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != HebrewEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
- }
-
- static private void CheckTicksRange(long ticks) {
- if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) {
- throw new ArgumentOutOfRangeException(
- "time",
- // Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar.
- String.Format(
- CultureInfo.InvariantCulture,
- Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
- calendarMinValue,
- calendarMaxValue));
- }
- }
-
- static internal int GetResult(__DateBuffer result, int part) {
- switch (part) {
- case DatePartYear:
- return (result.year);
- case DatePartMonth:
- return (result.month);
- case DatePartDay:
- return (result.day);
- }
-
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DateTimeParsing"));
- }
-
- /*=================================GetLunarMonthDay==========================
- **Action: Using the Hebrew table (HebrewTable) to get the Hebrew month/day value for Gregorian January 1st
- ** in a given Gregorian year.
- ** Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days.
- ** That's why, there no nead to specify the lunar month in the table. There are exceptions, and these
- ** are coded by giving numbers above 29 and below 1.
- ** Actual decoding is takenig place in the switch statement below.
- **Returns:
- ** The Hebrew year type. The value is from 1 to 6.
- ** normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
- ** Leap years : 4 = 383 5 384 6 = 385 days.
- **Arguments:
- ** gregorianYear The year value in Gregorian calendar. The value should be between 1500 and 2239.
- ** lunarDate Object to take the result of the Hebrew year/month/day.
- **Exceptions:
- ============================================================================*/
-
- static internal int GetLunarMonthDay(int gregorianYear, __DateBuffer lunarDate) {
- //
- // Get the offset into the LunarMonthLen array and the lunar day
- // for January 1st.
- //
- int index = gregorianYear - FirstGregorianTableYear;
- if (index < 0 || index > TABLESIZE) {
- throw new ArgumentOutOfRangeException(nameof(gregorianYear));
- }
-
- index *= 2;
- lunarDate.day = HebrewTable[index];
-
- // Get the type of the year. The value is from 1 to 6
- int LunarYearType = HebrewTable[index + 1];
-
- //
- // Get the Lunar Month.
- //
- switch (lunarDate.day) {
- case ( 0 ) : // 1/1 is on Shvat 1
- lunarDate.month = 5;
- lunarDate.day = 1;
- break;
- case ( 30 ) : // 1/1 is on Kislev 30
- lunarDate.month = 3;
- break;
- case ( 31 ) : // 1/1 is on Shvat 2
- lunarDate.month = 5;
- lunarDate.day = 2;
- break;
- case ( 32 ) : // 1/1 is on Shvat 3
- lunarDate.month = 5;
- lunarDate.day = 3;
- break;
- case ( 33 ) : // 1/1 is on Kislev 29
- lunarDate.month = 3;
- lunarDate.day = 29;
- break;
- default : // 1/1 is on Tevet (This is the general case)
- lunarDate.month = 4;
- break;
- }
- return (LunarYearType);
- }
-
- // Returns a given date part of this DateTime. This method is used
- // to compute the year, day-of-year, month, or day part.
-
- internal virtual int GetDatePart(long ticks, int part) {
- // The Gregorian year, month, day value for ticks.
- int gregorianYear, gregorianMonth, gregorianDay;
- int hebrewYearType; // lunar year type
- long AbsoluteDate; // absolute date - absolute date 1/1/1600
-
- //
- // Make sure we have a valid Gregorian date that will fit into our
- // Hebrew conversion limits.
- //
- CheckTicksRange(ticks);
-
- DateTime time = new DateTime(ticks);
-
- //
- // Save the Gregorian date values.
- //
- gregorianYear = time.Year;
- gregorianMonth = time.Month;
- gregorianDay = time.Day;
-
- __DateBuffer lunarDate = new __DateBuffer(); // lunar month and day for Jan 1
-
- // From the table looking-up value of HebrewTable[index] (stored in lunarDate.day), we get the the
- // lunar month and lunar day where the Gregorian date 1/1 falls.
- lunarDate.year = gregorianYear + HebrewYearOf1AD;
- hebrewYearType = GetLunarMonthDay(gregorianYear, lunarDate);
-
- // This is the buffer used to store the result Hebrew date.
- __DateBuffer result = new __DateBuffer();
-
- //
- // Store the values for the start of the new year - 1/1.
- //
- result.year = lunarDate.year;
- result.month = lunarDate.month;
- result.day = lunarDate.day;
-
- //
- // Get the absolute date from 1/1/1600.
- //
- AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay);
-
- //
- // If the requested date was 1/1, then we're done.
- //
- if ((gregorianMonth == 1) && (gregorianDay == 1)) {
- return (GetResult(result, part));
- }
-
- //
- // Calculate the number of days between 1/1 and the requested date.
- //
- long NumDays; // number of days since 1/1
- NumDays = AbsoluteDate - GregorianCalendar.GetAbsoluteDate(gregorianYear, 1, 1);
-
- //
- // If the requested date is within the current lunar month, then
- // we're done.
- //
- if ((NumDays + (long)lunarDate.day) <= (long)(LunarMonthLen[hebrewYearType, lunarDate.month])) {
- result.day += (int)NumDays;
- return (GetResult(result, part));
- }
-
- //
- // Adjust for the current partial month.
- //
- result.month++;
- result.day = 1;
-
- //
- // Adjust the Lunar Month and Year (if necessary) based on the number
- // of days between 1/1 and the requested date.
- //
- // Assumes Jan 1 can never translate to the last Lunar month, which
- // is true.
- //
- NumDays -= (long)(LunarMonthLen[hebrewYearType, lunarDate.month] - lunarDate.day);
- Debug.Assert(NumDays >= 1, "NumDays >= 1");
-
- // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month
- // and day.
- if (NumDays > 1) {
- //
- // See if we're on the correct Lunar month.
- //
- while (NumDays > (long)(LunarMonthLen[hebrewYearType, result.month])) {
- //
- // Adjust the number of days and move to the next month.
- //
- NumDays -= (long)(LunarMonthLen[hebrewYearType, result.month++]);
-
- //
- // See if we need to adjust the Year.
- // Must handle both 12 and 13 month years.
- //
- if ((result.month > 13) || (LunarMonthLen[hebrewYearType, result.month] == 0)) {
- //
- // Adjust the Year.
- //
- result.year++;
- hebrewYearType = HebrewTable[(gregorianYear + 1 - FirstGregorianTableYear) * 2 + 1];
-
- //
- // Adjust the Month.
- //
- result.month = 1;
- }
- }
- //
- // Found the right Lunar month.
- //
- result.day += (int)(NumDays - 1);
- }
- return (GetResult(result, part));
- }
-
- // Returns the DateTime resulting from adding the given number of
- // months to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year and month parts of the specified DateTime by
- // value months, and, if required, adjusting the day part of the
- // resulting date downwards to the last day of the resulting month in the
- // resulting year. The time-of-day part of the result is the same as the
- // time-of-day part of the specified DateTime.
- //
- // In more precise terms, considering the specified DateTime to be of the
- // form y / m / d + t, where y is the
- // year, m is the month, d is the day, and t is the
- // time-of-day, the result is y1 / m1 / d1 + t,
- // where y1 and m1 are computed by adding value months
- // to y and m, and d1 is the largest value less than
- // or equal to d that denotes a valid day in month m1 of year
- // y1.
- //
-
- public override DateTime AddMonths(DateTime time, int months) {
- try {
- int y = GetDatePart(time.Ticks, DatePartYear);
- int m = GetDatePart(time.Ticks, DatePartMonth);
- int d = GetDatePart(time.Ticks, DatePartDay);
-
-
- int monthsInYear;
- int i;
- if (months >= 0) {
- i = m + months;
- while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra))) {
- y++;
- i -= monthsInYear;
- }
- } else {
- if ((i = m + months) <= 0) {
- months = -months;
- months -= m;
- y--;
-
- while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra))) {
- y--;
- months -= monthsInYear;
- }
- monthsInYear = GetMonthsInYear(y, CurrentEra);
- i = monthsInYear - months;
- }
- }
-
- int days = GetDaysInMonth(y, i);
- if (d > days) {
- d = days;
- }
- return (new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay)));
- }
- // We expect ArgumentException and ArgumentOutOfRangeException (which is subclass of ArgumentException)
- // If exception is thrown in the calls above, we are out of the supported range of this calendar.
- catch (ArgumentException)
- {
- throw new ArgumentOutOfRangeException(
- nameof(months),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_AddValue")));
- }
- }
-
- // Returns the DateTime resulting from adding the given number of
- // years to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year part of the specified DateTime by value
- // years. If the month and day of the specified DateTime is 2/29, and if the
- // resulting year is not a leap year, the month and day of the resulting
- // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
- // parts of the result are the same as those of the specified DateTime.
- //
-
- public override DateTime AddYears(DateTime time, int years) {
- int y = GetDatePart(time.Ticks, DatePartYear);
- int m = GetDatePart(time.Ticks, DatePartMonth);
- int d = GetDatePart(time.Ticks, DatePartDay);
-
- y += years;
- CheckHebrewYearValue(y, Calendar.CurrentEra, nameof(years));
-
- int months = GetMonthsInYear(y, CurrentEra);
- if (m > months) {
- m = months;
- }
-
- int days = GetDaysInMonth(y, m);
- if (d > days) {
- d = days;
- }
-
- long ticks = ToDateTime(y, m, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay);
- Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (new DateTime(ticks));
- }
-
- // Returns the day-of-month part of the specified DateTime. The returned
- // value is an integer between 1 and 31.
- //
-
- public override int GetDayOfMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDay));
- }
-
- // Returns the day-of-week part of the specified DateTime. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- // If we calculate back, the Hebrew day of week for Gregorian 0001/1/1 is Monday (1).
- // Therfore, the fomula is:
- return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
- }
-
- static internal int GetHebrewYearType(int year, int era) {
- CheckHebrewYearValue(year, era, nameof(year));
- // The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear.
- // So we need to convert year (Hebrew year value) to Gregorian Year below.
- return (HebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]);
- }
-
- // Returns the day-of-year part of the specified DateTime. The returned value
- // is an integer between 1 and 366.
- //
-
- public override int GetDayOfYear(DateTime time) {
- // Get Hebrew year value of the specified time.
- int year = GetYear(time);
- DateTime beginOfYearDate;
- if (year == 5343)
- {
- // Gregorian 1583/01/01 corresponds to Hebrew 5343/04/07 (MinSupportedDateTime)
- // To figure out the Gregorian date associated with Hebrew 5343/01/01, we need to
- // count the days from 5343/01/01 to 5343/04/07 and subtract that from Gregorian
- // 1583/01/01.
- // 1. Tishri (30 days)
- // 2. Heshvan (30 days since 5343 has 355 days)
- // 3. Kislev (30 days since 5343 has 355 days)
- // 96 days to get from 5343/01/01 to 5343/04/07
- // Gregorian 1583/01/01 - 96 days = 1582/9/27
-
- // the beginning of Hebrew year 5343 corresponds to Gregorian September 27, 1582.
- beginOfYearDate = new DateTime(1582, 9, 27);
- }
- else
- {
- // following line will fail when year is 5343 (first supported year)
- beginOfYearDate = ToDateTime(year, 1, 1, 0, 0, 0, 0, CurrentEra);
- }
- return ((int)((time.Ticks - beginOfYearDate.Ticks) / TicksPerDay) + 1);
- }
-
- // Returns the number of days in the month given by the year and
- // month arguments.
- //
-
- public override int GetDaysInMonth(int year, int month, int era) {
- CheckEraRange(era);
- int hebrewYearType = GetHebrewYearType(year, era);
- CheckHebrewMonthValue(year, month, era);
-
- Debug.Assert(hebrewYearType>= 1 && hebrewYearType <= 6,
- "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year);
- int monthDays = LunarMonthLen[hebrewYearType, month];
- if (monthDays == 0) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
- return (monthDays);
- }
-
- // Returns the number of days in the year given by the year argument for the current era.
- //
-
- public override int GetDaysInYear(int year, int era) {
- CheckEraRange(era);
- // normal years : 1 = 353 days 2 = 354 days 3 = 355 days.
- // Leap years : 4 = 383 5 384 6 = 385 days.
-
- // LunarYearType is from 1 to 6
- int LunarYearType = GetHebrewYearType(year, era);
- if (LunarYearType < 4) {
- // common year: LunarYearType = 1, 2, 3
- return (352 + LunarYearType);
- }
- return (382 + (LunarYearType - 3));
- }
-
- // Returns the era for the specified DateTime value.
-
- public override int GetEra(DateTime time) {
-
- return (HebrewEra);
- }
-
-
- public override int[] Eras {
- get {
- return (new int[] {HebrewEra});
- }
- }
-
- // Returns the month part of the specified DateTime. The returned value is an
- // integer between 1 and 12.
- //
-
- public override int GetMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartMonth));
- }
-
- // Returns the number of months in the specified year and era.
-
- public override int GetMonthsInYear(int year, int era) {
- return (IsLeapYear(year, era) ? 13 : 12);
- }
-
- // Returns the year part of the specified DateTime. The returned value is an
- // integer between 1 and 9999.
- //
-
- public override int GetYear(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartYear));
- }
-
- // Checks whether a given day in the specified era is a leap day. This method returns true if
- // the date is a leap day, or false if not.
- //
-
- public override bool IsLeapDay(int year, int month, int day, int era) {
- if (IsLeapMonth(year, month, era)) {
- // Every day in a leap month is a leap day.
- CheckHebrewDayValue(year, month, day, era);
- return (true);
- } else if (IsLeapYear(year, Calendar.CurrentEra)) {
- // There is an additional day in the 6th month in the leap year (the extra day is the 30th day in the 6th month),
- // so we should return true for 6/30 if that's in a leap year.
- if (month == 6 && day == 30) {
- return (true);
- }
- }
- CheckHebrewDayValue(year, month, day, era);
- return (false);
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
-
- public override int GetLeapMonth(int year, int era)
- {
- // Year/era values are checked in IsLeapYear().
- if (IsLeapYear(year, era))
- {
- // The 7th month in a leap year is a leap month.
- return (7);
- }
- return (0);
- }
-
- // Checks whether a given month in the specified era is a leap month. This method returns true if
- // month is a leap month, or false if not.
- //
-
- public override bool IsLeapMonth(int year, int month, int era) {
- // Year/era values are checked in IsLeapYear().
- bool isLeapYear = IsLeapYear(year, era);
- CheckHebrewMonthValue(year, month, era);
- // The 7th month in a leap year is a leap month.
- if (isLeapYear) {
- if (month == 7) {
- return (true);
- }
- }
- return (false);
- }
-
- // Checks whether a given year in the specified era is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
-
- public override bool IsLeapYear(int year, int era) {
- CheckHebrewYearValue(year, era, nameof(year));
- return (((7 * (long)year + 1) % 19) < 7);
- }
-
- // (month1, day1) - (month2, day2)
- static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2) {
- if (month1 == month2) {
- return (day1 - day2);
- }
-
- // Make sure that (month1, day1) < (month2, day2)
- bool swap = (month1 > month2);
- if (swap) {
- // (month1, day1) < (month2, day2). Swap the values.
- // The result will be a negative number.
- int tempMonth, tempDay;
- tempMonth = month1; tempDay = day1;
- month1 = month2; day1 = day2;
- month2 = tempMonth; day2 = tempDay;
- }
-
- // Get the number of days from (month1,day1) to (month1, end of month1)
- int days = LunarMonthLen[lunarYearType, month1] - day1;
-
- // Move to next month.
- month1++;
-
- // Add up the days.
- while (month1 < month2) {
- days += LunarMonthLen[lunarYearType, month1++];
- }
- days += day2;
-
- return (swap ? days : -days);
- }
-
- /*=================================HebrewToGregorian==========================
- **Action: Convert Hebrew date to Gregorian date.
- **Returns:
- **Arguments:
- **Exceptions:
- ** The algorithm is like this:
- ** The hebrew year has an offset to the Gregorian year, so we can guess the Gregorian year for
- ** the specified Hebrew year. That is, GreogrianYear = HebrewYear - FirstHebrewYearOf1AD.
- **
- ** From the Gregorian year and HebrewTable, we can get the Hebrew month/day value
- ** of the Gregorian date January 1st. Let's call this month/day value [hebrewDateForJan1]
- **
- ** If the requested Hebrew month/day is less than [hebrewDateForJan1], we know the result
- ** Gregorian date falls in previous year. So we decrease the Gregorian year value, and
- ** retrieve the Hebrew month/day value of the Gregorian date january 1st again.
- **
- ** Now, we get the answer of the Gregorian year.
- **
- ** The next step is to get the number of days between the requested Hebrew month/day
- ** and [hebrewDateForJan1]. When we get that, we can create the DateTime by adding/subtracting
- ** the ticks value of the number of days.
- **
- ============================================================================*/
-
-
- static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond) {
- // Get the rough Gregorian year for the specified hebrewYear.
- //
- int gregorianYear = hebrewYear - HebrewYearOf1AD;
-
- __DateBuffer hebrewDateOfJan1 = new __DateBuffer(); // year value is unused.
- int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1);
-
- if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day)) {
- return (new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond));
- }
-
- int days = GetDayDifference(lunarYearType, hebrewMonth, hebrewDay, hebrewDateOfJan1.month, hebrewDateOfJan1.day);
-
- DateTime gregorianNewYear = new DateTime(gregorianYear, 1, 1);
- return (new DateTime(gregorianNewYear.Ticks + days * TicksPerDay
- + TimeToTicks(hour, minute, second, millisecond)));
- }
-
- // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
- //
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- CheckHebrewYearValue(year, era, nameof(year));
- CheckHebrewMonthValue(year, month, era);
- CheckHebrewDayValue(year, month, day, era);
- DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond);
- CheckTicksRange(dt.Ticks);
- return (dt);
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 5790;
-
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value == 99)
- {
- // Do nothing here. Year 99 is allowed so that TwoDitYearMax is disabled.
- }
- else
- {
- CheckHebrewYearValue(value, HebrewEra, nameof(value));
- }
- twoDigitYearMax = value;
- }
- }
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- if (year < 100) {
- return (base.ToFourDigitYear(year));
- }
-
- if (year > MaxHebrewYear || year < MinHebrewYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MinHebrewYear,
- MaxHebrewYear));
- }
- return (year);
- }
-
- internal class __DateBuffer {
- internal int year;
- internal int month;
- internal int day;
- }
-
- }
-
-}
-
diff --git a/src/mscorlib/src/System/Globalization/HebrewNumber.cs b/src/mscorlib/src/System/Globalization/HebrewNumber.cs
deleted file mode 100644
index 5517cb14ea..0000000000
--- a/src/mscorlib/src/System/Globalization/HebrewNumber.cs
+++ /dev/null
@@ -1,403 +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.
-
-
-namespace System.Globalization {
- using System;
- using System.Text;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Used in HebrewNumber.ParseByChar to maintain the context information (
- // the state in the state machine and current Hebrew number values, etc.)
- // when parsing Hebrew number character by character.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal struct HebrewNumberParsingContext {
- // The current state of the state machine for parsing Hebrew numbers.
- internal HebrewNumber.HS state;
- // The current value of the Hebrew number.
- // The final value is determined when state is FoundEndOfHebrewNumber.
- internal int result;
-
- public HebrewNumberParsingContext(int result) {
- // Set the start state of the state machine for parsing Hebrew numbers.
- state = HebrewNumber.HS.Start;
- this.result = result;
- }
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Please see ParseByChar() for comments about different states defined here.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal enum HebrewNumberParsingState {
- InvalidHebrewNumber,
- NotHebrewDigit,
- FoundEndOfHebrewNumber,
- ContinueParsing,
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // class HebrewNumber
- //
- // Provides static methods for formatting integer values into
- // Hebrew text and parsing Hebrew number text.
- //
- // Limitations:
- // Parse can only handles value 1 ~ 999.
- // ToString() can only handles 1 ~ 999. If value is greater than 5000,
- // 5000 will be subtracted from the value.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal class HebrewNumber {
-
- // This class contains only static methods. Add a private ctor so that
- // compiler won't generate a default one for us.
- private HebrewNumber() {
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // ToString
- //
- // Converts the given number to Hebrew letters according to the numeric
- // value of each Hebrew letter. Basically, this converts the lunar year
- // and the lunar month to letters.
- //
- // The character of a year is described by three letters of the Hebrew
- // alphabet, the first and third giving, respectively, the days of the
- // weeks on which the New Year occurs and Passover begins, while the
- // second is the initial of the Hebrew word for defective, normal, or
- // complete.
- //
- // Defective Year : Both Heshvan and Kislev are defective (353 or 383 days)
- // Normal Year : Heshvan is defective, Kislev is full (354 or 384 days)
- // Complete Year : Both Heshvan and Kislev are full (355 or 385 days)
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal static String ToString(int Number) {
- char cTens = '\x0';
- char cUnits; // tens and units chars
- int Hundreds, Tens; // hundreds and tens values
- StringBuilder szHebrew = new StringBuilder();
-
-
- //
- // Adjust the number if greater than 5000.
- //
- if (Number > 5000) {
- Number -= 5000;
- }
-
- Debug.Assert(Number > 0 && Number <= 999, "Number is out of range.");;
-
- //
- // Get the Hundreds.
- //
- Hundreds = Number / 100;
-
- if (Hundreds > 0) {
- Number -= Hundreds * 100;
- // \x05e7 = 100
- // \x05e8 = 200
- // \x05e9 = 300
- // \x05ea = 400
- // If the number is greater than 400, use the multiples of 400.
- for (int i = 0; i < (Hundreds / 4) ; i++) {
- szHebrew.Append('\x05ea');
- }
-
- int remains = Hundreds % 4;
- if (remains > 0) {
- szHebrew.Append((char)((int)'\x05e6' + remains));
- }
- }
-
- //
- // Get the Tens.
- //
- Tens = Number / 10;
- Number %= 10;
-
- switch (Tens) {
- case ( 0 ) :
- cTens = '\x0';
- break;
- case ( 1 ) :
- cTens = '\x05d9'; // Hebrew Letter Yod
- break;
- case ( 2 ) :
- cTens = '\x05db'; // Hebrew Letter Kaf
- break;
- case ( 3 ) :
- cTens = '\x05dc'; // Hebrew Letter Lamed
- break;
- case ( 4 ) :
- cTens = '\x05de'; // Hebrew Letter Mem
- break;
- case ( 5 ) :
- cTens = '\x05e0'; // Hebrew Letter Nun
- break;
- case ( 6 ) :
- cTens = '\x05e1'; // Hebrew Letter Samekh
- break;
- case ( 7 ) :
- cTens = '\x05e2'; // Hebrew Letter Ayin
- break;
- case ( 8 ) :
- cTens = '\x05e4'; // Hebrew Letter Pe
- break;
- case ( 9 ) :
- cTens = '\x05e6'; // Hebrew Letter Tsadi
- break;
- }
-
- //
- // Get the Units.
- //
- cUnits = (char)(Number > 0 ? ((int)'\x05d0' + Number - 1) : 0);
-
- if ((cUnits == '\x05d4') && // Hebrew Letter He (5)
- (cTens == '\x05d9')) { // Hebrew Letter Yod (10)
- cUnits = '\x05d5'; // Hebrew Letter Vav (6)
- cTens = '\x05d8'; // Hebrew Letter Tet (9)
- }
-
- if ((cUnits == '\x05d5') && // Hebrew Letter Vav (6)
- (cTens == '\x05d9')) { // Hebrew Letter Yod (10)
- cUnits = '\x05d6'; // Hebrew Letter Zayin (7)
- cTens = '\x05d8'; // Hebrew Letter Tet (9)
- }
-
- //
- // Copy the appropriate info to the given buffer.
- //
-
- if (cTens != '\x0') {
- szHebrew.Append(cTens);
- }
-
- if (cUnits != '\x0') {
- szHebrew.Append(cUnits);
- }
-
- if (szHebrew.Length > 1) {
- szHebrew.Insert(szHebrew.Length - 1, '"');
- } else {
- szHebrew.Append('\'');
- }
-
- //
- // Return success.
- //
- return (szHebrew.ToString());
- }
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Token used to tokenize a Hebrew word into tokens so that we can use in the
- // state machine.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- enum HebrewToken {
- Invalid = -1,
- Digit400 = 0,
- Digit200_300 = 1,
- Digit100 = 2,
- Digit10 = 3, // 10 ~ 90
- Digit1 = 4, // 1, 2, 3, 4, 5, 8,
- Digit6_7 = 5,
- Digit7 = 6,
- Digit9 = 7,
- SingleQuote = 8,
- DoubleQuote = 9,
- };
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // This class is used to map a token into its Hebrew digit value.
- //
- ////////////////////////////////////////////////////////////////////////////
-
- class HebrewValue {
- internal HebrewToken token;
- internal int value;
- internal HebrewValue(HebrewToken token, int value) {
- this.token = token;
- this.value = value;
- }
- }
-
- //
- // Map a Hebrew character from U+05D0 ~ U+05EA to its digit value.
- // The value is -1 if the Hebrew character does not have a associated value.
- //
- static HebrewValue[] HebrewValues = {
- new HebrewValue(HebrewToken.Digit1, 1) , // '\x05d0
- new HebrewValue(HebrewToken.Digit1, 2) , // '\x05d1
- new HebrewValue(HebrewToken.Digit1, 3) , // '\x05d2
- new HebrewValue(HebrewToken.Digit1, 4) , // '\x05d3
- new HebrewValue(HebrewToken.Digit1, 5) , // '\x05d4
- new HebrewValue(HebrewToken.Digit6_7,6) , // '\x05d5
- new HebrewValue(HebrewToken.Digit6_7,7) , // '\x05d6
- new HebrewValue(HebrewToken.Digit1, 8) , // '\x05d7
- new HebrewValue(HebrewToken.Digit9, 9) , // '\x05d8
- new HebrewValue(HebrewToken.Digit10, 10) , // '\x05d9; // Hebrew Letter Yod
- new HebrewValue(HebrewToken.Invalid, -1) , // '\x05da;
- new HebrewValue(HebrewToken.Digit10, 20) , // '\x05db; // Hebrew Letter Kaf
- new HebrewValue(HebrewToken.Digit10, 30) , // '\x05dc; // Hebrew Letter Lamed
- new HebrewValue(HebrewToken.Invalid, -1) , // '\x05dd;
- new HebrewValue(HebrewToken.Digit10, 40) , // '\x05de; // Hebrew Letter Mem
- new HebrewValue(HebrewToken.Invalid, -1) , // '\x05df;
- new HebrewValue(HebrewToken.Digit10, 50) , // '\x05e0; // Hebrew Letter Nun
- new HebrewValue(HebrewToken.Digit10, 60) , // '\x05e1; // Hebrew Letter Samekh
- new HebrewValue(HebrewToken.Digit10, 70) , // '\x05e2; // Hebrew Letter Ayin
- new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e3;
- new HebrewValue(HebrewToken.Digit10, 80) , // '\x05e4; // Hebrew Letter Pe
- new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e5;
- new HebrewValue(HebrewToken.Digit10, 90) , // '\x05e6; // Hebrew Letter Tsadi
- new HebrewValue(HebrewToken.Digit100, 100) , // '\x05e7;
- new HebrewValue(HebrewToken.Digit200_300, 200) , // '\x05e8;
- new HebrewValue(HebrewToken.Digit200_300, 300) , // '\x05e9;
- new HebrewValue(HebrewToken.Digit400, 400) , // '\x05ea;
- };
-
- const int minHebrewNumberCh = 0x05d0;
- static char maxHebrewNumberCh = (char)(minHebrewNumberCh + HebrewValues.Length - 1);
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Hebrew number parsing State
- // The current state and the next token will lead to the next state in the state machine.
- // DQ = Double Quote
- //
- ////////////////////////////////////////////////////////////////////////////
-
- internal enum HS {
- _err = -1, // an error state
- Start = 0,
- S400 = 1, // a Hebrew digit 400
- S400_400 = 2, // Two Hebrew digit 400
- S400_X00 = 3, // Two Hebrew digit 400 and followed by 100
- S400_X0 = 4, // Hebrew digit 400 and followed by 10 ~ 90
- X00_DQ = 5, // A hundred number and followed by a double quote.
- S400_X00_X0 = 6,
- X0_DQ = 7, // A two-digit number and followed by a double quote.
- X = 8, // A single digit Hebrew number.
- X0 = 9, // A two-digit Hebrew number
- X00 = 10, // A three-digit Hebrew number
- S400_DQ = 11, // A Hebrew digit 400 and followed by a double quote.
- S400_400_DQ = 12,
- S400_400_100 = 13,
- S9 = 14, // Hebrew digit 9
- X00_S9 = 15, // A hundered number and followed by a digit 9
- S9_DQ = 16, // Hebrew digit 9 and followed by a double quote
- END = 100, // A terminial state is reached.
- }
-
- //
- // The state machine for Hebrew number pasing.
- //
- readonly static HS[][] NumberPasingState = {
- // 400 300/200 100 90~10 8~1 6, 7, 9, ' "
- /* 0 */ new HS[] {HS.S400, HS.X00, HS.X00, HS.X0, HS.X, HS.X, HS.X, HS.S9, HS._err, HS._err},
- /* 1: S400 */ new HS[] {HS.S400_400, HS.S400_X00, HS.S400_X00, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS.END, HS.S400_DQ},
- /* 2: S400_400 */ new HS[] {HS._err, HS._err, HS.S400_400_100,HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.S400_400_DQ},
- /* 3: S400_X00 */ new HS[] {HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.X00_DQ},
- /* 4: S400_X0 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ},
- /* 5: X00_DQ */ new HS[] {HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err},
- /* 6: S400_X00_X0 */new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ},
- /* 7: X0_DQ */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err},
- /* 8: X */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS._err},
- /* 9: X0 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.X0_DQ},
- /* 10: X00 */ new HS[] {HS._err, HS._err, HS._err, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.X00_DQ},
- /* 11: S400_DQ */ new HS[] {HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err},
- /* 12: S400_400_DQ*/new HS[] {HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err},
- /* 13: S400_400_100*/new HS[]{HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ},
- /* 14: S9 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err,HS.END, HS.S9_DQ},
- /* 15: X00_S9 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S9_DQ},
- /* 16: S9_DQ */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS._err, HS._err, HS._err},
- };
-
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Actions:
- // Parse the Hebrew number by passing one character at a time.
- // The state between characters are maintained at HebrewNumberPasingContext.
- // Returns:
- // Return a enum of HebrewNumberParsingState.
- // NotHebrewDigit: The specified ch is not a valid Hebrew digit.
- // InvalidHebrewNumber: After parsing the specified ch, it will lead into
- // an invalid Hebrew number text.
- // FoundEndOfHebrewNumber: A terminal state is reached. This means that
- // we find a valid Hebrew number text after the specified ch is parsed.
- // ContinueParsing: The specified ch is a valid Hebrew digit, and
- // it will lead into a valid state in the state machine, we should
- // continue to parse incoming characters.
- //
- ////////////////////////////////////////////////////////////////////////
-
- internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context) {
- HebrewToken token;
- if (ch == '\'') {
- token = HebrewToken.SingleQuote;
- } else if (ch == '\"') {
- token = HebrewToken.DoubleQuote;
- } else {
- int index = (int)ch - minHebrewNumberCh;
- if (index >= 0 && index < HebrewValues.Length ) {
- token = HebrewValues[index].token;
- if (token == HebrewToken.Invalid) {
- return (HebrewNumberParsingState.NotHebrewDigit);
- }
- context.result += HebrewValues[index].value;
- } else {
- // Not in valid Hebrew digit range.
- return (HebrewNumberParsingState.NotHebrewDigit);
- }
- }
- context.state = NumberPasingState[(int)context.state][(int)token];
- if (context.state == HS._err) {
- // Invalid Hebrew state. This indicates an incorrect Hebrew number.
- return (HebrewNumberParsingState.InvalidHebrewNumber);
- }
- if (context.state == HS.END) {
- // Reach a terminal state.
- return (HebrewNumberParsingState.FoundEndOfHebrewNumber);
- }
- // We should continue to parse.
- return (HebrewNumberParsingState.ContinueParsing);
- }
-
- ////////////////////////////////////////////////////////////////////////
- //
- // Actions:
- // Check if the ch is a valid Hebrew number digit.
- // This function will return true if the specified char is a legal Hebrew
- // digit character, single quote, or double quote.
- // Returns:
- // true if the specified character is a valid Hebrew number character.
- //
- ////////////////////////////////////////////////////////////////////////
-
- internal static bool IsDigit(char ch) {
- if (ch >= minHebrewNumberCh && ch <= maxHebrewNumberCh) {
- return (HebrewValues[ch - minHebrewNumberCh].value >= 0);
- }
- return (ch == '\'' || ch == '\"');
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallerFilePathAttribute.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs
index 330934cf95..a6e8f73d3e 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CallerFilePathAttribute.cs
+++ b/src/mscorlib/src/System/Globalization/HijriCalendar.Unix.cs
@@ -2,16 +2,14 @@
// 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.Runtime.CompilerServices
+namespace System.Globalization
{
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- public sealed class CallerFilePathAttribute : Attribute
+ public partial class HijriCalendar : Calendar
{
- public CallerFilePathAttribute()
+ private static int GetHijriDateAdjustment()
{
+ // this setting is not supported on Unix, so always return 0
+ return 0;
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs
new file mode 100644
index 0000000000..4ba95c8fa8
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/HijriCalendar.Win32.cs
@@ -0,0 +1,83 @@
+// 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;
+
+namespace System.Globalization
+{
+ public partial class HijriCalendar : Calendar
+ {
+ private int GetHijriDateAdjustment()
+ {
+ if (_hijriAdvance == Int32.MinValue)
+ {
+ // Never been set before. Use the system value from registry.
+ _hijriAdvance = GetAdvanceHijriDate();
+ }
+ return (_hijriAdvance);
+ }
+
+ private const String InternationalRegKey = "Control Panel\\International";
+ private const String HijriAdvanceRegKeyEntry = "AddHijriDate";
+
+ /*=================================GetAdvanceHijriDate==========================
+ **Action: Gets the AddHijriDate value from the registry.
+ **Returns:
+ **Arguments: None.
+ **Exceptions:
+ **Note:
+ ** The HijriCalendar has a user-overidable calculation. That is, use can set a value from the control
+ ** panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days.
+ **
+ ** The valid string values in the registry are:
+ ** "AddHijriDate-2" => Add -2 days to the current calculated Hijri date.
+ ** "AddHijriDate" => Add -1 day to the current calculated Hijri date.
+ ** "" => Add 0 day to the current calculated Hijri date.
+ ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date.
+ ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date.
+ ============================================================================*/
+ private static int GetAdvanceHijriDate()
+ {
+ int hijriAdvance = 0;
+ Microsoft.Win32.RegistryKey key = null;
+
+ using (key = Registry.CurrentUser.OpenSubKey(InternationalRegKey, writable: false))
+ {
+ if (key == null)
+ return 0;
+
+ Object value = key.GetValue(HijriAdvanceRegKeyEntry);
+ if (value == null)
+ {
+ return (0);
+ }
+ String str = value.ToString();
+ if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0)
+ {
+ if (str.Length == HijriAdvanceRegKeyEntry.Length)
+ hijriAdvance = -1;
+ else
+ {
+ str = str.Substring(HijriAdvanceRegKeyEntry.Length);
+ try
+ {
+ int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
+ if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri))
+ {
+ hijriAdvance = advance;
+ }
+ }
+ // If we got garbage from registry just ignore it.
+ // hijriAdvance = 0 because of declaraction assignment up above.
+ catch (ArgumentException) { }
+ catch (FormatException) { }
+ catch (OverflowException) { }
+ }
+ }
+ }
+
+ return (hijriAdvance);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs
index 9c87e8e25f..fb91c27ef6 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs
+++ b/src/mscorlib/src/System/Globalization/HijriCalendar.WinRT.cs
@@ -2,16 +2,15 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using Internal.Runtime.Augments;
-using System;
-
-namespace System.Runtime.CompilerServices
+namespace System.Globalization
{
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- public sealed class CallerLineNumberAttribute : Attribute
+ public partial class HijriCalendar : Calendar
{
- public CallerLineNumberAttribute()
+ private static int GetHijriDateAdjustment()
{
+ return WinRTInterop.Callbacks.GetHijriDateAdjustment();
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/HijriCalendar.cs b/src/mscorlib/src/System/Globalization/HijriCalendar.cs
deleted file mode 100644
index 061d380285..0000000000
--- a/src/mscorlib/src/System/Globalization/HijriCalendar.cs
+++ /dev/null
@@ -1,716 +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.
-
-namespace System.Globalization {
-
- using System;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-#if !FEATURE_WIN32_REGISTRY
- using System.Text;
- using Microsoft.Win32;
-#endif // FEATURE_WIN32_REGISTRY
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Rules for the Hijri calendar:
- // - The Hijri calendar is a strictly Lunar calendar.
- // - Days begin at sunset.
- // - Islamic Year 1 (Muharram 1, 1 A.H.) is equivalent to absolute date
- // 227015 (Friday, July 16, 622 C.E. - Julian).
- // - Leap Years occur in the 2, 5, 7, 10, 13, 16, 18, 21, 24, 26, & 29th
- // years of a 30-year cycle. Year = leap iff ((11y+14) mod 30 < 11).
- // - There are 12 months which contain alternately 30 and 29 days.
- // - The 12th month, Dhu al-Hijjah, contains 30 days instead of 29 days
- // in a leap year.
- // - Common years have 354 days. Leap years have 355 days.
- // - There are 10,631 days in a 30-year cycle.
- // - The Islamic months are:
- // 1. Muharram (30 days) 7. Rajab (30 days)
- // 2. Safar (29 days) 8. Sha'ban (29 days)
- // 3. Rabi I (30 days) 9. Ramadan (30 days)
- // 4. Rabi II (29 days) 10. Shawwal (29 days)
- // 5. Jumada I (30 days) 11. Dhu al-Qada (30 days)
- // 6. Jumada II (29 days) 12. Dhu al-Hijjah (29 days) {30}
- //
- // NOTENOTE
- // The calculation of the HijriCalendar is based on the absolute date. And the
- // absolute date means the number of days from January 1st, 1 A.D.
- // Therefore, we do not support the days before the January 1st, 1 A.D.
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 0622/07/18 9999/12/31
- ** Hijri 0001/01/01 9666/04/03
- */
-
- [Serializable]
- public class HijriCalendar : Calendar {
-
-
- public static readonly int HijriEra = 1;
-
- internal const int DatePartYear = 0;
- internal const int DatePartDayOfYear = 1;
- internal const int DatePartMonth = 2;
- internal const int DatePartDay = 3;
-
- internal const int MinAdvancedHijri = -2;
- internal const int MaxAdvancedHijri = 2;
-
- internal static readonly int[] HijriMonthDays = {0,30,59,89,118,148,177,207,236,266,295,325,355};
-
- //internal static Calendar m_defaultInstance;
-
-#if FEATURE_WIN32_REGISTRY
- private const String InternationalRegKey = "Control Panel\\International";
- private const String HijriAdvanceRegKeyEntry = "AddHijriDate";
-#endif
-
- private int m_HijriAdvance = Int32.MinValue;
-
- // DateTime.MaxValue = Hijri calendar (year:9666, month: 4, day: 3).
- internal const int MaxCalendarYear = 9666;
- internal const int MaxCalendarMonth = 4;
- internal const int MaxCalendarDay = 3;
- // Hijri calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 7, day: 18)
- // This is the minimal Gregorian date that we support in the HijriCalendar.
- internal static readonly DateTime calendarMinValue = new DateTime(622, 7, 18);
- internal static readonly DateTime calendarMaxValue = DateTime.MaxValue;
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (calendarMinValue);
- }
- }
-
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (calendarMaxValue);
- }
- }
-
- // Return the type of the Hijri calendar.
- //
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.LunarCalendar;
- }
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of HijriCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance() {
- if (m_defaultInstance == null) {
- m_defaultInstance = new HijriCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
- // Construct an instance of Hijri calendar.
-
- public HijriCalendar() {
- }
-
- internal override int ID {
- get {
- return (CAL_HIJRI);
- }
- }
-
- protected override int DaysInYearBeforeMinSupportedYear
- {
- get
- {
- // the year before the 1st year of the cycle would have been the 30th year
- // of the previous cycle which is not a leap year. Common years have 354 days.
- return 354;
- }
- }
-
-
-
- /*=================================GetAbsoluteDateHijri==========================
- **Action: Gets the Absolute date for the given Hijri date. The absolute date means
- ** the number of days from January 1st, 1 A.D.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
-
- long GetAbsoluteDateHijri(int y, int m, int d) {
- return (long)(DaysUpToHijriYear(y) + HijriMonthDays[m-1] + d - 1 - HijriAdjustment);
- }
-
- /*=================================DaysUpToHijriYear==========================
- **Action: Gets the total number of days (absolute date) up to the given Hijri Year.
- ** The absolute date means the number of days from January 1st, 1 A.D.
- **Returns: Gets the total number of days (absolute date) up to the given Hijri Year.
- **Arguments: HijriYear year value in Hijri calendar.
- **Exceptions: None
- **Notes:
- ============================================================================*/
-
- long DaysUpToHijriYear(int HijriYear) {
- long NumDays; // number of absolute days
- int NumYear30; // number of years up to current 30 year cycle
- int NumYearsLeft; // number of years into 30 year cycle
-
- //
- // Compute the number of years up to the current 30 year cycle.
- //
- NumYear30 = ((HijriYear - 1) / 30) * 30;
-
- //
- // Compute the number of years left. This is the number of years
- // into the 30 year cycle for the given year.
- //
- NumYearsLeft = HijriYear - NumYear30 - 1;
-
- //
- // Compute the number of absolute days up to the given year.
- //
- NumDays = ((NumYear30 * 10631L) / 30L) + 227013L;
- while (NumYearsLeft > 0) {
- // Common year is 354 days, and leap year is 355 days.
- NumDays += 354 + (IsLeapYear(NumYearsLeft, CurrentEra) ? 1: 0);
- NumYearsLeft--;
- }
-
- //
- // Return the number of absolute days.
- //
- return (NumDays);
- }
-
-
- public int HijriAdjustment {
- get {
- if (m_HijriAdvance == Int32.MinValue) {
- // Never been set before. Use the system value from registry.
- m_HijriAdvance = GetAdvanceHijriDate();
- }
- return (m_HijriAdvance);
- }
-
- set {
- // NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
- if (value < MinAdvancedHijri || value > MaxAdvancedHijri) {
- throw new ArgumentOutOfRangeException(
- nameof(HijriAdjustment),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
- MinAdvancedHijri,
- MaxAdvancedHijri));
- }
- Contract.EndContractBlock();
- VerifyWritable();
-
- m_HijriAdvance = value;
- }
- }
-
- /*=================================GetAdvanceHijriDate==========================
- **Action: Gets the AddHijriDate value from the registry.
- **Returns:
- **Arguments: None.
- **Exceptions:
- **Note:
- ** The HijriCalendar has a user-overidable calculation. That is, use can set a value from the control
- ** panel, so that the calculation of the Hijri Calendar can move ahead or backwards from -2 to +2 days.
- **
- ** The valid string values in the registry are:
- ** "AddHijriDate-2" => Add -2 days to the current calculated Hijri date.
- ** "AddHijriDate" => Add -1 day to the current calculated Hijri date.
- ** "" => Add 0 day to the current calculated Hijri date.
- ** "AddHijriDate+1" => Add +1 days to the current calculated Hijri date.
- ** "AddHijriDate+2" => Add +2 days to the current calculated Hijri date.
- ============================================================================*/
- static int GetAdvanceHijriDate() {
-#if FEATURE_WIN32_REGISTRY
-
- int hijriAdvance = 0;
- Microsoft.Win32.RegistryKey key = null;
-
- try {
- // Open in read-only mode.
- // Use InternalOpenSubKey so that we avoid the security check.
- key = Microsoft.Win32.Registry.CurrentUser.InternalOpenSubKey(InternationalRegKey, false);
- }
- //If this fails for any reason, we'll just return 0.
- catch (ObjectDisposedException) { return 0; }
- catch (ArgumentException) { return 0; }
-
- if (key != null) {
- try {
- Object value = key.InternalGetValue(HijriAdvanceRegKeyEntry, null, false, false);
- if (value == null) {
- return (0);
- }
- String str = value.ToString();
- if (String.Compare(str, 0, HijriAdvanceRegKeyEntry, 0, HijriAdvanceRegKeyEntry.Length, StringComparison.OrdinalIgnoreCase) == 0) {
- if (str.Length == HijriAdvanceRegKeyEntry.Length)
- hijriAdvance = -1;
- else {
- str = str.Substring(HijriAdvanceRegKeyEntry.Length);
- try {
- int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
- if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri)) {
- hijriAdvance = advance;
- }
- }
- // If we got garbage from registry just ignore it.
- // hijriAdvance = 0 because of declaraction assignment up above.
- catch (ArgumentException) { }
- catch (FormatException) { }
- catch (OverflowException) { }
- }
- }
- }
- finally {
- key.Close();
- }
-
- }
- return (hijriAdvance);
-
-#else //FEATURE_WIN32_REGISTRY
- return 0;
-#endif // FEATURE_WIN32_REGISTRY
- }
-
- static internal void CheckTicksRange(long ticks) {
- if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) {
- throw new ArgumentOutOfRangeException(
- "time",
- String.Format(
- CultureInfo.InvariantCulture,
- Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
- calendarMinValue,
- calendarMaxValue));
- }
- }
-
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != HijriEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
- }
-
- static internal void CheckYearRange(int year, int era) {
- CheckEraRange(era);
- if (year < 1 || year > MaxCalendarYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxCalendarYear));
- }
- }
-
- static internal void CheckYearMonthRange(int year, int month, int era) {
- CheckYearRange(year, era);
- if (year == MaxCalendarYear) {
- if (month > MaxCalendarMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(month),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxCalendarMonth));
- }
- }
-
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
- }
-
- /*=================================GetDatePart==========================
- **Action: Returns a given date part of this <i>DateTime</i>. This method is used
- ** to compute the year, day-of-year, month, or day part.
- **Returns:
- **Arguments:
- **Exceptions: ArgumentException if part is incorrect.
- **Notes:
- ** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
- ** Use the formula (((AbsoluteDate - 227013) * 30) / 10631) + 1, we can a rough value for the Hijri year.
- ** In order to get the exact Hijri year, we compare the exact absolute date for HijriYear and (HijriYear + 1).
- ** From here, we can get the correct Hijri year.
- ============================================================================*/
-
- internal virtual int GetDatePart(long ticks, int part) {
- int HijriYear; // Hijri year
- int HijriMonth; // Hijri month
- int HijriDay; // Hijri day
- long NumDays; // The calculation buffer in number of days.
-
- CheckTicksRange(ticks);
-
- //
- // Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
- // 1/1/0001 is absolute date 1.
- //
- NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
-
- //
- // See how much we need to backup or advance
- //
- NumDays += HijriAdjustment;
-
- //
- // Calculate the appromixate Hijri Year from this magic formula.
- //
- HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
-
- long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear
- long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
-
- if (NumDays < daysToHijriYear) {
- daysToHijriYear -= daysOfHijriYear;
- HijriYear--;
- } else if (NumDays == daysToHijriYear) {
- HijriYear--;
- daysToHijriYear -= GetDaysInYear(HijriYear, CurrentEra);
- } else {
- if (NumDays > daysToHijriYear + daysOfHijriYear) {
- daysToHijriYear += daysOfHijriYear;
- HijriYear++;
- }
- }
- if (part == DatePartYear) {
- return (HijriYear);
- }
-
- //
- // Calculate the Hijri Month.
- //
-
- HijriMonth = 1;
- NumDays -= daysToHijriYear;
-
- if (part == DatePartDayOfYear) {
- return ((int)NumDays);
- }
-
- while ((HijriMonth <= 12) && (NumDays > HijriMonthDays[HijriMonth - 1])) {
- HijriMonth++;
- }
- HijriMonth--;
-
- if (part == DatePartMonth) {
- return (HijriMonth);
- }
-
- //
- // Calculate the Hijri Day.
- //
- HijriDay = (int)(NumDays - HijriMonthDays[HijriMonth - 1]);
-
- if (part == DatePartDay) {
- return (HijriDay);
- }
- // Incorrect part value.
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DateTimeParsing"));
- }
-
- // Returns the DateTime resulting from adding the given number of
- // months to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year and month parts of the specified DateTime by
- // value months, and, if required, adjusting the day part of the
- // resulting date downwards to the last day of the resulting month in the
- // resulting year. The time-of-day part of the result is the same as the
- // time-of-day part of the specified DateTime.
- //
- // In more precise terms, considering the specified DateTime to be of the
- // form y / m / d + t, where y is the
- // year, m is the month, d is the day, and t is the
- // time-of-day, the result is y1 / m1 / d1 + t,
- // where y1 and m1 are computed by adding value months
- // to y and m, and d1 is the largest value less than
- // or equal to d that denotes a valid day in month m1 of year
- // y1.
- //
-
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
- throw new ArgumentOutOfRangeException(
- nameof(months),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- -120000,
- 120000));
- }
- Contract.EndContractBlock();
- // Get the date in Hijri calendar.
- int y = GetDatePart(time.Ticks, DatePartYear);
- int m = GetDatePart(time.Ticks, DatePartMonth);
- int d = GetDatePart(time.Ticks, DatePartDay);
- int i = m - 1 + months;
- if (i >= 0) {
- m = i % 12 + 1;
- y = y + i / 12;
- } else {
- m = 12 + (i + 1) % 12;
- y = y + (i - 11) / 12;
- }
- int days = GetDaysInMonth(y, m);
- if (d > days) {
- d = days;
- }
- long ticks = GetAbsoluteDateHijri(y, m, d)* TicksPerDay + (time.Ticks % TicksPerDay);
- Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (new DateTime(ticks));
- }
-
- // Returns the DateTime resulting from adding the given number of
- // years to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year part of the specified DateTime by value
- // years. If the month and day of the specified DateTime is 2/29, and if the
- // resulting year is not a leap year, the month and day of the resulting
- // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
- // parts of the result are the same as those of the specified DateTime.
- //
-
- public override DateTime AddYears(DateTime time, int years) {
- return (AddMonths(time, years * 12));
- }
-
- // Returns the day-of-month part of the specified DateTime. The returned
- // value is an integer between 1 and 31.
- //
-
- public override int GetDayOfMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDay));
- }
-
- // Returns the day-of-week part of the specified DateTime. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
- }
-
- // Returns the day-of-year part of the specified DateTime. The returned value
- // is an integer between 1 and 366.
- //
-
- public override int GetDayOfYear(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDayOfYear));
- }
-
- // Returns the number of days in the month given by the year and
- // month arguments.
- //
- [Pure]
- public override int GetDaysInMonth(int year, int month, int era) {
- CheckYearMonthRange(year, month, era);
- if (month == 12) {
- // For the 12th month, leap year has 30 days, and common year has 29 days.
- return (IsLeapYear(year, CurrentEra) ? 30 : 29);
- }
- // Other months contain 30 and 29 days alternatively. The 1st month has 30 days.
- return (((month % 2) == 1) ? 30 : 29);
- }
-
- // Returns the number of days in the year given by the year argument for the current era.
- //
-
- public override int GetDaysInYear(int year, int era) {
- CheckYearRange(year, era);
- // Common years have 354 days. Leap years have 355 days.
- return (IsLeapYear(year, CurrentEra) ? 355: 354);
- }
-
- // Returns the era for the specified DateTime value.
-
- public override int GetEra(DateTime time) {
- CheckTicksRange(time.Ticks);
- return (HijriEra);
- }
-
-
- public override int[] Eras {
- get {
- return (new int[] {HijriEra});
- }
- }
-
- // Returns the month part of the specified DateTime. The returned value is an
- // integer between 1 and 12.
- //
-
- public override int GetMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartMonth));
- }
-
- // Returns the number of months in the specified year and era.
-
- public override int GetMonthsInYear(int year, int era) {
- CheckYearRange(year, era);
- return (12);
- }
-
- // Returns the year part of the specified DateTime. The returned value is an
- // integer between 1 and MaxCalendarYear.
- //
-
- public override int GetYear(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartYear));
- }
-
- // Checks whether a given day in the specified era is a leap day. This method returns true if
- // the date is a leap day, or false if not.
- //
-
- public override bool IsLeapDay(int year, int month, int day, int era) {
- // The year/month/era value checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Day"),
- daysInMonth,
- month));
- }
- return (IsLeapYear(year, era) && month == 12 && day == 30);
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era)
- {
- CheckYearRange(year, era);
- return (0);
- }
-
- // Checks whether a given month in the specified era is a leap month. This method returns true if
- // month is a leap month, or false if not.
- //
-
- public override bool IsLeapMonth(int year, int month, int era) {
- CheckYearMonthRange(year, month, era);
- return (false);
- }
-
- // Checks whether a given year in the specified era is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
-
- public override bool IsLeapYear(int year, int era) {
- CheckYearRange(year, era);
- return ((((year * 11) + 14) % 30) < 11);
- }
-
- // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
- //
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- // The year/month/era checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
- BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Day"),
- daysInMonth,
- month));
- }
-
- long lDate = GetAbsoluteDateHijri(year, month, day);
-
- if (lDate >= 0) {
- return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
- } else {
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
-
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > MaxCalendarYear)
- {
- throw new ArgumentOutOfRangeException(
- nameof(value),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- MaxCalendarYear));
-
- }
- twoDigitYearMax = value;
- }
- }
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- if (year < 100) {
- return (base.ToFourDigitYear(year));
- }
-
- if (year > MaxCalendarYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxCalendarYear));
- }
- return (year);
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs b/src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs
new file mode 100644
index 0000000000..f1ad6f1d0a
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/IdnMapping.Unix.cs
@@ -0,0 +1,142 @@
+// 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.Globalization
+{
+ sealed partial class IdnMapping
+ {
+ private unsafe string GetAsciiCore(char* unicode, int count)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ uint flags = Flags;
+ CheckInvalidIdnCharacters(unicode, count, flags, nameof(unicode));
+
+ const int StackallocThreshold = 512;
+ // Each unicode character is represented by up to 3 ASCII chars
+ // and the whole string is prefixed by "xn--" (length 4)
+ int estimatedLength = (int)Math.Min(count * 3L + 4, StackallocThreshold);
+ int actualLength;
+ if (estimatedLength < StackallocThreshold)
+ {
+ char* outputStack = stackalloc char[estimatedLength];
+ actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, outputStack, estimatedLength);
+ if (actualLength > 0 && actualLength <= estimatedLength)
+ {
+ return new string(outputStack, 0, actualLength);
+ }
+ }
+ else
+ {
+ actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, null, 0);
+ }
+ if (actualLength == 0)
+ {
+ throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(unicode));
+ }
+
+ char[] outputHeap = new char[actualLength];
+ fixed (char* pOutputHeap = outputHeap)
+ {
+ actualLength = Interop.GlobalizationInterop.ToAscii(flags, unicode, count, pOutputHeap, actualLength);
+ if (actualLength == 0 || actualLength > outputHeap.Length)
+ {
+ throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(unicode));
+ }
+ return new string(pOutputHeap, 0, actualLength);
+ }
+ }
+
+ private unsafe string GetUnicodeCore(char* ascii, int count)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ uint flags = Flags;
+ CheckInvalidIdnCharacters(ascii, count, flags, nameof(ascii));
+
+ const int StackAllocThreshold = 512;
+ if (count < StackAllocThreshold)
+ {
+ char* output = stackalloc char[count];
+ return GetUnicodeCore(ascii, count, flags, output, count, reattempt: true);
+ }
+ else
+ {
+ char[] output = new char[count];
+ fixed (char* pOutput = output)
+ {
+ return GetUnicodeCore(ascii, count, flags, pOutput, count, reattempt: true);
+ }
+ }
+ }
+
+ private unsafe string GetUnicodeCore(char* ascii, int count, uint flags, char* output, int outputLength, bool reattempt)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ int realLen = Interop.GlobalizationInterop.ToUnicode(flags, ascii, count, output, outputLength);
+
+ if (realLen == 0)
+ {
+ throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii));
+ }
+ else if (realLen <= outputLength)
+ {
+ return new string(output, 0, realLen);
+ }
+ else if (reattempt)
+ {
+ char[] newOutput = new char[realLen];
+ fixed (char* pNewOutput = newOutput)
+ {
+ return GetUnicodeCore(ascii, count, flags, pNewOutput, realLen, reattempt: false);
+ }
+ }
+
+ throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii));
+ }
+
+ // -----------------------------
+ // ---- PAL layer ends here ----
+ // -----------------------------
+
+ private uint Flags
+ {
+ get
+ {
+ int flags =
+ (AllowUnassigned ? Interop.GlobalizationInterop.AllowUnassigned : 0) |
+ (UseStd3AsciiRules ? Interop.GlobalizationInterop.UseStd3AsciiRules : 0);
+ return (uint)flags;
+ }
+ }
+
+ /// <summary>
+ /// ICU doesn't check for invalid characters unless the STD3 rules option
+ /// is enabled.
+ ///
+ /// To match Windows behavior, we walk the string ourselves looking for these
+ /// bad characters so we can continue to throw ArgumentException in these cases.
+ /// </summary>
+ private static unsafe void CheckInvalidIdnCharacters(char* s, int count, uint flags, string paramName)
+ {
+ if ((flags & Interop.GlobalizationInterop.UseStd3AsciiRules) == 0)
+ {
+ for (int i = 0; i < count; i++)
+ {
+ char c = s[i];
+
+ // These characters are prohibited regardless of the UseStd3AsciiRules property.
+ // See https://msdn.microsoft.com/en-us/library/system.globalization.idnmapping.usestd3asciirules(v=vs.110).aspx
+ if (c <= 0x1F || c == 0x7F)
+ {
+ throw new ArgumentException(SR.Argument_IdnIllegalName, paramName);
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.Windows.cs b/src/mscorlib/src/System/Globalization/IdnMapping.Windows.cs
new file mode 100644
index 0000000000..d3f05bb164
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/IdnMapping.Windows.cs
@@ -0,0 +1,121 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace System.Globalization
+{
+ public sealed partial class IdnMapping
+ {
+ private unsafe string GetAsciiCore(char* unicode, int count)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ uint flags = Flags;
+
+ // Determine the required length
+ int length = Interop.Normaliz.IdnToAscii(flags, new IntPtr(unicode), count, IntPtr.Zero, 0);
+ if (length == 0)
+ {
+ ThrowForZeroLength(nameof(unicode), SR.Argument_IdnIllegalName, SR.Argument_InvalidCharSequenceNoIndex);
+ }
+
+ // Do the conversion
+ const int StackAllocThreshold = 512; // arbitrary limit to switch from stack to heap allocation
+ if (length < StackAllocThreshold)
+ {
+ char* output = stackalloc char[length];
+ return GetAsciiCore(unicode, count, flags, output, length);
+ }
+ else
+ {
+ char[] output = new char[length];
+ fixed (char* pOutput = output)
+ {
+ return GetAsciiCore(unicode, count, flags, pOutput, length);
+ }
+ }
+ }
+
+ private unsafe string GetAsciiCore(char* unicode, int count, uint flags, char* output, int outputLength)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ int length = Interop.Normaliz.IdnToAscii(flags, new IntPtr(unicode), count, new IntPtr(output), outputLength);
+ if (length == 0)
+ {
+ ThrowForZeroLength(nameof(unicode), SR.Argument_IdnIllegalName, SR.Argument_InvalidCharSequenceNoIndex);
+ }
+ Debug.Assert(length == outputLength);
+ return new string(output, 0, length);
+ }
+
+ private unsafe string GetUnicodeCore(char* ascii, int count)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ uint flags = Flags;
+
+ // Determine the required length
+ int length = Interop.Normaliz.IdnToUnicode(flags, new IntPtr(ascii), count, IntPtr.Zero, 0);
+ if (length == 0)
+ {
+ ThrowForZeroLength(nameof(ascii), SR.Argument_IdnIllegalName, SR.Argument_IdnBadPunycode);
+ }
+
+ // Do the conversion
+ const int StackAllocThreshold = 512; // arbitrary limit to switch from stack to heap allocation
+ if (length < StackAllocThreshold)
+ {
+ char* output = stackalloc char[length];
+ return GetUnicodeCore(ascii, count, flags, output, length);
+ }
+ else
+ {
+ char[] output = new char[length];
+ fixed (char* pOutput = output)
+ {
+ return GetUnicodeCore(ascii, count, flags, pOutput, length);
+ }
+ }
+ }
+
+ private unsafe string GetUnicodeCore(char* ascii, int count, uint flags, char* output, int outputLength)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ int length = Interop.Normaliz.IdnToUnicode(flags, new IntPtr(ascii), count, new IntPtr(output), outputLength);
+ if (length == 0)
+ {
+ ThrowForZeroLength(nameof(ascii), SR.Argument_IdnIllegalName, SR.Argument_IdnBadPunycode);
+ }
+ Debug.Assert(length == outputLength);
+ return new string(output, 0, length);
+ }
+
+ // -----------------------------
+ // ---- PAL layer ends here ----
+ // -----------------------------
+
+ private uint Flags
+ {
+ get
+ {
+ int flags =
+ (AllowUnassigned ? Interop.Normaliz.IDN_ALLOW_UNASSIGNED : 0) |
+ (UseStd3AsciiRules ? Interop.Normaliz.IDN_USE_STD3_ASCII_RULES : 0);
+ return (uint)flags;
+ }
+ }
+
+ private static void ThrowForZeroLength(string paramName, string invalidNameString, string otherString)
+ {
+ throw new ArgumentException(
+ Marshal.GetLastWin32Error() == Interop.Normaliz.ERROR_INVALID_NAME ? invalidNameString : otherString,
+ paramName);
+ }
+ }
+}
+
diff --git a/src/mscorlib/src/System/Globalization/IdnMapping.cs b/src/mscorlib/src/System/Globalization/IdnMapping.cs
index bf75f5be3c..4320e3abf5 100644
--- a/src/mscorlib/src/System/Globalization/IdnMapping.cs
+++ b/src/mscorlib/src/System/Globalization/IdnMapping.cs
@@ -2,7 +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.
-//
// This file contains the IDN functions and implementation.
//
// This allows encoding of non-ASCII domain names in a "punycode" form,
@@ -24,69 +23,18 @@
// RFC 3490 - Internationalizing Domain Names in Applications (IDNA)
// RFC 3491 - Nameprep: A Stringprep Profile for Internationalized Domain Names (IDN)
// RFC 3492 - Punycode: A Bootstring encoding of Unicode for Internationalized Domain Names in Applications (IDNA)
-//
-/*
-
-The punycode implementation is based on the sample code in RFC 3492
-
-Copyright (C) The Internet Society (2003). All Rights Reserved.
-
-This document and translations of it may be copied and furnished to
-others, and derivative works that comment on or otherwise explain it
-or assist in its implementation may be prepared, copied, published
-and distributed, in whole or in part, without restriction of any
-kind, provided that the above copyright notice and this paragraph are
-included on all such copies and derivative works. However, this
-document itself may not be modified in any way, such as by removing
-the copyright notice or references to the Internet Society or other
-Internet organizations, except as needed for the purpose of
-developing Internet standards in which case the procedures for
-copyrights defined in the Internet Standards process must be
-followed, or as required to translate it into languages other than
-English.
-
-The limited permissions granted above are perpetual and will not be
-revoked by the Internet Society or its successors or assigns.
-
-This document and the information contained herein is provided on an
-"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
-TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
-BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
-HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
-MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
-*/
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Text;
namespace System.Globalization
{
- using System;
- using System.Security;
- using System.Globalization;
- using System.Text;
- using System.Runtime.Versioning;
- using System.Runtime.InteropServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
// IdnMapping class used to map names to Punycode
-
- public sealed class IdnMapping
+ public sealed partial class IdnMapping
{
- // Legal name lengths for domain names
- const int M_labelLimit = 63; // Not including dots
- const int M_defaultNameLimit = 255; // Including dots
-
- // IDNA prefix
- const String M_strAcePrefix = "xn--";
-
- // Legal "dot" seperators (i.e: . in www.microsoft.com)
- static char[] M_Dots =
- {
- '.', '\u3002', '\uFF0E', '\uFF61'
- };
-
- bool m_bAllowUnassigned;
- bool m_bUseStd3AsciiRules;
+ private bool _allowUnassigned;
+ private bool _useStd3AsciiRules;
public IdnMapping()
{
@@ -94,282 +42,192 @@ namespace System.Globalization
public bool AllowUnassigned
{
- get
- {
- return this.m_bAllowUnassigned;
- }
-
- set
- {
- this.m_bAllowUnassigned = value;
- }
+ get { return _allowUnassigned; }
+ set { _allowUnassigned = value; }
}
public bool UseStd3AsciiRules
{
- get
- {
- return this.m_bUseStd3AsciiRules;
- }
-
- set
- {
- this.m_bUseStd3AsciiRules = value;
- }
+ get { return _useStd3AsciiRules; }
+ set { _useStd3AsciiRules = value; }
}
// Gets ASCII (Punycode) version of the string
- public String GetAscii(String unicode)
+ public string GetAscii(string unicode)
{
return GetAscii(unicode, 0);
}
- public String GetAscii(String unicode, int index)
+ public string GetAscii(string unicode, int index)
{
- if (unicode==null) throw new ArgumentNullException(nameof(unicode));
+ if (unicode == null)
+ throw new ArgumentNullException(nameof(unicode));
Contract.EndContractBlock();
return GetAscii(unicode, index, unicode.Length - index);
}
- public string GetAscii(String unicode, int index, int count)
+ public string GetAscii(string unicode, int index, int count)
{
- if (unicode == null) throw new ArgumentNullException(nameof(unicode));
+ if (unicode == null)
+ throw new ArgumentNullException(nameof(unicode));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (index > unicode.Length)
- throw new ArgumentOutOfRangeException(nameof(index),
- Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
if (index > unicode.Length - count)
- throw new ArgumentOutOfRangeException(nameof(unicode),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(unicode), SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
- // We're only using part of the string
- unicode = unicode.Substring(index, count);
-
- if (Environment.IsWindows8OrAbove)
- {
- return GetAsciiUsingOS(unicode);
- }
-
- // Check for ASCII only string, which will be unchanged
- if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, true))
- {
- return unicode;
- }
-
- // Cannot be null terminated (normalization won't help us with this one, and
- // may have returned false before checking the whole string above)
- Debug.Assert(unicode.Length >= 1, "[IdnMapping.GetAscii]Expected 0 length strings to fail before now.");
- if (unicode[unicode.Length - 1] <= 0x1f)
- {
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length-1 ),
- nameof(unicode));
- }
-
- // Have to correctly IDNA normalize the string and Unassigned flags
- bool bHasLastDot = (unicode.Length > 0) && IsDot(unicode[unicode.Length - 1]);
- unicode = unicode.Normalize((NormalizationForm)(m_bAllowUnassigned ?
- ExtendedNormalizationForms.FormIdna : ExtendedNormalizationForms.FormIdnaDisallowUnassigned));
-
- // Make sure we didn't normalize away something after a last dot
- if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1]))
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
- }
-
- // May need to check Std3 rules again for non-ascii
- if (UseStd3AsciiRules)
+ if (count == 0)
{
- ValidateStd3AndAscii(unicode, true, false);
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
}
-
- // Go ahead and encode it
- return punycode_encode(unicode);
- }
-
-
- private String GetAsciiUsingOS(String unicode)
- {
- if (unicode.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
- }
-
- if (unicode[unicode.Length - 1] == 0)
+ if (unicode[index + count - 1] == 0)
{
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", unicode.Length - 1),
- nameof(unicode));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, index + count - 1), nameof(unicode));
}
-
- uint flags = (uint) ((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
- int length = IdnToAscii(flags, unicode, unicode.Length, null, 0);
- int lastError;
-
- if (length == 0)
+ if (GlobalizationMode.Invariant)
{
- lastError = Marshal.GetLastWin32Error();
- if (lastError == ERROR_INVALID_NAME)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
- }
-
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
+ return GetAsciiInvariant(unicode, index, count);
}
- char [] output = new char[length];
-
- length = IdnToAscii(flags, unicode, unicode.Length, output, length);
- if (length == 0)
+ unsafe
{
- lastError = Marshal.GetLastWin32Error();
- if (lastError == ERROR_INVALID_NAME)
+ fixed (char* pUnicode = unicode)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(unicode));
+ return GetAsciiCore(pUnicode + index, count);
}
-
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(unicode));
}
-
- return new String(output, 0, length);
}
// Gets Unicode version of the string. Normalized and limited to IDNA characters.
- public String GetUnicode(String ascii)
+ public string GetUnicode(string ascii)
{
return GetUnicode(ascii, 0);
}
- public String GetUnicode(String ascii, int index)
+ public string GetUnicode(string ascii, int index)
{
- if (ascii==null) throw new ArgumentNullException(nameof(ascii));
+ if (ascii == null)
+ throw new ArgumentNullException(nameof(ascii));
Contract.EndContractBlock();
return GetUnicode(ascii, index, ascii.Length - index);
}
- public String GetUnicode(String ascii, int index, int count)
+ public string GetUnicode(string ascii, int index, int count)
{
- if (ascii==null) throw new ArgumentNullException(nameof(ascii));
+ if (ascii == null)
+ throw new ArgumentNullException(nameof(ascii));
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0) ? nameof(index) : nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (index > ascii.Length)
- throw new ArgumentOutOfRangeException("byteIndex",
- Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
if (index > ascii.Length - count)
- throw new ArgumentOutOfRangeException(nameof(ascii),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(ascii), SR.ArgumentOutOfRange_IndexCountBuffer);
// This is a case (i.e. explicitly null-terminated input) where behavior in .NET and Win32 intentionally differ.
// The .NET APIs should (and did in v4.0 and earlier) throw an ArgumentException on input that includes a terminating null.
// The Win32 APIs fail on an embedded null, but not on a terminating null.
if (count > 0 && ascii[index + count - 1] == (char)0)
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"),
- nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
Contract.EndContractBlock();
- // We're only using part of the string
- ascii = ascii.Substring(index, count);
-
- if (Environment.IsWindows8OrAbove)
+ if (GlobalizationMode.Invariant)
{
- return GetUnicodeUsingOS(ascii);
+ return GetUnicodeInvariant(ascii, index, count);
}
- // Convert Punycode to Unicode
- String strUnicode = punycode_decode(ascii);
+ unsafe
+ {
+ fixed (char* pAscii = ascii)
+ {
+ return GetUnicodeCore(pAscii + index, count);
+ }
+ }
+ }
- // Output name MUST obey IDNA rules & round trip (casing differences are allowed)
- if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnIllegalName"), nameof(ascii));
+ public override bool Equals(object obj)
+ {
+ IdnMapping that = obj as IdnMapping;
+ return
+ that != null &&
+ _allowUnassigned == that._allowUnassigned &&
+ _useStd3AsciiRules == that._useStd3AsciiRules;
+ }
- return strUnicode;
+ public override int GetHashCode()
+ {
+ return (_allowUnassigned ? 100 : 200) + (_useStd3AsciiRules ? 1000 : 2000);
}
-
- private string GetUnicodeUsingOS(string ascii)
+ //
+ // Invariant implementation
+ //
+
+ private const char c_delimiter = '-';
+ private const string c_strAcePrefix = "xn--";
+ private const int c_labelLimit = 63; // Not including dots
+ private const int c_defaultNameLimit = 255; // Including dots
+ private const int c_initialN = 0x80;
+ private const int c_maxint = 0x7ffffff;
+ private const int c_initialBias = 72;
+ private const int c_punycodeBase = 36;
+ private const int c_tmin = 1;
+ private const int c_tmax = 26;
+ private const int c_skew = 38;
+ private const int c_damp = 700;
+
+
+ // Legal "dot" separators (i.e: . in www.microsoft.com)
+ private static char[] c_Dots = { '.', '\u3002', '\uFF0E', '\uFF61' };
+
+ private string GetAsciiInvariant(string unicode, int index, int count)
{
- uint flags = (uint)((AllowUnassigned ? IDN_ALLOW_UNASSIGNED : 0) | (UseStd3AsciiRules ? IDN_USE_STD3_ASCII_RULES : 0));
- int length = IdnToUnicode(flags, ascii, ascii.Length, null, 0);
- int lastError;
-
- if (length == 0)
+ if (index > 0 || count < unicode.Length)
{
- lastError = Marshal.GetLastWin32Error();
- if (lastError == ERROR_INVALID_NAME)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
- }
-
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
+ unicode = unicode.Substring(index, count);
}
- char [] output = new char[length];
-
- length = IdnToUnicode(flags, ascii, ascii.Length, output, length);
- if (length == 0)
+ // Check for ASCII only string, which will be unchanged
+ if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, true))
{
- lastError = Marshal.GetLastWin32Error();
- if (lastError == ERROR_INVALID_NAME)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnIllegalName"), nameof(ascii));
- }
-
- throw new ArgumentException(Environment.GetResourceString("Argument_IdnBadPunycode"), nameof(ascii));
+ return unicode;
}
-
- return new String(output, 0, length);
- }
- public override bool Equals(Object obj)
- {
- IdnMapping that = obj as IdnMapping;
-
- if (that != null)
+ // Cannot be null terminated (normalization won't help us with this one, and
+ // may have returned false before checking the whole string above)
+ Debug.Assert(count >= 1, "[IdnMapping.GetAscii] Expected 0 length strings to fail before now.");
+ if (unicode[unicode.Length - 1] <= 0x1f)
{
- return this.m_bAllowUnassigned == that.m_bAllowUnassigned &&
- this.m_bUseStd3AsciiRules == that.m_bUseStd3AsciiRules;
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, unicode.Length - 1), nameof(unicode));
}
- return (false);
- }
+ // Have to correctly IDNA normalize the string and Unassigned flags
+ bool bHasLastDot = (unicode.Length > 0) && IsDot(unicode[unicode.Length - 1]);
- public override int GetHashCode()
- {
- return (this.m_bAllowUnassigned ? 100 : 200) + (this.m_bUseStd3AsciiRules ? 1000 : 2000);
- }
+ // Make sure we didn't normalize away something after a last dot
+ if ((!bHasLastDot) && unicode.Length > 0 && IsDot(unicode[unicode.Length - 1]))
+ {
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
+ }
- // Helpers
- static bool IsSupplementary(int cTest)
- {
- return cTest >= 0x10000;
- }
+ // May need to check Std3 rules again for non-ascii
+ if (UseStd3AsciiRules)
+ {
+ ValidateStd3AndAscii(unicode, true, false);
+ }
- // Is it a dot?
- // are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or
- // U+FF61 (halfwidth ideographic full stop).
- // Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization
- static bool IsDot(char c)
- {
- return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61';
+ // Go ahead and encode it
+ return PunycodeEncode(unicode);
}
-
// See if we're only ASCII
static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii)
{
// If its empty, then its too small
if (unicode.Length == 0)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
- Contract.EndContractBlock();
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
int iLastDot = -1;
@@ -379,9 +237,7 @@ namespace System.Globalization
// Aren't allowing control chars (or 7f, but idn tables catch that, they don't catch \0 at end though)
if (unicode[i] <= 0x1f)
{
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", i ),
- nameof(unicode));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, i ), nameof(unicode));
}
// If its Unicode or a control character, return false (non-ascii)
@@ -393,17 +249,15 @@ namespace System.Globalization
{
// Can't have 2 dots in a row
if (i == iLastDot + 1)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// If its too far between dots then fail
- if (i - iLastDot > M_labelLimit + 1)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
+ if (i - iLastDot > c_labelLimit + 1)
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// If validating Std3, then char before dot can't be - char
if (bUseStd3 && i > 0)
- ValidateStd3(unicode[i-1], true);
+ ValidateStd3(unicode[i - 1], true);
// Remember where the last dot is
iLastDot = i;
@@ -418,148 +272,22 @@ namespace System.Globalization
}
// If we never had a dot, then we need to be shorter than the label limit
- if (iLastDot == -1 && unicode.Length > M_labelLimit)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
+ if (iLastDot == -1 && unicode.Length > c_labelLimit)
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// Need to validate entire string length, 1 shorter if last char wasn't a dot
- if (unicode.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1])? 0 : 1))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadNameSize",
- M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
- nameof(unicode));
+ if (unicode.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1))
+ throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize,
+ c_defaultNameLimit - (IsDot(unicode[unicode.Length - 1]) ? 0 : 1)), nameof(unicode));
// If last char wasn't a dot we need to check for trailing -
- if (bUseStd3 && !IsDot(unicode[unicode.Length-1]))
- ValidateStd3(unicode[unicode.Length-1], true);
+ if (bUseStd3 && !IsDot(unicode[unicode.Length - 1]))
+ ValidateStd3(unicode[unicode.Length - 1], true);
return true;
}
- // Validate Std3 rules for a character
- static void ValidateStd3(char c, bool bNextToDot)
- {
- // Check for illegal characters
- if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed
- (c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) ||
- (c == '-' && bNextToDot))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadStd3", c), "Unicode");
- }
-
- //
- // The following punycode implementation is ported from the sample punycode.c in RFC 3492
- // Original sample code was written by Adam M. Costello.
- //
-
- // Return whether a punycode code point is flagged as being upper case.
-
- static bool HasUpperCaseFlag(char punychar)
- {
- return (punychar >= 'A' && punychar <= 'Z');
- }
-
-
- /**********************************************************/
- /* Implementation (would normally go in its own .c file): */
-
- /*** Bootstring parameters for Punycode ***/
- const int punycodeBase = 36;
- const int tmin = 1;
- const int tmax = 26;
- const int skew = 38;
- const int damp = 700;
- const int initial_bias = 72;
- const int initial_n = 0x80;
- const char delimiter = '-';
-
- /* basic(cp) tests whether cp is a basic code point: */
- static bool basic(uint cp)
- {
- // Is it in ASCII range?
- return cp < 0x80;
- }
-
- // decode_digit(cp) returns the numeric value of a basic code */
- // point (for use in representing integers) in the range 0 to */
- // punycodeBase-1, or <0 if cp is does not represent a value. */
-
- static int decode_digit(char cp)
- {
- if (cp >= '0' && cp <= '9')
- return cp - '0' + 26;
-
- // Two flavors for case differences
- if (cp >= 'a' && cp <= 'z')
- return cp - 'a';
-
- if (cp >= 'A' && cp <= 'Z')
- return cp - 'A';
-
- // Expected 0-9, A-Z or a-z, everything else is illegal
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), "ascii");
- }
-
- /* encode_digit(d,flag) returns the basic code point whose value */
- /* (when used for representing integers) is d, which needs to be in */
- /* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */
- /* true, in which case the uppercase form is used. */
-
- static char encode_digit(int d)
- {
- Debug.Assert(d >= 0 && d < punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
- // 26-35 map to ASCII 0-9
- if (d > 25) return (char)(d - 26 + '0');
-
- // 0-25 map to a-z or A-Z
- return (char)(d + 'a');
- }
-
-
-
- /* encode_basic(bcp,flag) forces a basic code point to lowercase */
- /* if flag is false, uppercase if flag is true, and returns */
- /* the resulting code point. The code point is unchanged if it */
- /* is caseless. The behavior is undefined if bcp is not a basic */
- /* code point. */
-
- static char encode_basic(char bcp)
- {
- if (HasUpperCaseFlag(bcp))
- bcp += (char)('a' - 'A');
-
- return bcp;
- }
-
- /*** Platform-specific constants ***/
-
- /* maxint is the maximum value of a uint variable: */
- const int maxint = 0x7ffffff;
-
- /*** Bias adaptation function ***/
-
- static int adapt(
- int delta, int numpoints, bool firsttime )
- {
- uint k;
-
- delta = firsttime ? delta / damp : delta / 2;
- Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
- delta += delta / numpoints;
-
- for (k = 0; delta > ((punycodeBase - tmin) * tmax) / 2; k += punycodeBase)
- {
- delta /= punycodeBase - tmin;
- }
-
- Debug.Assert(delta + skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
- return (int)(k + (punycodeBase - tmin + 1) * delta / (delta + skew));
- }
-
- /*** Main encode function ***/
-
- /* punycode_encode() converts Unicode to Punycode. The input */
+ /* PunycodeEncode() converts Unicode to Punycode. The input */
/* is represented as an array of Unicode code points (not code */
/* units; surrogate pairs are not allowed), and the output */
/* will be represented as an array of ASCII code points. The */
@@ -584,14 +312,11 @@ namespace System.Globalization
/* value can be any of the punycode_status values defined above */
/* except punycode_bad_input; if not punycode_success, then */
/* output_size and output might contain garbage. */
-
- static String punycode_encode(String unicode)
+ static string PunycodeEncode(string unicode)
{
// 0 length strings aren't allowed
if (unicode.Length == 0)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
- Contract.EndContractBlock();
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
StringBuilder output = new StringBuilder(unicode.Length);
int iNextDot = 0;
@@ -602,8 +327,8 @@ namespace System.Globalization
while (iNextDot < unicode.Length)
{
// Find end of this segment
- iNextDot = unicode.IndexOfAny(M_Dots, iAfterLastDot);
- Debug.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
+ iNextDot = unicode.IndexOfAny(c_Dots, iAfterLastDot);
+ Contract.Assert(iNextDot <= unicode.Length, "[IdnMapping.punycode_encode]IndexOfAny is broken");
if (iNextDot < 0)
iNextDot = unicode.Length;
@@ -612,14 +337,13 @@ namespace System.Globalization
{
// Only allowed to have empty sections as trailing .
if (iNextDot != unicode.Length)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// Last dot, stop
break;
}
// We'll need an Ace prefix
- output.Append(M_strAcePrefix);
+ output.Append(c_strAcePrefix);
// Everything resets every segment.
bool bRightToLeft = false;
@@ -642,8 +366,7 @@ namespace System.Globalization
if (eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), nameof(unicode));
+ throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode));
}
}
@@ -653,8 +376,7 @@ namespace System.Globalization
for (basicCount = iAfterLastDot; basicCount < iNextDot; basicCount++)
{
// Can't be lonely surrogate because it would've thrown in normalization
- Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false,
- "[IdnMapping.punycode_encode]Unexpected low surrogate");
+ Debug.Assert(Char.IsLowSurrogate(unicode, basicCount) == false, "[IdnMapping.punycode_encode]Unexpected low surrogate");
// Double check our bidi rules
BidiCategory testBidi = CharUnicodeInfo.GetBidiCategory(unicode, basicCount);
@@ -663,23 +385,20 @@ namespace System.Globalization
if (bRightToLeft && testBidi == BidiCategory.LeftToRight)
{
// Oops, throw error
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), nameof(unicode));
+ throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode));
}
// If we're not RTL we can't have RTL chars
- if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft ||
- testBidi == BidiCategory.RightToLeftArabic))
+ if (!bRightToLeft && (testBidi == BidiCategory.RightToLeft || testBidi == BidiCategory.RightToLeftArabic))
{
// Oops, throw error
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), nameof(unicode));
+ throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(unicode));
}
// If its basic then add it
- if (basic(unicode[basicCount]))
+ if (Basic(unicode[basicCount]))
{
- output.Append(encode_basic(unicode[basicCount]));
+ output.Append(EncodeBasic(unicode[basicCount]));
numProcessed++;
}
// If its a surrogate, skip the next since our bidi category tester doesn't handle it.
@@ -693,16 +412,15 @@ namespace System.Globalization
if (numBasicCodePoints == iNextDot - iAfterLastDot)
{
// Get rid of xn-- and this segments done
- output.Remove(iOutputAfterLastDot, M_strAcePrefix.Length);
+ output.Remove(iOutputAfterLastDot, c_strAcePrefix.Length);
}
else
{
// If it has some non-basic code points the input cannot start with xn--
- if (unicode.Length - iAfterLastDot >= M_strAcePrefix.Length &&
- unicode.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
- M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(unicode));
+ if (unicode.Length - iAfterLastDot >= c_strAcePrefix.Length &&
+ unicode.Substring(iAfterLastDot, c_strAcePrefix.Length).Equals(
+ c_strAcePrefix, StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(unicode));
// Need to do ACE encoding
int numSurrogatePairs = 0; // number of surrogate pairs so far
@@ -710,13 +428,13 @@ namespace System.Globalization
// Add a delimiter (-) if we had any basic code points (between basic and encoded pieces)
if (numBasicCodePoints > 0)
{
- output.Append(delimiter);
+ output.Append(c_delimiter);
}
// Initialize the state
- int n = initial_n;
+ int n = c_initialN;
int delta = 0;
- int bias = initial_bias;
+ int bias = c_initialBias;
// Main loop
while (numProcessed < (iNextDot - iAfterLastDot))
@@ -726,7 +444,7 @@ namespace System.Globalization
int j;
int m;
int test = 0;
- for (m = maxint, j = iAfterLastDot;
+ for (m = c_maxint, j = iAfterLastDot;
j < iNextDot;
j += IsSupplementary(test) ? 2 : 1)
{
@@ -751,27 +469,24 @@ namespace System.Globalization
if (test < n)
{
delta++;
- Debug.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
+ Contract.Assert(delta > 0, "[IdnMapping.cs]2 punycode_encode - delta overflowed int");
}
if (test == n)
{
// Represent delta as a generalized variable-length integer:
int q, k;
- for (q = delta, k = punycodeBase; ; k += punycodeBase)
+ for (q = delta, k = c_punycodeBase; ; k += c_punycodeBase)
{
- int t = k <= bias ? tmin :
- k >= bias + tmax ? tmax : k - bias;
+ int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias;
if (q < t) break;
- Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_encode]Expected punycodeBase (36) to be != t");
-
- int mod;
- q = Math.DivRem(q - t, punycodeBase - t, out mod);
- output.Append(encode_digit(t + mod));
+ Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_encode]Expected c_punycodeBase (36) to be != t");
+ output.Append(EncodeDigit(t + (q - t) % (c_punycodeBase - t)));
+ q = (q - t) / (c_punycodeBase - t);
}
- output.Append(encode_digit(q));
- bias = adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints);
+ output.Append(EncodeDigit(q));
+ bias = Adapt(delta, (numProcessed - numSurrogatePairs) + 1, numProcessed == numBasicCodePoints);
delta = 0;
numProcessed++;
@@ -789,9 +504,8 @@ namespace System.Globalization
}
// Make sure its not too big
- if (output.Length - iOutputAfterLastDot > M_labelLimit)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(unicode));
+ if (output.Length - iOutputAfterLastDot > c_labelLimit)
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(unicode));
// Done with this segment, add dot if necessary
if (iNextDot != unicode.Length)
@@ -802,19 +516,61 @@ namespace System.Globalization
}
// Throw if we're too long
- if (output.Length > M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadNameSize",
- M_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)),
- nameof(unicode));
-
+ if (output.Length > c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1))
+ throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize,
+ c_defaultNameLimit - (IsDot(unicode[unicode.Length-1]) ? 0 : 1)), nameof(unicode));
// Return our output string
return output.ToString();
}
- /*** Main decode function ***/
+ // Is it a dot?
+ // are we U+002E (., full stop), U+3002 (ideographic full stop), U+FF0E (fullwidth full stop), or
+ // U+FF61 (halfwidth ideographic full stop).
+ // Note: IDNA Normalization gets rid of dots now, but testing for last dot is before normalization
+ private static bool IsDot(char c)
+ {
+ return c == '.' || c == '\u3002' || c == '\uFF0E' || c == '\uFF61';
+ }
+
+ private static bool IsSupplementary(int cTest)
+ {
+ return cTest >= 0x10000;
+ }
- /* punycode_decode() converts Punycode to Unicode. The input is */
+ private static bool Basic(uint cp)
+ {
+ // Is it in ASCII range?
+ return cp < 0x80;
+ }
+
+ // Validate Std3 rules for a character
+ private static void ValidateStd3(char c, bool bNextToDot)
+ {
+ // Check for illegal characters
+ if ((c <= ',' || c == '/' || (c >= ':' && c <= '@') || // Lots of characters not allowed
+ (c >= '[' && c <= '`') || (c >= '{' && c <= (char)0x7F)) ||
+ (c == '-' && bNextToDot))
+ throw new ArgumentException(SR.Format(SR.Argument_IdnBadStd3, c), nameof(c));
+ }
+
+ private string GetUnicodeInvariant(string ascii, int index, int count)
+ {
+ if (index > 0 || count < ascii.Length)
+ {
+ // We're only using part of the string
+ ascii = ascii.Substring(index, count);
+ }
+ // Convert Punycode to Unicode
+ string strUnicode = PunycodeDecode(ascii);
+
+ // Output name MUST obey IDNA rules & round trip (casing differences are allowed)
+ if (!ascii.Equals(GetAscii(strUnicode), StringComparison.OrdinalIgnoreCase))
+ throw new ArgumentException(SR.Argument_IdnIllegalName, nameof(ascii));
+
+ return strUnicode;
+ }
+
+ /* PunycodeDecode() converts Punycode to Unicode. The input is */
/* represented as an array of ASCII code points, and the output */
/* will be represented as an array of Unicode code points. The */
/* input_length is the number of code points in the input. The */
@@ -835,19 +591,16 @@ namespace System.Globalization
/* decoder will never need to write an output_length greater than */
/* input_length, because of how the encoding is defined. */
- static String punycode_decode( String ascii )
+ private static string PunycodeDecode(string ascii)
{
// 0 length strings aren't allowed
if (ascii.Length == 0)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(ascii));
- Contract.EndContractBlock();
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// Throw if we're too long
- if (ascii.Length > M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadNameSize",
- M_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii));
+ if (ascii.Length > c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1))
+ throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize,
+ c_defaultNameLimit - (IsDot(ascii[ascii.Length-1]) ? 0 : 1)), nameof(ascii));
// output stringbuilder
StringBuilder output = new StringBuilder(ascii.Length);
@@ -869,51 +622,35 @@ namespace System.Globalization
{
// Only allowed to have empty sections as trailing .
if (iNextDot != ascii.Length)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// Last dot, stop
break;
}
// In either case it can't be bigger than segment size
- if (iNextDot - iAfterLastDot > M_labelLimit)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(ascii));
+ if (iNextDot - iAfterLastDot > c_labelLimit)
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// See if this section's ASCII or ACE
- if (ascii.Length < M_strAcePrefix.Length + iAfterLastDot ||
- !ascii.Substring(iAfterLastDot, M_strAcePrefix.Length).Equals(
- M_strAcePrefix, StringComparison.OrdinalIgnoreCase))
+ if (ascii.Length < c_strAcePrefix.Length + iAfterLastDot ||
+ !ascii.Substring(iAfterLastDot,c_strAcePrefix.Length).Equals(c_strAcePrefix, StringComparison.OrdinalIgnoreCase))
{
- // Its supposed to be just ASCII
- // Actually, for non xn-- stuff do we want to allow Unicode?
- // for (int i = iAfterLastDot; i < iNextDot; i++)
- // {
- // // Only ASCII is allowed
- // if (ascii[i] >= 0x80)
- // throw new ArgumentException(Environment.GetResourceString(
- // "Argument_IdnBadPunycode"), nameof(ascii));
-// }
-
// Its ASCII, copy it
output.Append(ascii.Substring(iAfterLastDot, iNextDot - iAfterLastDot));
-
- // ASCII doesn't have BIDI issues
}
else
{
// Not ASCII, bump up iAfterLastDot to be after ACE Prefix
- iAfterLastDot += M_strAcePrefix.Length;
+ iAfterLastDot += c_strAcePrefix.Length;
// Get number of basic code points (where delimiter is)
// numBasicCodePoints < 0 if there're no basic code points
- int iTemp = ascii.LastIndexOf(delimiter, iNextDot - 1);
+ int iTemp = ascii.LastIndexOf(c_delimiter, iNextDot - 1);
// Trailing - not allowed
if (iTemp == iNextDot - 1)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
int numBasicCodePoints;
if (iTemp <= iAfterLastDot)
@@ -924,31 +661,25 @@ namespace System.Globalization
// Copy all the basic code points, making sure they're all in the allowed range,
// and losing the casing for all of them.
- for (int copyAscii = iAfterLastDot;
- copyAscii < iAfterLastDot + numBasicCodePoints;
- copyAscii++)
+ for (int copyAscii = iAfterLastDot; copyAscii < iAfterLastDot + numBasicCodePoints; copyAscii++)
{
// Make sure we don't allow unicode in the ascii part
if (ascii[copyAscii] > 0x7f)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
// When appending make sure they get lower cased
- output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ?
- ascii[copyAscii] - 'A' + 'a' :
- ascii[copyAscii]));
+ output.Append((char)(ascii[copyAscii] >= 'A' && ascii[copyAscii] <='Z' ? ascii[copyAscii] - 'A' + 'a' : ascii[copyAscii]));
}
}
// Get ready for main loop. Start at beginning if we didn't have any
// basic code points, otherwise start after the -.
// asciiIndex will be next character to read from ascii
- int asciiIndex = iAfterLastDot +
- ( numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
+ int asciiIndex = iAfterLastDot + (numBasicCodePoints > 0 ? numBasicCodePoints + 1 : 0);
// initialize our state
- int n = initial_n;
- int bias = initial_bias;
+ int n = c_initialN;
+ int bias = c_initialBias;
int i = 0;
int w, k;
@@ -965,58 +696,43 @@ namespace System.Globalization
/* value at the end to obtain delta. */
int oldi = i;
- for (w = 1, k = punycodeBase; ; k += punycodeBase)
+ for (w = 1, k = c_punycodeBase; ; k += c_punycodeBase)
{
// Check to make sure we aren't overrunning our ascii string
if (asciiIndex >= iNextDot)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
// decode the digit from the next char
- int digit = decode_digit(ascii[asciiIndex++]);
+ int digit = DecodeDigit(ascii[asciiIndex++]);
Debug.Assert(w > 0, "[IdnMapping.punycode_decode]Expected w > 0");
- if (digit > (maxint - i) / w)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ if (digit > (c_maxint - i) / w)
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
i += (int)(digit * w);
- int t = k <= bias ? tmin :
- k >= bias + tmax ? tmax : k - bias;
- if (digit < t) break;
- Debug.Assert(punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != punycodeBase (36)");
- if (w > maxint / (punycodeBase - t))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
- w *= (punycodeBase - t);
+ int t = k <= bias ? c_tmin : k >= bias + c_tmax ? c_tmax : k - bias;
+ if (digit < t)
+ break;
+ Debug.Assert(c_punycodeBase != t, "[IdnMapping.punycode_decode]Expected t != c_punycodeBase (36)");
+ if (w > c_maxint / (c_punycodeBase - t))
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
+ w *= (c_punycodeBase - t);
}
- bias = adapt(i - oldi,
- (output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0);
+ bias = Adapt(i - oldi, (output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1, oldi == 0);
/* i was supposed to wrap around from output.Length to 0, */
/* incrementing n each time, so we'll fix that now: */
Debug.Assert((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1 > 0,
"[IdnMapping.punycode_decode]Expected to have added > 0 characters this segment");
- if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > maxint - n)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ if (i / ((output.Length - iOutputAfterLastDot - numSurrogatePairs) + 1) > c_maxint - n)
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
n += (int)(i / (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1));
i %= (output.Length - iOutputAfterLastDot - numSurrogatePairs + 1);
- // If it was flagged it needs to be capitalized
- // if (HasUpperCaseFlag(ascii[asciiIndex - 1]))
- // {
- // /* Case of last character determines uppercase flag: */
- // // Any casing stuff need to happen last.
- // If we wanted to reverse the IDNA casing data
- // n = MakeNUpperCase(n)
- // }
-
// Make sure n is legal
if ((n < 0 || n > 0x10ffff) || (n >= 0xD800 && n <= 0xDFFF))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
// insert n at position i of the output: Really tricky if we have surrogates
int iUseInsertLocation;
@@ -1027,14 +743,11 @@ namespace System.Globalization
{
// Hard way, we have supplimentary characters
int iCount;
- for (iCount = i, iUseInsertLocation = iOutputAfterLastDot;
- iCount > 0;
- iCount--, iUseInsertLocation++)
+ for (iCount = i, iUseInsertLocation = iOutputAfterLastDot; iCount > 0; iCount--, iUseInsertLocation++)
{
// If its a surrogate, we have to go one more
if (iUseInsertLocation >= output.Length)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadPunycode"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(ascii));
if (Char.IsSurrogate(output[iUseInsertLocation]))
iUseInsertLocation++;
}
@@ -1071,34 +784,27 @@ namespace System.Globalization
for (int iTest = iOutputAfterLastDot; iTest < output.Length; iTest++)
{
// This might happen if we run into a pair
- if (Char.IsLowSurrogate(output.ToString(), iTest)) continue;
+ if (Char.IsLowSurrogate(output.ToString(), iTest))
+ continue;
// Check to see if its LTR
eBidi = CharUnicodeInfo.GetBidiCategory(output.ToString(), iTest);
if ((bRightToLeft && eBidi == BidiCategory.LeftToRight) ||
- (!bRightToLeft && (eBidi == BidiCategory.RightToLeft ||
- eBidi == BidiCategory.RightToLeftArabic)))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), nameof(ascii));
-
- // Make it lower case if we must (so we can test IsNormalized later)
- // if (output[iTest] >= 'A' && output[iTest] <= 'Z')
- // output[iTest] = (char)(output[iTest] + (char)('a' - 'A'));
+ (!bRightToLeft && (eBidi == BidiCategory.RightToLeft || eBidi == BidiCategory.RightToLeftArabic)))
+ throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii));
}
// Its also a requirement that the last one be RTL if 1st is RTL
if (bRightToLeft && eBidi != BidiCategory.RightToLeft && eBidi != BidiCategory.RightToLeftArabic)
{
// Oops, last wasn't RTL, last should be RTL if first is RTL
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadBidi"), nameof(ascii));
+ throw new ArgumentException(SR.Argument_IdnBadBidi, nameof(ascii));
}
}
// See if this label was too long
- if (iNextDot - iAfterLastDot > M_labelLimit)
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadLabelSize"), nameof(ascii));
+ if (iNextDot - iAfterLastDot > c_labelLimit)
+ throw new ArgumentException(SR.Argument_IdnBadLabelSize, nameof(ascii));
// Done with this segment, add dot if necessary
if (iNextDot != ascii.Length)
@@ -1109,79 +815,84 @@ namespace System.Globalization
}
// Throw if we're too long
- if (output.Length > M_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_IdnBadNameSize",
- M_defaultNameLimit -(IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii));
+ if (output.Length > c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1))
+ throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, c_defaultNameLimit - (IsDot(output[output.Length-1]) ? 0 : 1)), nameof(ascii));
// Return our output string
return output.ToString();
}
- /*
- The previous punycode implimentation is based on the sample code in RFC 3492
-
- Full Copyright Statement
-
- Copyright (C) The Internet Society (2003). All Rights Reserved.
-
- This document and translations of it may be copied and furnished to
- others, and derivative works that comment on or otherwise explain it
- or assist in its implementation may be prepared, copied, published
- and distributed, in whole or in part, without restriction of any
- kind, provided that the above copyright notice and this paragraph are
- included on all such copies and derivative works. However, this
- document itself may not be modified in any way, such as by removing
- the copyright notice or references to the Internet Society or other
- Internet organizations, except as needed for the purpose of
- developing Internet standards in which case the procedures for
- copyrights defined in the Internet Standards process must be
- followed, or as required to translate it into languages other than
- English.
-
- The limited permissions granted above are perpetual and will not be
- revoked by the Internet Society or its successors or assigns.
-
- This document and the information contained herein is provided on an
- "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
- TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING
- BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION
- HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
- MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
- */
-
-
- private const int IDN_ALLOW_UNASSIGNED = 0x1;
- private const int IDN_USE_STD3_ASCII_RULES = 0x2;
+ // DecodeDigit(cp) returns the numeric value of a basic code */
+ // point (for use in representing integers) in the range 0 to */
+ // c_punycodeBase-1, or <0 if cp is does not represent a value. */
+
+ private static int DecodeDigit(char cp)
+ {
+ if (cp >= '0' && cp <= '9')
+ return cp - '0' + 26;
+
+ // Two flavors for case differences
+ if (cp >= 'a' && cp <= 'z')
+ return cp - 'a';
+
+ if (cp >= 'A' && cp <= 'Z')
+ return cp - 'A';
+
+ // Expected 0-9, A-Z or a-z, everything else is illegal
+ throw new ArgumentException(SR.Argument_IdnBadPunycode, nameof(cp));
+ }
+
+ private static int Adapt(int delta, int numpoints, bool firsttime)
+ {
+ uint k;
+
+ delta = firsttime ? delta / c_damp : delta / 2;
+ Debug.Assert(numpoints != 0, "[IdnMapping.adapt]Expected non-zero numpoints.");
+ delta += delta / numpoints;
+
+ for (k = 0; delta > ((c_punycodeBase - c_tmin) * c_tmax) / 2; k += c_punycodeBase)
+ {
+ delta /= c_punycodeBase - c_tmin;
+ }
+
+ Debug.Assert(delta + c_skew != 0, "[IdnMapping.adapt]Expected non-zero delta+skew.");
+ return (int)(k + (c_punycodeBase - c_tmin + 1) * delta / (delta + c_skew));
+ }
+
+ /* EncodeBasic(bcp,flag) forces a basic code point to lowercase */
+ /* if flag is false, uppercase if flag is true, and returns */
+ /* the resulting code point. The code point is unchanged if it */
+ /* is caseless. The behavior is undefined if bcp is not a basic */
+ /* code point. */
+
+ static char EncodeBasic(char bcp)
+ {
+ if (HasUpperCaseFlag(bcp))
+ bcp += (char)('a' - 'A');
+
+ return bcp;
+ }
+
+ // Return whether a punycode code point is flagged as being upper case.
+ private static bool HasUpperCaseFlag(char punychar)
+ {
+ return (punychar >= 'A' && punychar <= 'Z');
+ }
+
+ /* EncodeDigit(d,flag) returns the basic code point whose value */
+ /* (when used for representing integers) is d, which needs to be in */
+ /* the range 0 to punycodeBase-1. The lowercase form is used unless flag is */
+ /* true, in which case the uppercase form is used. */
+
+ private static char EncodeDigit(int d)
+ {
+ Debug.Assert(d >= 0 && d < c_punycodeBase, "[IdnMapping.encode_digit]Expected 0 <= d < punycodeBase");
+ // 26-35 map to ASCII 0-9
+ if (d > 25) return (char)(d - 26 + '0');
+
+ // 0-25 map to a-z or A-Z
+ return (char)(d + 'a');
+ }
- private const int ERROR_INVALID_NAME = 123;
-
-
- [SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)]
- private static extern int IdnToAscii(
- uint dwFlags,
- [InAttribute()]
- [MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
- String lpUnicodeCharStr,
- int cchUnicodeChar,
- [System.Runtime.InteropServices.OutAttribute()]
-
- char [] lpASCIICharStr,
- int cchASCIIChar);
-
- [SuppressUnmanagedCodeSecurityAttribute()]
- [DllImport("normaliz.dll", CharSet=CharSet.Unicode, SetLastError=true)]
- private static extern int IdnToUnicode(
- uint dwFlags,
- [InAttribute()]
- [MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
- string lpASCIICharStr,
- int cchASCIIChar,
- [System.Runtime.InteropServices.OutAttribute()]
-
- char [] lpUnicodeCharStr,
- int cchUnicodeChar);
}
}
-
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs
new file mode 100644
index 0000000000..51ff8095a3
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.Unix.cs
@@ -0,0 +1,96 @@
+// 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.Diagnostics;
+
+namespace System.Globalization
+{
+ public partial class JapaneseCalendar : Calendar
+ {
+ private static EraInfo[] GetJapaneseEras()
+ {
+ if (GlobalizationMode.Invariant)
+ {
+ return null;
+ }
+
+ string[] eraNames;
+ if (!CalendarData.EnumCalendarInfo("ja-JP", CalendarId.JAPAN, CalendarDataType.EraNames, out eraNames))
+ {
+ return null;
+ }
+
+ string[] abbrevEnglishEraNames;
+ if (!CalendarData.EnumCalendarInfo("en", CalendarId.JAPAN, CalendarDataType.AbbrevEraNames, out abbrevEnglishEraNames))
+ {
+ return null;
+ }
+
+ List<EraInfo> eras = new List<EraInfo>();
+ int lastMaxYear = GregorianCalendar.MaxYear;
+
+ int latestEra = Interop.GlobalizationInterop.GetLatestJapaneseEra();
+ for (int i = latestEra; i >= 0; i--)
+ {
+ DateTime dt;
+ if (!GetJapaneseEraStartDate(i, out dt))
+ {
+ return null;
+ }
+
+ if (dt < JapaneseCalendar.calendarMinValue)
+ {
+ // only populate the Eras that are valid JapaneseCalendar date times
+ break;
+ }
+
+ eras.Add(new EraInfo(i, dt.Year, dt.Month, dt.Day, dt.Year - 1, 1, lastMaxYear - dt.Year + 1,
+ eraNames[i], GetAbbreviatedEraName(eraNames, i), abbrevEnglishEraNames[i]));
+
+ lastMaxYear = dt.Year;
+ }
+
+ // remap the Era numbers, now that we know how many there will be
+ for (int i = 0; i < eras.Count; i++)
+ {
+ eras[i].era = eras.Count - i;
+ }
+
+ return eras.ToArray();
+ }
+
+ // PAL Layer ends here
+
+ private static string GetAbbreviatedEraName(string[] eraNames, int eraIndex)
+ {
+ // This matches the behavior on Win32 - only returning the first character of the era name.
+ // See Calendar.EraAsString(Int32) - https://msdn.microsoft.com/en-us/library/windows/apps/br206751.aspx
+ return eraNames[eraIndex].Substring(0, 1);
+ }
+
+ private static bool GetJapaneseEraStartDate(int era, out DateTime dateTime)
+ {
+ Debug.Assert(!GlobalizationMode.Invariant);
+
+ dateTime = default(DateTime);
+
+ int startYear;
+ int startMonth;
+ int startDay;
+ bool result = Interop.GlobalizationInterop.GetJapaneseEraStartDate(
+ era,
+ out startYear,
+ out startMonth,
+ out startDay);
+
+ if (result)
+ {
+ dateTime = new DateTime(startYear, startMonth, startDay);
+ }
+
+ return result;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs
new file mode 100644
index 0000000000..fe8b1b5896
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.Win32.cs
@@ -0,0 +1,209 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+
+using Microsoft.Win32;
+
+namespace System.Globalization
+{
+ public partial class JapaneseCalendar : Calendar
+ {
+ private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
+ private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
+
+ // We know about 4 built-in eras, however users may add additional era(s) from the
+ // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
+ //
+ // Registry values look like:
+ // yyyy.mm.dd=era_abbrev_english_englishabbrev
+ //
+ // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
+ // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
+ // era is the Japanese Era name
+ // abbrev is the Abbreviated Japanese Era Name
+ // english is the English name for the Era (unused)
+ // englishabbrev is the Abbreviated English name for the era.
+ // . is a delimiter, but the value of . doesn't matter.
+ // '_' marks the space between the japanese era name, japanese abbreviated era name
+ // english name, and abbreviated english names.
+ private static EraInfo[] GetJapaneseEras()
+ {
+ // Look in the registry key and see if we can find any ranges
+ int iFoundEras = 0;
+ EraInfo[] registryEraRanges = null;
+
+ try
+ {
+ using (RegistryKey key = Registry.LocalMachine.OpenSubKey(c_japaneseErasHive, writable: false))
+ {
+ // Abort if we didn't find anything
+ if (key == null) return null;
+
+ // Look up the values in our reg key
+ String[] valueNames = key.GetValueNames();
+ if (valueNames != null && valueNames.Length > 0)
+ {
+ registryEraRanges = new EraInfo[valueNames.Length];
+
+ // Loop through the registry and read in all the values
+ for (int i = 0; i < valueNames.Length; i++)
+ {
+ // See if the era is a valid date
+ EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
+
+ // continue if not valid
+ if (era == null) continue;
+
+ // Remember we found one.
+ registryEraRanges[iFoundEras] = era;
+ iFoundEras++;
+ }
+ }
+ }
+ }
+ catch (System.Security.SecurityException)
+ {
+ // If we weren't allowed to read, then just ignore the error
+ return null;
+ }
+ catch (System.IO.IOException)
+ {
+ // If key is being deleted just ignore the error
+ return null;
+ }
+ catch (System.UnauthorizedAccessException)
+ {
+ // Registry access rights permissions, just ignore the error
+ return null;
+ }
+
+ //
+ // If we didn't have valid eras, then fail
+ // should have at least 4 eras
+ //
+ if (iFoundEras < 4) return null;
+
+ //
+ // Now we have eras, clean them up.
+ //
+ // Clean up array length
+ Array.Resize(ref registryEraRanges, iFoundEras);
+
+ // Sort them
+ Array.Sort(registryEraRanges, CompareEraRanges);
+
+ // Clean up era information
+ for (int i = 0; i < registryEraRanges.Length; i++)
+ {
+ // eras count backwards from length to 1 (and are 1 based indexes into string arrays)
+ registryEraRanges[i].era = registryEraRanges.Length - i;
+
+ // update max era year
+ if (i == 0)
+ {
+ // First range is 'til the end of the calendar
+ registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
+ }
+ else
+ {
+ // Rest are until the next era (remember most recent era is first in array)
+ registryEraRanges[i].maxEraYear = registryEraRanges[i - 1].yearOffset + 1 - registryEraRanges[i].yearOffset;
+ }
+ }
+
+ // Return our ranges
+ return registryEraRanges;
+ }
+
+ //
+ // Compare two era ranges, eg just the ticks
+ // Remember the era array is supposed to be in reverse chronological order
+ //
+ private static int CompareEraRanges(EraInfo a, EraInfo b)
+ {
+ return b.ticks.CompareTo(a.ticks);
+ }
+
+ //
+ // GetEraFromValue
+ //
+ // Parse the registry value name/data pair into an era
+ //
+ // Registry values look like:
+ // yyyy.mm.dd=era_abbrev_english_englishabbrev
+ //
+ // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
+ // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
+ // era is the Japanese Era name
+ // abbrev is the Abbreviated Japanese Era Name
+ // english is the English name for the Era (unused)
+ // englishabbrev is the Abbreviated English name for the era.
+ // . is a delimiter, but the value of . doesn't matter.
+ // '_' marks the space between the japanese era name, japanese abbreviated era name
+ // english name, and abbreviated english names.
+ private static EraInfo GetEraFromValue(String value, String data)
+ {
+ // Need inputs
+ if (value == null || data == null) return null;
+
+ //
+ // Get Date
+ //
+ // Need exactly 10 characters in name for date
+ // yyyy.mm.dd although the . can be any character
+ if (value.Length != 10) return null;
+
+ int year;
+ 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))
+ {
+ // Couldn't convert integer, fail
+ return null;
+ }
+
+ //
+ // Get Strings
+ //
+ // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
+ String[] names = data.Split('_');
+
+ // Should have exactly 4 parts
+ // 0 - Era Name
+ // 1 - Abbreviated Era Name
+ // 2 - English Era Name
+ // 3 - Abbreviated English Era Name
+ if (names.Length != 4) return null;
+
+ // Each part should have data in it
+ if (names[0].Length == 0 ||
+ names[1].Length == 0 ||
+ names[2].Length == 0 ||
+ names[3].Length == 0)
+ return null;
+
+ //
+ // Now we have an era we can build
+ // Note that the era # and max era year need cleaned up after sorting
+ // Don't use the full English Era Name (names[2])
+ //
+ return new EraInfo(0, year, month, day, year - 1, 1, 0,
+ names[0], names[1], names[3]);
+ }
+
+ // PAL Layer ends here
+
+ private static string[] s_japaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
+
+ private static string GetJapaneseEnglishEraName(int era)
+ {
+ Debug.Assert(era > 0);
+ return era <= s_japaneseErasEnglishNames.Length ? s_japaneseErasEnglishNames[era - 1] : " ";
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs
new file mode 100644
index 0000000000..6a9df97200
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/JapaneseCalendar.WinRT.cs
@@ -0,0 +1,62 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+
+using Internal.Runtime.Augments;
+
+namespace System.Globalization
+{
+ public partial class JapaneseCalendar : Calendar
+ {
+ private static EraInfo[] GetJapaneseEras()
+ {
+ int erasCount = WinRTInterop.Callbacks.GetJapaneseEraCount();
+ if (erasCount < 4)
+ {
+ return null;
+ }
+
+ EraInfo[] eras = new EraInfo[erasCount];
+ int lastMaxYear = GregorianCalendar.MaxYear;
+
+ for (int i = erasCount; i > 0; i--)
+ {
+ DateTimeOffset dateOffset;
+
+ string eraName;
+ string abbreviatedEraName;
+
+ if (!GetJapaneseEraInfo(i, out dateOffset, out eraName, out abbreviatedEraName))
+ {
+ return null;
+ }
+
+ DateTime dt = new DateTime(dateOffset.Ticks);
+
+ eras[erasCount - i] = new EraInfo(i, dt.Year, dt.Month, dt.Day, dt.Year - 1, 1, lastMaxYear - dt.Year + 1,
+ eraName, abbreviatedEraName, GetJapaneseEnglishEraName(i)); // era #4 start year/month/day, yearOffset, minEraYear
+
+ lastMaxYear = dt.Year;
+ }
+
+ return eras;
+ }
+
+ // PAL Layer ends here
+
+ private static string[] JapaneseErasEnglishNames = new String[] { "M", "T", "S", "H" };
+
+ private static string GetJapaneseEnglishEraName(int era)
+ {
+ Debug.Assert(era > 0);
+ return era <= JapaneseErasEnglishNames.Length ? JapaneseErasEnglishNames[era - 1] : " ";
+ }
+
+ private static bool GetJapaneseEraInfo(int era, out DateTimeOffset dateOffset, out string eraName, out string abbreviatedEraName)
+ {
+ return WinRTInterop.Callbacks.GetJapaneseEraInfo(era, out dateOffset, out eraName, out abbreviatedEraName);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
deleted file mode 100644
index 72331f8346..0000000000
--- a/src/mscorlib/src/System/Globalization/JapaneseCalendar.cs
+++ /dev/null
@@ -1,581 +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.
-
-namespace System.Globalization {
-
- using System;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
- using Microsoft.Win32;
-
- /*=================================JapaneseCalendar==========================
- **
- ** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as
- ** Gregorian calendar. However, the year value is an offset to the Gregorian
- ** year based on the era.
- **
- ** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor,
- ** and the era begins on the day an emperor ascends the throne and continues until his death.
- ** The era changes at 12:00AM.
- **
- ** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st.
- ** 1989/1/8 A.D. is also Heisei 1st 1/8.
- **
- ** Any date in the year during which era is changed can be reckoned in either era. For example,
- ** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year.
- **
- ** Note:
- ** The DateTime can be represented by the JapaneseCalendar are limited to two factors:
- ** 1. The min value and max value of DateTime class.
- ** 2. The available era information.
- **
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1868/09/08 9999/12/31
- ** Japanese Meiji 01/01 Heisei 8011/12/31
- ============================================================================*/
-
-
- [Serializable]
- public class JapaneseCalendar : Calendar
- {
- internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8);
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (calendarMinValue);
- }
- }
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (DateTime.MaxValue);
- }
- }
-
- // Return the type of the Japanese calendar.
- //
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.SolarCalendar;
- }
- }
-
- //
- // Using a field initializer rather than a static constructor so that the whole class can be lazy
- // init.
- static internal volatile EraInfo[] japaneseEraInfo;
-
- //
- // Read our era info
- //
- // m_EraInfo must be listed in reverse chronological order. The most recent era
- // should be the first element.
- // That is, m_EraInfo[0] contains the most recent era.
- //
- // We know about 4 built-in eras, however users may add additional era(s) from the
- // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
- //
- // Registry values look like:
- // yyyy.mm.dd=era_abbrev_english_englishabbrev
- //
- // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
- // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
- // era is the Japanese Era name
- // abbrev is the Abbreviated Japanese Era Name
- // english is the English name for the Era (unused)
- // englishabbrev is the Abbreviated English name for the era.
- // . is a delimiter, but the value of . doesn't matter.
- // '_' marks the space between the japanese era name, japanese abbreviated era name
- // english name, and abbreviated english names.
- //
- internal static EraInfo[] GetEraInfo()
- {
- // See if we need to build it
- if (japaneseEraInfo == null)
- {
- // See if we have any eras from the registry
- japaneseEraInfo = GetErasFromRegistry();
-
- // See if we have to use the built-in eras
- if (japaneseEraInfo == null)
- {
- // We know about some built-in ranges
- EraInfo[] defaultEraRanges = new EraInfo[4];
- defaultEraRanges[0] = new EraInfo( 4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988,
- "\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear
- defaultEraRanges[1] = new EraInfo( 3, 1926, 12, 25, 1925, 1, 1989-1925,
- "\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear
- defaultEraRanges[2] = new EraInfo( 2, 1912, 7, 30, 1911, 1, 1926-1911,
- "\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear
- defaultEraRanges[3] = new EraInfo( 1, 1868, 1, 1, 1867, 1, 1912-1867,
- "\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear
-
- // Remember the ranges we built
- japaneseEraInfo = defaultEraRanges;
- }
- }
-
- // return the era we found/made
- return japaneseEraInfo;
- }
-
-
-#if FEATURE_WIN32_REGISTRY
- private const string c_japaneseErasHive = @"System\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras";
- private const string c_japaneseErasHivePermissionList = @"HKEY_LOCAL_MACHINE\" + c_japaneseErasHive;
-
- //
- // GetErasFromRegistry()
- //
- // We know about 4 built-in eras, however users may add additional era(s) from the
- // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras
- //
- // Registry values look like:
- // yyyy.mm.dd=era_abbrev_english_englishabbrev
- //
- // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
- // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
- // era is the Japanese Era name
- // abbrev is the Abbreviated Japanese Era Name
- // english is the English name for the Era (unused)
- // englishabbrev is the Abbreviated English name for the era.
- // . is a delimiter, but the value of . doesn't matter.
- // '_' marks the space between the japanese era name, japanese abbreviated era name
- // english name, and abbreviated english names.
- private static EraInfo[] GetErasFromRegistry()
- {
- // Look in the registry key and see if we can find any ranges
- int iFoundEras = 0;
- EraInfo[] registryEraRanges = null;
-
- try
- {
- RegistryKey key = Registry.LocalMachine.OpenSubKey(c_japaneseErasHive, writable: false);
-
- // Abort if we didn't find anything
- if (key == null) return null;
-
- // Look up the values in our reg key
- String[] valueNames = key.GetValueNames();
- if (valueNames != null && valueNames.Length > 0)
- {
- registryEraRanges = new EraInfo[valueNames.Length];
-
- // Loop through the registry and read in all the values
- for (int i = 0; i < valueNames.Length; i++)
- {
- // See if the era is a valid date
- EraInfo era = GetEraFromValue(valueNames[i], key.GetValue(valueNames[i]).ToString());
-
- // continue if not valid
- if (era == null) continue;
-
- // Remember we found one.
- registryEraRanges[iFoundEras] = era;
- iFoundEras++;
- }
- }
- }
- catch (System.Security.SecurityException)
- {
- // If we weren't allowed to read, then just ignore the error
- return null;
- }
- catch (System.IO.IOException)
- {
- // If key is being deleted just ignore the error
- return null;
- }
- catch (System.UnauthorizedAccessException)
- {
- // Registry access rights permissions, just ignore the error
- return null;
- }
-
- //
- // If we didn't have valid eras, then fail
- // should have at least 4 eras
- //
- if (iFoundEras < 4) return null;
-
- //
- // Now we have eras, clean them up.
- //
- // Clean up array length
- Array.Resize(ref registryEraRanges, iFoundEras);
-
- // Sort them
- Array.Sort(registryEraRanges, CompareEraRanges);
-
- // Clean up era information
- for (int i = 0; i < registryEraRanges.Length; i++)
- {
- // eras count backwards from length to 1 (and are 1 based indexes into string arrays)
- registryEraRanges[i].era = registryEraRanges.Length - i;
-
- // update max era year
- if (i == 0)
- {
- // First range is 'til the end of the calendar
- registryEraRanges[0].maxEraYear = GregorianCalendar.MaxYear - registryEraRanges[0].yearOffset;
- }
- else
- {
- // Rest are until the next era (remember most recent era is first in array)
- registryEraRanges[i].maxEraYear = registryEraRanges[i-1].yearOffset + 1 - registryEraRanges[i].yearOffset;
- }
- }
-
- // Return our ranges
- return registryEraRanges;
- }
-#else
- private static EraInfo[] GetErasFromRegistry()
- {
- return null;
- }
-#endif
-
- //
- // Compare two era ranges, eg just the ticks
- // Remember the era array is supposed to be in reverse chronological order
- //
- private static int CompareEraRanges(EraInfo a, EraInfo b)
- {
- return b.ticks.CompareTo(a.ticks);
- }
-
- //
- // GetEraFromValue
- //
- // Parse the registry value name/data pair into an era
- //
- // Registry values look like:
- // yyyy.mm.dd=era_abbrev_english_englishabbrev
- //
- // Where yyyy.mm.dd is the registry value name, and also the date of the era start.
- // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long)
- // era is the Japanese Era name
- // abbrev is the Abbreviated Japanese Era Name
- // english is the English name for the Era (unused)
- // englishabbrev is the Abbreviated English name for the era.
- // . is a delimiter, but the value of . doesn't matter.
- // '_' marks the space between the japanese era name, japanese abbreviated era name
- // english name, and abbreviated english names.
- private static EraInfo GetEraFromValue(String value, String data)
- {
- // Need inputs
- if (value == null || data == null) return null;
-
- //
- // Get Date
- //
- // Need exactly 10 characters in name for date
- // yyyy.mm.dd although the . can be any character
- if (value.Length != 10) return null;
-
- int year;
- int month;
- int day;
-
- if (!Number.TryParseInt32(value.Substring(0,4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
- !Number.TryParseInt32(value.Substring(5,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
- !Number.TryParseInt32(value.Substring(8,2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
- {
- // Couldn't convert integer, fail
- return null;
- }
-
- //
- // Get Strings
- //
- // Needs to be a certain length e_a_E_A at least (7 chars, exactly 4 groups)
- String[] names = data.Split('_');
-
- // Should have exactly 4 parts
- // 0 - Era Name
- // 1 - Abbreviated Era Name
- // 2 - English Era Name
- // 3 - Abbreviated English Era Name
- if (names.Length != 4) return null;
-
- // Each part should have data in it
- if (names[0].Length == 0 ||
- names[1].Length == 0 ||
- names[2].Length == 0 ||
- names[3].Length == 0)
- return null;
-
- //
- // Now we have an era we can build
- // Note that the era # and max era year need cleaned up after sorting
- // Don't use the full English Era Name (names[2])
- //
- return new EraInfo( 0, year, month, day, year - 1, 1, 0,
- names[0], names[1], names[3]);
- }
-
- internal static volatile Calendar s_defaultInstance;
- internal GregorianCalendarHelper helper;
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
-
- internal static Calendar GetDefaultInstance() {
- if (s_defaultInstance == null) {
- s_defaultInstance = new JapaneseCalendar();
- }
- return (s_defaultInstance);
- }
-
-
- public JapaneseCalendar() {
- try {
- new CultureInfo("ja-JP");
- } catch (ArgumentException e) {
- throw new TypeInitializationException(this.GetType().FullName, e);
- }
- helper = new GregorianCalendarHelper(this, GetEraInfo());
- }
-
- internal override int ID {
- get {
- return (CAL_JAPAN);
- }
- }
-
-
- public override DateTime AddMonths(DateTime time, int months) {
- return (helper.AddMonths(time, months));
- }
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (helper.AddYears(time, years));
- }
-
- /*=================================GetDaysInMonth==========================
- **Action: Returns the number of days in the month given by the year and month arguments.
- **Returns: The number of days in the given month.
- **Arguments:
- ** year The year in Japanese calendar.
- ** month The month
- ** era The Japanese era value.
- **Exceptions
- ** ArgumentException If month is less than 1 or greater * than 12.
- ============================================================================*/
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- return (helper.GetDaysInMonth(year, month, era));
- }
-
-
- public override int GetDaysInYear(int year, int era) {
- return (helper.GetDaysInYear(year, era));
- }
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (helper.GetDayOfMonth(time));
- }
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return (helper.GetDayOfWeek(time));
- }
-
-
- public override int GetDayOfYear(DateTime time)
- {
- return (helper.GetDayOfYear(time));
- }
-
-
- public override int GetMonthsInYear(int year, int era)
- {
- return (helper.GetMonthsInYear(year, era));
- }
-
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
- {
- return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
- }
-
- /*=================================GetEra==========================
- **Action: Get the era value of the specified time.
- **Returns: The era value for the specified time.
- **Arguments:
- ** time the specified date time.
- **Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges.
- ============================================================================*/
-
-
- public override int GetEra(DateTime time) {
- return (helper.GetEra(time));
- }
-
-
- public override int GetMonth(DateTime time) {
- return (helper.GetMonth(time));
- }
-
-
- public override int GetYear(DateTime time) {
- return (helper.GetYear(time));
- }
-
-
- public override bool IsLeapDay(int year, int month, int day, int era)
- {
- return (helper.IsLeapDay(year, month, day, era));
- }
-
-
- public override bool IsLeapYear(int year, int era) {
- return (helper.IsLeapYear(year, era));
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era)
- {
- return (helper.GetLeapMonth(year, era));
- }
-
-
- public override bool IsLeapMonth(int year, int month, int era) {
- return (helper.IsLeapMonth(year, month, era));
- }
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
- }
-
- // For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years.
- // Therefore, for any two digit number, we just return the original number.
-
- public override int ToFourDigitYear(int year) {
- if (year <= 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- }
- Contract.EndContractBlock();
-
- if (year > helper.MaxYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- helper.MaxYear));
- }
- return (year);
- }
-
-
- public override int[] Eras {
- get {
- return (helper.Eras);
- }
- }
-
- //
- // Return the various era strings
- // Note: The arrays are backwards of the eras
- //
- internal static String[] EraNames()
- {
- EraInfo[] eras = GetEraInfo();
- String[] eraNames = new String[eras.Length];
-
- for (int i = 0; i < eras.Length; i++)
- {
- // Strings are in chronological order, eras are backwards order.
- eraNames[i] = eras[eras.Length - i - 1].eraName;
- }
-
- return eraNames;
- }
-
- internal static String[] AbbrevEraNames()
- {
- EraInfo[] eras = GetEraInfo();
- String[] erasAbbrev = new String[eras.Length];
-
- for (int i = 0; i < eras.Length; i++)
- {
- // Strings are in chronological order, eras are backwards order.
- erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName;
- }
-
- return erasAbbrev;
- }
-
- internal static String[] EnglishEraNames()
- {
- EraInfo[] eras = GetEraInfo();
- String[] erasEnglish = new String[eras.Length];
-
- for (int i = 0; i < eras.Length; i++)
- {
- // Strings are in chronological order, eras are backwards order.
- erasEnglish[i] = eras[eras.Length - i - 1].englishEraName;
- }
-
- return erasEnglish;
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
-
- internal override bool IsValidYear(int year, int era) {
- return helper.IsValidYear(year, era);
- }
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > helper.MaxYear)
- {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- helper.MaxYear));
- }
- twoDigitYearMax = value;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs
deleted file mode 100644
index 67cfb23833..0000000000
--- a/src/mscorlib/src/System/Globalization/JapaneseLunisolarCalendar.cs
+++ /dev/null
@@ -1,293 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about JapaneseLunisolarCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1960/01/28 2050/01/22
- ** JapaneseLunisolar 1960/01/01 2049/12/29
- */
-
- [Serializable]
- public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar {
-
- //
- // The era value for the current era.
- //
-
- public const int JapaneseEra = 1;
-
- internal GregorianCalendarHelper helper;
-
- internal const int MIN_LUNISOLAR_YEAR = 1960;
- internal const int MAX_LUNISOLAR_YEAR = 2049;
-
- internal const int MIN_GREGORIAN_YEAR = 1960;
- internal const int MIN_GREGORIAN_MONTH = 1;
- internal const int MIN_GREGORIAN_DAY = 28;
-
- internal const int MAX_GREGORIAN_YEAR = 2050;
- internal const int MAX_GREGORIAN_MONTH = 1;
- internal const int MAX_GREGORIAN_DAY = 22;
-
- internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
- internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (minDate);
- }
- }
-
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (maxDate);
- }
- }
- protected override int DaysInYearBeforeMinSupportedYear
- {
- get
- {
- // 1959 from ChineseLunisolarCalendar
- return 354;
- }
- }
-
- static readonly int [,] yinfo =
- {
-/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
-1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354
-1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
-1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
-1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355
-1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
-1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384
-1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
-1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385
-1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
-1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384
-2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354
-2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384
-2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
-2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
-2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
-2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355
-2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
-2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
-2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
-2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354
-2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
- */ };
-
- internal override int MinCalendarYear {
- get
- {
- return (MIN_LUNISOLAR_YEAR);
- }
- }
-
- internal override int MaxCalendarYear {
- get
- {
- return (MAX_LUNISOLAR_YEAR);
- }
- }
-
- internal override DateTime MinDate {
- get
- {
- return (minDate);
- }
- }
-
- internal override DateTime MaxDate {
- get
- {
- return (maxDate);
- }
- }
-
- internal override EraInfo[] CalEraInfo {
- get
- {
- return (JapaneseCalendar.GetEraInfo());
- }
- }
-
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MIN_LUNISOLAR_YEAR,
- MAX_LUNISOLAR_YEAR ));
- }
- Contract.EndContractBlock();
-
- return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
- }
-
- internal override int GetYear(int year, DateTime time) {
- return helper.GetYear(year, time);
- }
-
- internal override int GetGregorianYear(int year, int era) {
- return helper.GetGregorianYear(year, era);
- }
-
- // Trim off the eras that are before our date range
- private static EraInfo[] TrimEras(EraInfo[] baseEras)
- {
- EraInfo[] newEras = new EraInfo[baseEras.Length];
- int newIndex = 0;
-
- // Eras have most recent first, so start with that
- for (int i = 0; i < baseEras.Length; i++)
- {
- // If this one's minimum year is bigger than our maximum year
- // then we can't use it.
- if (baseEras[i].yearOffset + baseEras[i].minEraYear >= MAX_LUNISOLAR_YEAR)
- {
- // skip this one.
- continue;
- }
-
- // If this one's maximum era is less than our minimum era
- // then we've gotten too low in the era #s, so we're done
- if (baseEras[i].yearOffset + baseEras[i].maxEraYear < MIN_LUNISOLAR_YEAR)
- {
- break;
- }
-
- // Wasn't too large or too small, can use this one
- newEras[newIndex] = baseEras[i];
- newIndex++;
- }
-
- // If we didn't copy any then something was wrong, just return base
- if (newIndex == 0) return baseEras;
-
- // Resize the output array
- Array.Resize(ref newEras, newIndex);
- return newEras;
- }
-
-
- // Construct an instance of JapaneseLunisolar calendar.
- public JapaneseLunisolarCalendar()
- {
- helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo()));
- }
-
-
- public override int GetEra(DateTime time) {
- return (helper.GetEra(time));
- }
-
- internal override int BaseCalendarID {
- get {
- return (CAL_JAPAN);
- }
- }
-
- internal override int ID {
- get {
- return (CAL_JAPANESELUNISOLAR);
- }
- }
-
-
- public override int[] Eras {
- get {
- return (helper.Eras);
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/JulianCalendar.cs b/src/mscorlib/src/System/Globalization/JulianCalendar.cs
deleted file mode 100644
index ff8801433c..0000000000
--- a/src/mscorlib/src/System/Globalization/JulianCalendar.cs
+++ /dev/null
@@ -1,436 +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.
-
-namespace System.Globalization {
-
- using System;
- using System.Diagnostics.Contracts;
- //
- // This class implements the Julian calendar. In 48 B.C. Julius Caesar ordered a calendar reform, and this calendar
- // is called Julian calendar. It consisted of a solar year of twelve months and of 365 days with an extra day
- // every fourth year.
- //*
- //* Calendar support range:
- //* Calendar Minimum Maximum
- //* ========== ========== ==========
- //* Gregorian 0001/01/01 9999/12/31
- //* Julia 0001/01/03 9999/10/19
-
- [Serializable]
- public class JulianCalendar : Calendar {
-
-
- public static readonly int JulianEra = 1;
-
- private const int DatePartYear = 0;
- private const int DatePartDayOfYear = 1;
- private const int DatePartMonth = 2;
- private const int DatePartDay = 3;
-
- // Number of days in a non-leap year
- private const int JulianDaysPerYear = 365;
- // Number of days in 4 years
- private const int JulianDaysPer4Years = JulianDaysPerYear * 4 + 1;
-
- //internal static Calendar m_defaultInstance;
-
- private static readonly int[] DaysToMonth365 =
- {
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365
- };
-
- private static readonly int[] DaysToMonth366 =
- {
- 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366
- };
-
- // Gregorian Calendar 9999/12/31 = Julian Calendar 9999/10/19
- // keep it as variable field for serialization compat.
- internal int MaxYear = 9999;
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (DateTime.MinValue);
- }
- }
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (DateTime.MaxValue);
- }
- }
-
- // Return the type of the Julian calendar.
- //
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.SolarCalendar;
- }
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of JulianCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance() {
- if (m_defaultInstance == null) {
- m_defaultInstance = new JulianCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
- // Construct an instance of gregorian calendar.
-
- public JulianCalendar() {
- // There is no system setting of TwoDigitYear max, so set the value here.
- twoDigitYearMax = 2029;
- }
-
- internal override int ID {
- get {
- return (CAL_JULIAN);
- }
- }
-
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != JulianEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
- }
-
- internal void CheckYearEraRange(int year, int era) {
- CheckEraRange(era);
- if (year <= 0 || year > MaxYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxYear));
- }
- }
-
- static internal void CheckMonthRange(int month) {
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Check for if the day value is valid.
- **Returns:
- **Arguments:
- **Exceptions:
- **Notes:
- ** Before calling this method, call CheckYearEraRange()/CheckMonthRange() to make
- ** sure year/month values are correct.
- ============================================================================*/
-
- static internal void CheckDayRange(int year, int month, int day) {
- if (year == 1 && month == 1)
- {
- // The mimimum supported Julia date is Julian 0001/01/03.
- if (day < 3) {
- throw new ArgumentOutOfRangeException(null,
- Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
- }
- bool isLeapYear = (year % 4) == 0;
- int[] days = isLeapYear ? DaysToMonth366 : DaysToMonth365;
- int monthDays = days[month] - days[month - 1];
- if (day < 1 || day > monthDays) {
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- monthDays));
- }
- }
-
-
- // Returns a given date part of this DateTime. This method is used
- // to compute the year, day-of-year, month, or day part.
- static internal int GetDatePart(long ticks, int part)
- {
- // Gregorian 1/1/0001 is Julian 1/3/0001. Remember DateTime(0) is refered to Gregorian 1/1/0001.
- // The following line convert Gregorian ticks to Julian ticks.
- long julianTicks = ticks + TicksPerDay * 2;
- // n = number of days since 1/1/0001
- int n = (int)(julianTicks / TicksPerDay);
- // y4 = number of whole 4-year periods within 100-year period
- int y4 = n / JulianDaysPer4Years;
- // n = day number within 4-year period
- n -= y4 * JulianDaysPer4Years;
- // y1 = number of whole years within 4-year period
- int y1 = n / JulianDaysPerYear;
- // Last year has an extra day, so decrement result if 4
- if (y1 == 4) y1 = 3;
- // If year was requested, compute and return it
- if (part == DatePartYear)
- {
- return (y4 * 4 + y1 + 1);
- }
- // n = day number within year
- n -= y1 * JulianDaysPerYear;
- // If day-of-year was requested, return it
- if (part == DatePartDayOfYear)
- {
- return (n + 1);
- }
- // Leap year calculation looks different from IsLeapYear since y1, y4,
- // and y100 are relative to year 1, not year 0
- bool leapYear = (y1 == 3);
- int[] days = leapYear? DaysToMonth366: DaysToMonth365;
- // All months have less than 32 days, so n >> 5 is a good conservative
- // estimate for the month
- int m = (n >> 5) + 1;
- // m = 1-based month number
- while (n >= days[m]) m++;
- // If month was requested, return it
- if (part == DatePartMonth) return (m);
- // Return 1-based day-of-month
- return (n - days[m - 1] + 1);
- }
-
- // Returns the tick count corresponding to the given year, month, and day.
- static internal long DateToTicks(int year, int month, int day)
- {
- int[] days = (year % 4 == 0)? DaysToMonth366: DaysToMonth365;
- int y = year - 1;
- int n = y * 365 + y / 4 + days[month - 1] + day - 1;
- // Gregorian 1/1/0001 is Julian 1/3/0001. n * TicksPerDay is the ticks in JulianCalendar.
- // Therefore, we subtract two days in the following to convert the ticks in JulianCalendar
- // to ticks in Gregorian calendar.
- return ((n - 2) * TicksPerDay);
- }
-
-
- public override DateTime AddMonths(DateTime time, int months)
- {
- if (months < -120000 || months > 120000) {
- throw new ArgumentOutOfRangeException(
- nameof(months),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- -120000,
- 120000));
- }
- Contract.EndContractBlock();
- int y = GetDatePart(time.Ticks, DatePartYear);
- int m = GetDatePart(time.Ticks, DatePartMonth);
- int d = GetDatePart(time.Ticks, DatePartDay);
- int i = m - 1 + months;
- if (i >= 0) {
- m = i % 12 + 1;
- y = y + i / 12;
- }
- else {
- m = 12 + (i + 1) % 12;
- y = y + (i - 11) / 12;
- }
- int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366: DaysToMonth365;
- int days = (daysArray[m] - daysArray[m - 1]);
-
- if (d > days) {
- d = days;
- }
- long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay;
- Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (new DateTime(ticks));
- }
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (AddMonths(time, years * 12));
- }
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDay));
- }
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
- }
-
-
- public override int GetDayOfYear(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDayOfYear));
- }
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- CheckYearEraRange(year, era);
- CheckMonthRange(month);
- int[] days = (year % 4 == 0) ? DaysToMonth366: DaysToMonth365;
- return (days[month] - days[month - 1]);
- }
-
-
- public override int GetDaysInYear(int year, int era) {
- // Year/Era range is done in IsLeapYear().
- return (IsLeapYear(year, era) ? 366:365);
- }
-
-
- public override int GetEra(DateTime time)
- {
- return (JulianEra);
- }
-
-
- public override int GetMonth(DateTime time)
- {
- return (GetDatePart(time.Ticks, DatePartMonth));
- }
-
-
- public override int[] Eras {
- get {
- return (new int[] {JulianEra});
- }
- }
-
-
- public override int GetMonthsInYear(int year, int era)
- {
- CheckYearEraRange(year, era);
- return (12);
- }
-
-
- public override int GetYear(DateTime time)
- {
- return (GetDatePart(time.Ticks, DatePartYear));
- }
-
-
- public override bool IsLeapDay(int year, int month, int day, int era)
- {
- CheckMonthRange(month);
- // Year/Era range check is done in IsLeapYear().
- if (IsLeapYear(year, era)) {
- CheckDayRange(year, month, day);
- return (month == 2 && day == 29);
- }
- CheckDayRange(year, month, day);
- return (false);
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era)
- {
- CheckYearEraRange(year, era);
- return (0);
- }
-
-
- public override bool IsLeapMonth(int year, int month, int era)
- {
- CheckYearEraRange(year, era);
- CheckMonthRange(month);
- return (false);
- }
-
- // Checks whether a given year in the specified era is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
-
- public override bool IsLeapYear(int year, int era)
- {
- CheckYearEraRange(year, era);
- return (year % 4 == 0);
- }
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era)
- {
- CheckYearEraRange(year, era);
- CheckMonthRange(month);
- CheckDayRange(year, month, day);
- if (millisecond < 0 || millisecond >= MillisPerSecond) {
- throw new ArgumentOutOfRangeException(
- nameof(millisecond),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 0,
- MillisPerSecond - 1));
- }
-
- if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >=0 && second < 60)
- {
- return new DateTime(DateToTicks(year, month, day) + (new TimeSpan(0, hour, minute, second, millisecond)).Ticks);
- } else
- {
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"));
- }
- }
-
-
- public override int TwoDigitYearMax {
- get {
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > MaxYear)
- {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- MaxYear));
-
- }
- twoDigitYearMax = value;
- }
- }
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- if (year > MaxYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"),
- 1,
- MaxYear));
- }
- return (base.ToFourDigitYear(year));
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
deleted file mode 100644
index 6c5a03b7e8..0000000000
--- a/src/mscorlib/src/System/Globalization/KoreanCalendar.cs
+++ /dev/null
@@ -1,259 +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.
-
-namespace System.Globalization {
-
- using System;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
-
- /*=================================KoreanCalendar==========================
- **
- ** Korean calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
- ** That is,
- ** Korean year = Gregorian year + 2333. So 2000/01/01 A.D. is Korean 4333/01/01
- **
- ** 0001/1/1 A.D. is Korean year 2334.
- **
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 0001/01/01 9999/12/31
- ** Korean 2334/01/01 12332/12/31
- ============================================================================*/
-
-
- [Serializable] public class KoreanCalendar: Calendar {
- //
- // The era value for the current era.
- //
-
- public const int KoreanEra = 1;
-
- // Since
- // Gregorian Year = Era Year + yearOffset
- // Gregorian Year 1 is Korean year 2334, so that
- // 1 = 2334 + yearOffset
- // So yearOffset = -2333
- // Gregorian year 2001 is Korean year 4334.
-
- //m_EraInfo[0] = new EraInfo(1, new DateTime(1, 1, 1).Ticks, -2333, 2334, GregorianCalendar.MaxYear + 2333);
-
- // Initialize our era info.
- static internal EraInfo[] koreanEraInfo = new EraInfo[] {
- new EraInfo( 1, 1, 1, 1, -2333, 2334, GregorianCalendar.MaxYear + 2333) // era #, start year/month/day, yearOffset, minEraYear
- };
-
- internal GregorianCalendarHelper helper;
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (DateTime.MinValue);
- }
- }
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (DateTime.MaxValue);
- }
- }
-
- // Return the type of the Korean calendar.
- //
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.SolarCalendar;
- }
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of KoreanCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance() {
- if (m_defaultInstance == null) {
- m_defaultInstance = new KoreanCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
-
- public KoreanCalendar() {
- try {
- new CultureInfo("ko-KR");
- } catch (ArgumentException e) {
- throw new TypeInitializationException(this.GetType().FullName, e);
- }
- helper = new GregorianCalendarHelper(this, koreanEraInfo);
- }
-
- internal override int ID {
- get {
- return (CAL_KOREA);
- }
- }
-
-
- public override DateTime AddMonths(DateTime time, int months) {
- return (helper.AddMonths(time, months));
- }
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (helper.AddYears(time, years));
- }
-
- /*=================================GetDaysInMonth==========================
- **Action: Returns the number of days in the month given by the year and month arguments.
- **Returns: The number of days in the given month.
- **Arguments:
- ** year The year in Korean calendar.
- ** month The month
- ** era The Japanese era value.
- **Exceptions
- ** ArgumentException If month is less than 1 or greater * than 12.
- ============================================================================*/
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- return (helper.GetDaysInMonth(year, month, era));
- }
-
-
- public override int GetDaysInYear(int year, int era) {
- return (helper.GetDaysInYear(year, era));
- }
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (helper.GetDayOfMonth(time));
- }
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return (helper.GetDayOfWeek(time));
- }
-
-
- public override int GetDayOfYear(DateTime time)
- {
- return (helper.GetDayOfYear(time));
- }
-
-
- public override int GetMonthsInYear(int year, int era) {
- return (helper.GetMonthsInYear(year, era));
- }
-
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
- {
- return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
- }
-
-
- public override int GetEra(DateTime time) {
- return (helper.GetEra(time));
- }
-
- public override int GetMonth(DateTime time) {
- return (helper.GetMonth(time));
- }
-
-
- public override int GetYear(DateTime time) {
- return (helper.GetYear(time));
- }
-
-
- public override bool IsLeapDay(int year, int month, int day, int era)
- {
- return (helper.IsLeapDay(year, month, day, era));
- }
-
-
- public override bool IsLeapYear(int year, int era) {
- return (helper.IsLeapYear(year, era));
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era)
- {
- return (helper.GetLeapMonth(year, era));
- }
-
-
- public override bool IsLeapMonth(int year, int month, int era) {
- return (helper.IsLeapMonth(year, month, era));
- }
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
- }
-
-
- public override int[] Eras {
- get {
- return (helper.Eras);
- }
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 4362;
-
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > helper.MaxYear)
- {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- helper.MaxYear));
-
- }
- twoDigitYearMax = value;
- }
- }
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
deleted file mode 100644
index 9e36b435e7..0000000000
--- a/src/mscorlib/src/System/Globalization/KoreanLunisolarCalendar.cs
+++ /dev/null
@@ -1,1334 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about KoreanLunisolarCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 918/02/14 2051/02/10
- ** KoreanLunisolar 918/01/01 2050/13/29
- */
-
- [Serializable]
- public class KoreanLunisolarCalendar : EastAsianLunisolarCalendar {
-
-
- //
- // The era value for the current era.
- //
-
- public const int GregorianEra = 1;
-
- //internal static Calendar m_defaultInstance;
-
- internal const int MIN_LUNISOLAR_YEAR = 918;
- internal const int MAX_LUNISOLAR_YEAR = 2050;
-
- internal const int MIN_GREGORIAN_YEAR = 918;
- internal const int MIN_GREGORIAN_MONTH = 2;
- internal const int MIN_GREGORIAN_DAY = 14;
-
- internal const int MAX_GREGORIAN_YEAR = 2051;
- internal const int MAX_GREGORIAN_MONTH = 2;
- internal const int MAX_GREGORIAN_DAY = 10;
-
- internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
- internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
-
- public override DateTime MinSupportedDateTime {
- get
- {
- return (minDate);
- }
- }
-
-
-
- public override DateTime MaxSupportedDateTime {
- get
- {
- return (maxDate);
- }
- }
-
- protected override int DaysInYearBeforeMinSupportedYear
- {
- get
- {
- // 917 -- From http://emr.cs.iit.edu/home/reingold/calendar-book/Calendrica.html
- // using ChineseLunisolar
- return 384;
- }
- }
-
- static readonly int [,] yinfo =
- {
-/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
-918 */{ 0 , 2 , 14 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-919 */{ 0 , 2 , 4 , 17872 },/* 29 30 29 29 29 30 29 30 30 30 29 30 0 354
-920 */{ 6 , 1 , 24 , 41688 },/* 30 29 30 29 29 29 30 29 30 30 29 30 30 384
-921 */{ 0 , 2 , 11 , 41648 },/* 30 29 30 29 29 29 30 29 30 29 30 30 0 354
-922 */{ 0 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-923 */{ 4 , 1 , 20 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-924 */{ 0 , 2 , 8 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
-925 */{ 12 , 1 , 27 , 44384 },/* 30 29 30 29 30 30 29 30 29 30 30 29 29 384
-926 */{ 0 , 2 , 15 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-927 */{ 0 , 2 , 5 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-928 */{ 8 , 1 , 26 , 17848 },/* 29 30 29 29 29 30 29 30 30 29 30 30 30 384
-929 */{ 0 , 2 , 13 , 17776 },/* 29 30 29 29 29 30 29 30 29 30 30 30 0 354
-930 */{ 0 , 2 , 2 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-931 */{ 5 , 1 , 22 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 29 383
-932 */{ 0 , 2 , 9 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
-933 */{ 0 , 1 , 29 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-934 */{ 1 , 1 , 18 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-935 */{ 0 , 2 , 6 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-936 */{ 11 , 1 , 27 , 21344 },/* 29 30 29 30 29 29 30 30 29 30 30 29 29 383
-937 */{ 0 , 2 , 13 , 51904 },/* 30 30 29 29 30 29 30 29 30 30 29 29 0 354
-938 */{ 0 , 2 , 2 , 58720 },/* 30 30 30 29 29 30 29 30 29 30 30 29 0 355
-939 */{ 7 , 1 , 23 , 53928 },/* 30 30 29 30 29 29 30 29 30 29 30 29 30 384
-940 */{ 0 , 2 , 11 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-941 */{ 0 , 1 , 30 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-942 */{ 3 , 1 , 20 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-943 */{ 0 , 2 , 8 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-944 */{ 12 , 1 , 28 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 29 384
-945 */{ 0 , 2 , 15 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-946 */{ 0 , 2 , 5 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
-947 */{ 7 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-948 */{ 0 , 2 , 13 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-949 */{ 0 , 2 , 1 , 45664 },/* 30 29 30 30 29 29 30 29 29 30 30 29 0 354
-950 */{ 5 , 1 , 21 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-951 */{ 0 , 2 , 9 , 45936 },/* 30 29 30 30 29 30 29 30 29 30 29 0 0 325
-952 */{ 0 , 12 , 31 , 43728 },/* 30 29 30 29 30 29 30 29 30 30 29 30 29 384
-953 */{ 1 , 1 , 18 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 29 384
-954 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-955 */{ 9 , 1 , 27 , 19128 },/* 29 30 29 29 30 29 30 29 30 29 30 30 30 384
-956 */{ 0 , 2 , 15 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-957 */{ 0 , 2 , 3 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-958 */{ 7 , 1 , 23 , 43672 },/* 30 29 30 29 30 29 30 29 30 29 29 30 30 384
-959 */{ 0 , 2 , 11 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-960 */{ 0 , 1 , 31 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-961 */{ 3 , 1 , 20 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
-962 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-963 */{ 12 , 1 , 28 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 29 384
-964 */{ 0 , 2 , 16 , 41840 },/* 30 29 30 29 29 29 30 30 29 30 30 30 0 355
-965 */{ 0 , 2 , 5 , 20848 },/* 29 30 29 30 29 29 29 30 29 30 30 30 0 354
-966 */{ 8 , 1 , 25 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-967 */{ 0 , 2 , 12 , 54448 },/* 30 30 29 30 29 30 29 29 30 29 30 30 0 355
-968 */{ 0 , 2 , 2 , 23184 },/* 29 30 29 30 30 29 30 29 30 29 29 30 0 354
-969 */{ 5 , 1 , 21 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
-970 */{ 0 , 2 , 9 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-971 */{ 0 , 1 , 30 , 10976 },/* 29 29 30 29 30 29 30 29 30 30 30 29 0 354
-972 */{ 2 , 1 , 19 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-973 */{ 0 , 2 , 6 , 41696 },/* 30 29 30 29 29 29 30 29 30 30 30 29 0 354
-974 */{ 10 , 1 , 26 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-975 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-976 */{ 0 , 2 , 3 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-977 */{ 7 , 1 , 22 , 55952 },/* 30 30 29 30 30 29 30 29 30 29 29 30 29 384
-978 */{ 0 , 2 , 10 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
-979 */{ 0 , 1 , 31 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-980 */{ 3 , 1 , 21 , 10968 },/* 29 29 30 29 30 29 30 29 30 30 29 30 30 384
-981 */{ 0 , 2 , 8 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-982 */{ 12 , 1 , 28 , 37592 },/* 30 29 29 30 29 29 30 29 30 30 29 30 30 384
-983 */{ 0 , 2 , 16 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-984 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-985 */{ 9 , 1 , 24 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-986 */{ 0 , 2 , 12 , 44192 },/* 30 29 30 29 30 30 29 29 30 29 30 29 0 354
-987 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-988 */{ 5 , 1 , 22 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-989 */{ 0 , 2 , 9 , 19376 },/* 29 30 29 29 30 29 30 30 30 29 30 30 0 355
-990 */{ 0 , 1 , 30 , 9648 },/* 29 29 30 29 29 30 29 30 30 29 30 30 0 354
-991 */{ 2 , 1 , 19 , 37560 },/* 30 29 29 30 29 29 30 29 30 29 30 30 30 384
-992 */{ 0 , 2 , 7 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-993 */{ 10 , 1 , 26 , 26968 },/* 29 30 30 29 30 29 29 30 29 30 29 30 30 384
-994 */{ 0 , 2 , 14 , 22864 },/* 29 30 29 30 30 29 29 30 29 30 29 30 0 354
-995 */{ 0 , 2 , 3 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-996 */{ 7 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
-997 */{ 0 , 2 , 10 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-998 */{ 0 , 1 , 31 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-999 */{ 3 , 1 , 20 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1000 */{ 0 , 2 , 8 , 9584 },/* 29 29 30 29 29 30 29 30 29 30 30 30 0 354
-1001 */{ 12 , 1 , 28 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 29 383
-1002 */{ 0 , 2 , 15 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-1003 */{ 0 , 2 , 4 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1004 */{ 9 , 1 , 25 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1005 */{ 0 , 2 , 12 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1006 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1007 */{ 5 , 1 , 22 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1008 */{ 0 , 2 , 10 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
-1009 */{ 0 , 1 , 29 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1010 */{ 2 , 1 , 18 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1011 */{ 0 , 2 , 6 , 45664 },/* 30 29 30 30 29 29 30 29 29 30 30 29 0 354
-1012 */{ 10 , 1 , 26 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1013 */{ 0 , 2 , 13 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1014 */{ 0 , 2 , 3 , 13728 },/* 29 29 30 30 29 30 29 30 30 29 30 29 0 354
-1015 */{ 6 , 1 , 23 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 29 384
-1016 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1017 */{ 0 , 1 , 31 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1018 */{ 4 , 1 , 20 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1019 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1020 */{ 12 , 1 , 28 , 43608 },/* 30 29 30 29 30 29 30 29 29 30 29 30 30 384
-1021 */{ 0 , 2 , 15 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1022 */{ 0 , 2 , 4 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1023 */{ 9 , 1 , 25 , 11688 },/* 29 29 30 29 30 30 29 30 30 29 30 29 30 384
-1024 */{ 0 , 2 , 13 , 11088 },/* 29 29 30 29 30 29 30 30 29 30 29 30 0 354
-1025 */{ 0 , 2 , 1 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
-1026 */{ 5 , 1 , 22 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 29 383
-1027 */{ 0 , 2 , 9 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 0 355
-1028 */{ 0 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1029 */{ 2 , 1 , 18 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1030 */{ 0 , 2 , 5 , 55952 },/* 30 30 29 30 30 29 30 29 30 29 29 30 0 355
-1031 */{ 10 , 1 , 26 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
-1032 */{ 0 , 2 , 14 , 26320 },/* 29 30 30 29 29 30 30 29 30 30 29 30 0 355
-1033 */{ 0 , 2 , 3 , 9952 },/* 29 29 30 29 29 30 30 29 30 30 30 29 0 354
-1034 */{ 6 , 1 , 23 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-1035 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1036 */{ 0 , 1 , 31 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1037 */{ 4 , 1 , 19 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1038 */{ 0 , 2 , 7 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1039 */{ 12 , 1 , 27 , 54928 },/* 30 30 29 30 29 30 30 29 30 29 29 30 29 384
-1040 */{ 0 , 2 , 15 , 46464 },/* 30 29 30 30 29 30 29 30 30 29 29 29 0 354
-1041 */{ 0 , 2 , 3 , 54960 },/* 30 30 29 30 29 30 30 29 30 29 30 30 0 356
-1042 */{ 9 , 1 , 25 , 9944 },/* 29 29 30 29 29 30 30 29 30 30 29 30 30 384
-1043 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1044 */{ 0 , 2 , 2 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-1045 */{ 5 , 1 , 21 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1046 */{ 0 , 2 , 9 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1047 */{ 0 , 1 , 29 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1048 */{ 1 , 1 , 18 , 46424 },/* 30 29 30 30 29 30 29 30 29 30 29 30 30 385
-1049 */{ 0 , 2 , 6 , 11600 },/* 29 29 30 29 30 30 29 30 29 30 29 30 0 354
-1050 */{ 11 , 1 , 26 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-1051 */{ 0 , 2 , 14 , 19376 },/* 29 30 29 29 30 29 30 30 30 29 30 30 0 355
-1052 */{ 0 , 2 , 4 , 9648 },/* 29 29 30 29 29 30 29 30 30 29 30 30 0 354
-1053 */{ 7 , 1 , 23 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1054 */{ 0 , 2 , 11 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1055 */{ 0 , 1 , 31 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1056 */{ 3 , 1 , 20 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1057 */{ 0 , 2 , 7 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1058 */{ 12 , 1 , 27 , 43864 },/* 30 29 30 29 30 29 30 30 29 30 29 30 30 385
-1059 */{ 0 , 2 , 16 , 10064 },/* 29 29 30 29 29 30 30 30 29 30 29 30 0 354
-1060 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1061 */{ 8 , 1 , 24 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1062 */{ 0 , 2 , 12 , 42336 },/* 30 29 30 29 29 30 29 30 29 30 30 29 0 354
-1063 */{ 0 , 2 , 1 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1064 */{ 5 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1065 */{ 0 , 2 , 8 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1066 */{ 0 , 1 , 29 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1067 */{ 1 , 1 , 18 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
-1068 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1069 */{ 11 , 1 , 26 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1070 */{ 0 , 2 , 14 , 18896 },/* 29 30 29 29 30 29 29 30 30 30 29 30 0 354
-1071 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1072 */{ 7 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1073 */{ 0 , 2 , 10 , 43616 },/* 30 29 30 29 30 29 30 29 29 30 30 29 0 354
-1074 */{ 0 , 1 , 30 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1075 */{ 4 , 1 , 20 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1076 */{ 0 , 2 , 8 , 13728 },/* 29 29 30 30 29 30 29 30 30 29 30 29 0 354
-1077 */{ 0 , 1 , 27 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1078 */{ 1 , 1 , 17 , 19352 },/* 29 30 29 29 30 29 30 30 30 29 29 30 30 384
-1079 */{ 0 , 2 , 5 , 17840 },/* 29 30 29 29 29 30 29 30 30 29 30 30 0 354
-1080 */{ 9 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1081 */{ 0 , 2 , 12 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1082 */{ 0 , 2 , 1 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1083 */{ 6 , 1 , 21 , 46408 },/* 30 29 30 30 29 30 29 30 29 30 29 29 30 384
-1084 */{ 0 , 2 , 9 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 0 355
-1085 */{ 0 , 1 , 29 , 11680 },/* 29 29 30 29 30 30 29 30 30 29 30 29 0 354
-1086 */{ 2 , 1 , 18 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 29 384
-1087 */{ 0 , 2 , 6 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1088 */{ 12 , 1 , 27 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 29 383
-1089 */{ 0 , 2 , 13 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 0 355
-1090 */{ 0 , 2 , 3 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1091 */{ 8 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1092 */{ 0 , 2 , 10 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-1093 */{ 0 , 1 , 30 , 23360 },/* 29 30 29 30 30 29 30 30 29 30 29 29 0 354
-1094 */{ 4 , 1 , 19 , 43880 },/* 30 29 30 29 30 29 30 30 29 30 30 29 30 385
-1095 */{ 0 , 2 , 8 , 10976 },/* 29 29 30 29 30 29 30 29 30 30 30 29 0 354
-1096 */{ 0 , 1 , 28 , 58896 },/* 30 30 30 29 29 30 30 29 29 29 29 30 0 354
-1097 */{ 2 , 1 , 16 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 29 384
-1098 */{ 0 , 2 , 4 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1099 */{ 9 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1100 */{ 0 , 2 , 12 , 21664 },/* 29 30 29 30 29 30 29 29 30 29 30 29 0 353
-1101 */{ 0 , 1 , 31 , 54864 },/* 30 30 29 30 29 30 30 29 29 30 29 30 0 355
-1102 */{ 6 , 1 , 21 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1103 */{ 0 , 2 , 9 , 21968 },/* 29 30 29 30 29 30 29 30 30 30 29 30 0 355
-1104 */{ 0 , 1 , 30 , 9936 },/* 29 29 30 29 29 30 30 29 30 30 29 30 0 354
-1105 */{ 2 , 1 , 18 , 37608 },/* 30 29 29 30 29 29 30 29 30 30 30 29 30 384
-1106 */{ 0 , 2 , 6 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-1107 */{ 10 , 1 , 26 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1108 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1109 */{ 0 , 2 , 2 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1110 */{ 8 , 1 , 22 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1111 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1112 */{ 0 , 1 , 31 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1113 */{ 4 , 1 , 20 , 9656 },/* 29 29 30 29 29 30 29 30 30 29 30 30 30 384
-1114 */{ 0 , 2 , 8 , 17776 },/* 29 30 29 29 29 30 29 30 29 30 30 30 0 354
-1115 */{ 0 , 1 , 28 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1116 */{ 1 , 1 , 17 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1117 */{ 0 , 2 , 4 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1118 */{ 9 , 1 , 24 , 29352 },/* 29 30 30 30 29 29 30 29 30 29 30 29 30 384
-1119 */{ 0 , 2 , 12 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1120 */{ 0 , 2 , 1 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1121 */{ 5 , 1 , 21 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1122 */{ 0 , 2 , 9 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1123 */{ 0 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1124 */{ 3 , 1 , 19 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 29 383
-1125 */{ 0 , 2 , 5 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1126 */{ 11 , 1 , 25 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1127 */{ 0 , 2 , 13 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1128 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1129 */{ 8 , 1 , 22 , 39824 },/* 30 29 29 30 30 29 30 30 30 29 29 30 29 384
-1130 */{ 0 , 2 , 10 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1131 */{ 0 , 1 , 31 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1132 */{ 4 , 1 , 20 , 42216 },/* 30 29 30 29 29 30 29 29 30 30 30 29 30 384
-1133 */{ 0 , 2 , 7 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1134 */{ 0 , 1 , 27 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1135 */{ 2 , 1 , 16 , 55592 },/* 30 30 29 30 30 29 29 30 29 29 30 29 30 384
-1136 */{ 0 , 2 , 4 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1137 */{ 10 , 1 , 23 , 54952 },/* 30 30 29 30 29 30 30 29 30 29 30 29 30 385
-1138 */{ 0 , 2 , 12 , 11680 },/* 29 29 30 29 30 30 29 30 30 29 30 29 0 354
-1139 */{ 0 , 2 , 1 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1140 */{ 6 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-1141 */{ 0 , 2 , 9 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1142 */{ 0 , 1 , 29 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1143 */{ 4 , 1 , 18 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1144 */{ 0 , 2 , 6 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1145 */{ 11 , 1 , 25 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-1146 */{ 0 , 2 , 13 , 27456 },/* 29 30 30 29 30 29 30 30 29 30 29 29 0 354
-1147 */{ 0 , 2 , 2 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1148 */{ 8 , 1 , 23 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 29 384
-1149 */{ 0 , 2 , 10 , 39280 },/* 30 29 29 30 30 29 29 30 29 30 30 30 0 355
-1150 */{ 0 , 1 , 31 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1151 */{ 4 , 1 , 20 , 25784 },/* 29 30 30 29 29 30 29 29 30 29 30 30 30 384
-1152 */{ 0 , 2 , 8 , 21680 },/* 29 30 29 30 29 30 29 29 30 29 30 30 0 354
-1153 */{ 12 , 1 , 27 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1154 */{ 0 , 2 , 14 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-1155 */{ 0 , 2 , 4 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
-1156 */{ 10 , 1 , 24 , 43880 },/* 30 29 30 29 30 29 30 30 29 30 30 29 30 385
-1157 */{ 0 , 2 , 12 , 9952 },/* 29 29 30 29 29 30 30 29 30 30 30 29 0 354
-1158 */{ 0 , 2 , 1 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1159 */{ 6 , 1 , 21 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 29 384
-1160 */{ 0 , 2 , 9 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1161 */{ 0 , 1 , 28 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1162 */{ 2 , 1 , 17 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1163 */{ 0 , 2 , 5 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1164 */{ 11 , 1 , 26 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1165 */{ 0 , 2 , 13 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1166 */{ 0 , 2 , 3 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1167 */{ 7 , 1 , 23 , 37608 },/* 30 29 29 30 29 29 30 29 30 30 30 29 30 384
-1168 */{ 0 , 2 , 11 , 37488 },/* 30 29 29 30 29 29 30 29 29 30 30 30 0 354
-1169 */{ 0 , 1 , 30 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1170 */{ 5 , 1 , 19 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1171 */{ 0 , 2 , 7 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1172 */{ 0 , 1 , 27 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1173 */{ 1 , 1 , 16 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1174 */{ 0 , 2 , 4 , 19888 },/* 29 30 29 29 30 30 29 30 30 29 30 30 0 355
-1175 */{ 9 , 1 , 25 , 9648 },/* 29 29 30 29 29 30 29 30 30 29 30 30 29 383
-1176 */{ 0 , 2 , 12 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1177 */{ 0 , 2 , 1 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1178 */{ 6 , 1 , 21 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1179 */{ 0 , 2 , 9 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1180 */{ 0 , 1 , 29 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1181 */{ 3 , 1 , 17 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1182 */{ 0 , 2 , 5 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1183 */{ 11 , 1 , 26 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1184 */{ 0 , 2 , 14 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1185 */{ 0 , 2 , 2 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1186 */{ 7 , 1 , 23 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 29 383
-1187 */{ 0 , 2 , 10 , 53392 },/* 30 30 29 30 29 29 30 29 29 30 30 0 0 325
-1188 */{ 0 , 1 , 1 , 29848 },/* 29 30 30 30 29 30 29 29 30 29 29 30 30 384
-1189 */{ 5 , 1 , 19 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1190 */{ 0 , 2 , 7 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1191 */{ 0 , 1 , 27 , 39760 },/* 30 29 29 30 30 29 30 30 29 30 29 30 0 355
-1192 */{ 2 , 1 , 17 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1193 */{ 0 , 2 , 4 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1194 */{ 10 , 1 , 24 , 42216 },/* 30 29 30 29 29 30 29 29 30 30 30 29 30 384
-1195 */{ 0 , 2 , 12 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1196 */{ 0 , 2 , 1 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1197 */{ 6 , 1 , 20 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1198 */{ 0 , 2 , 8 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1199 */{ 0 , 1 , 28 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
-1200 */{ 2 , 1 , 18 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 29 384
-1201 */{ 0 , 2 , 5 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1202 */{ 12 , 1 , 26 , 18904 },/* 29 30 29 29 30 29 29 30 30 30 29 30 30 384
-1203 */{ 0 , 2 , 14 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1204 */{ 0 , 2 , 3 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1205 */{ 8 , 1 , 22 , 43608 },/* 30 29 30 29 30 29 30 29 29 30 29 30 30 384
-1206 */{ 0 , 2 , 10 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1207 */{ 0 , 1 , 30 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1208 */{ 4 , 1 , 19 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 29 384
-1209 */{ 0 , 2 , 6 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1210 */{ 0 , 1 , 27 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1211 */{ 2 , 1 , 17 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1212 */{ 0 , 2 , 5 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1213 */{ 9 , 1 , 24 , 25784 },/* 29 30 30 29 29 30 29 29 30 29 30 30 30 384
-1214 */{ 0 , 2 , 12 , 21680 },/* 29 30 29 30 29 30 29 29 30 29 30 30 0 354
-1215 */{ 0 , 2 , 1 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1216 */{ 7 , 1 , 21 , 27944 },/* 29 30 30 29 30 30 29 30 29 29 30 29 30 384
-1217 */{ 0 , 2 , 8 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
-1218 */{ 0 , 1 , 28 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1219 */{ 3 , 1 , 18 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-1220 */{ 0 , 2 , 6 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1221 */{ 12 , 1 , 25 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 29 384
-1222 */{ 0 , 2 , 13 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1223 */{ 0 , 2 , 2 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1224 */{ 8 , 1 , 22 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1225 */{ 0 , 2 , 9 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1226 */{ 0 , 1 , 30 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1227 */{ 5 , 1 , 19 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-1228 */{ 0 , 2 , 8 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1229 */{ 0 , 1 , 27 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1230 */{ 2 , 1 , 16 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-1231 */{ 0 , 2 , 4 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1232 */{ 9 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1233 */{ 0 , 2 , 11 , 45728 },/* 30 29 30 30 29 29 30 29 30 29 30 29 0 354
-1234 */{ 0 , 1 , 31 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1235 */{ 7 , 1 , 21 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1236 */{ 0 , 2 , 9 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
-1237 */{ 0 , 1 , 28 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-1238 */{ 4 , 1 , 18 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1239 */{ 0 , 2 , 6 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1240 */{ 12 , 1 , 26 , 43320 },/* 30 29 30 29 30 29 29 30 29 29 30 30 30 384
-1241 */{ 0 , 2 , 13 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 0 354
-1242 */{ 0 , 2 , 2 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1243 */{ 8 , 1 , 22 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1244 */{ 0 , 2 , 10 , 44624 },/* 30 29 30 29 30 30 30 29 29 30 29 30 0 355
-1245 */{ 0 , 1 , 30 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1246 */{ 4 , 1 , 19 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1247 */{ 0 , 2 , 7 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1248 */{ 0 , 1 , 28 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
-1249 */{ 2 , 1 , 16 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
-1250 */{ 0 , 2 , 3 , 58672 },/* 30 30 30 29 29 30 29 30 29 29 30 30 0 355
-1251 */{ 10 , 1 , 24 , 27800 },/* 29 30 30 29 30 30 29 29 30 29 29 30 30 384
-1252 */{ 0 , 2 , 12 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1253 */{ 0 , 1 , 31 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1254 */{ 6 , 1 , 21 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1255 */{ 0 , 2 , 9 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1256 */{ 0 , 1 , 29 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
-1257 */{ 4 , 1 , 17 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1258 */{ 0 , 2 , 5 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1259 */{ 11 , 1 , 25 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1260 */{ 0 , 2 , 13 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1261 */{ 0 , 2 , 1 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
-1262 */{ 9 , 1 , 22 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 29 384
-1263 */{ 0 , 2 , 10 , 21872 },/* 29 30 29 30 29 30 29 30 29 30 30 30 0 355
-1264 */{ 0 , 1 , 31 , 18896 },/* 29 30 29 29 30 29 29 30 30 30 29 30 0 354
-1265 */{ 5 , 1 , 19 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1266 */{ 0 , 2 , 7 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1267 */{ 0 , 1 , 27 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1268 */{ 1 , 1 , 16 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-1269 */{ 0 , 2 , 3 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1270 */{ 11 , 1 , 23 , 46528 },/* 30 29 30 30 29 30 29 30 30 30 29 29 29 384
-1271 */{ 0 , 2 , 11 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1272 */{ 0 , 2 , 1 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1273 */{ 6 , 1 , 21 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1274 */{ 0 , 2 , 9 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1275 */{ 0 , 1 , 29 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1276 */{ 3 , 1 , 18 , 27224 },/* 29 30 30 29 30 29 30 29 29 30 29 30 30 384
-1277 */{ 0 , 2 , 5 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1278 */{ 11 , 1 , 25 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
-1279 */{ 0 , 2 , 13 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
-1280 */{ 0 , 2 , 2 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1281 */{ 8 , 1 , 22 , 10984 },/* 29 29 30 29 30 29 30 29 30 30 30 29 30 384
-1282 */{ 0 , 2 , 10 , 18912 },/* 29 30 29 29 30 29 29 30 30 30 30 29 0 354
-1283 */{ 0 , 1 , 30 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1284 */{ 5 , 1 , 19 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
-1285 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354
-1286 */{ 0 , 1 , 26 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1287 */{ 2 , 1 , 15 , 62096 },/* 30 30 30 30 29 29 30 29 30 29 29 30 29 384
-1288 */{ 0 , 2 , 3 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
-1289 */{ 10 , 1 , 23 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 29 384
-1290 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1291 */{ 0 , 2 , 1 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1292 */{ 6 , 1 , 21 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1293 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1294 */{ 0 , 1 , 28 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1295 */{ 4 , 1 , 17 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-1296 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1297 */{ 12 , 1 , 24 , 44384 },/* 30 29 30 29 30 30 29 30 29 30 30 29 29 384
-1298 */{ 0 , 2 , 12 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1299 */{ 0 , 2 , 2 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1300 */{ 8 , 1 , 23 , 2424 },/* 29 29 29 29 30 29 29 30 29 30 30 30 30 383
-1301 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1302 */{ 0 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1303 */{ 5 , 1 , 19 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1304 */{ 0 , 2 , 6 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-1305 */{ 0 , 1 , 26 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1306 */{ 1 , 1 , 15 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 29 384
-1307 */{ 0 , 2 , 3 , 42720 },/* 30 29 30 29 29 30 30 29 30 30 30 29 0 355
-1308 */{ 11 , 1 , 24 , 37608 },/* 30 29 29 30 29 29 30 29 30 30 30 29 30 384
-1309 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1310 */{ 0 , 1 , 31 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1311 */{ 7 , 1 , 20 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1312 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1313 */{ 0 , 1 , 27 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1314 */{ 3 , 1 , 17 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1315 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1316 */{ 0 , 1 , 25 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355
-1317 */{ 1 , 1 , 14 , 37608 },/* 30 29 29 30 29 29 30 29 30 30 30 29 30 384
-1318 */{ 0 , 2 , 2 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-1319 */{ 8 , 1 , 22 , 42328 },/* 30 29 30 29 29 30 29 30 29 30 29 30 30 384
-1320 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1321 */{ 0 , 1 , 29 , 45728 },/* 30 29 30 30 29 29 30 29 30 29 30 29 0 354
-1322 */{ 5 , 1 , 18 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1323 */{ 0 , 2 , 6 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1324 */{ 0 , 1 , 27 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
-1325 */{ 1 , 1 , 15 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 29 384
-1326 */{ 0 , 2 , 3 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1327 */{ 9 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1328 */{ 0 , 2 , 12 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
-1329 */{ 0 , 1 , 31 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 0 354
-1330 */{ 7 , 1 , 20 , 27288 },/* 29 30 30 29 30 29 30 29 30 29 29 30 30 384
-1331 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1332 */{ 0 , 1 , 28 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1333 */{ 3 , 1 , 17 , 19368 },/* 29 30 29 29 30 29 30 30 30 29 30 29 30 384
-1334 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1335 */{ 12 , 1 , 25 , 42608 },/* 30 29 30 29 29 30 30 29 29 30 30 30 29 384
-1336 */{ 0 , 2 , 13 , 41696 },/* 30 29 30 29 29 29 30 29 30 30 30 29 0 354
-1337 */{ 0 , 2 , 1 , 53600 },/* 30 30 29 30 29 29 29 30 29 30 30 29 0 354
-1338 */{ 8 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1339 */{ 0 , 2 , 9 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1340 */{ 0 , 1 , 29 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355
-1341 */{ 5 , 1 , 18 , 23376 },/* 29 30 29 30 30 29 30 30 29 30 29 30 29 384
-1342 */{ 0 , 2 , 6 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1343 */{ 0 , 1 , 27 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1344 */{ 2 , 1 , 16 , 41704 },/* 30 29 30 29 29 29 30 29 30 30 30 29 30 384
-1345 */{ 0 , 2 , 3 , 41680 },/* 30 29 30 29 29 29 30 29 30 30 29 30 0 354
-1346 */{ 10 , 1 , 23 , 53592 },/* 30 30 29 30 29 29 29 30 29 30 29 30 30 384
-1347 */{ 0 , 2 , 11 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1348 */{ 0 , 1 , 31 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1349 */{ 7 , 1 , 19 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 29 384
-1350 */{ 0 , 2 , 7 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-1351 */{ 0 , 1 , 28 , 21968 },/* 29 30 29 30 29 30 29 30 30 30 29 30 0 355
-1352 */{ 3 , 1 , 18 , 18904 },/* 29 30 29 29 30 29 29 30 30 30 29 30 30 384
-1353 */{ 0 , 2 , 5 , 17840 },/* 29 30 29 29 29 30 29 30 30 29 30 30 0 354
-1354 */{ 0 , 1 , 25 , 41648 },/* 30 29 30 29 29 29 30 29 30 29 30 30 0 354
-1355 */{ 1 , 1 , 14 , 53592 },/* 30 30 29 30 29 29 29 30 29 30 29 30 30 384
-1356 */{ 0 , 2 , 2 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1357 */{ 9 , 1 , 21 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-1358 */{ 0 , 2 , 9 , 27424 },/* 29 30 30 29 30 29 30 30 29 29 30 29 0 354
-1359 */{ 0 , 1 , 29 , 44384 },/* 30 29 30 29 30 30 29 30 29 30 30 29 0 355
-1360 */{ 5 , 1 , 19 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-1361 */{ 0 , 2 , 6 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1362 */{ 0 , 1 , 27 , 17776 },/* 29 30 29 29 29 30 29 30 29 30 30 30 0 354
-1363 */{ 3 , 1 , 16 , 41656 },/* 30 29 30 29 29 29 30 29 30 29 30 30 30 384
-1364 */{ 0 , 2 , 4 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1365 */{ 10 , 1 , 23 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 29 383
-1366 */{ 0 , 2 , 10 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1367 */{ 0 , 1 , 31 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1368 */{ 7 , 1 , 20 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 29 384
-1369 */{ 0 , 2 , 7 , 42720 },/* 30 29 30 29 29 30 30 29 30 30 30 29 0 355
-1370 */{ 0 , 1 , 28 , 21216 },/* 29 30 29 30 29 29 30 29 30 30 30 29 0 354
-1371 */{ 3 , 1 , 17 , 50544 },/* 30 30 29 29 29 30 29 30 29 30 30 30 29 384
-1372 */{ 0 , 2 , 5 , 42336 },/* 30 29 30 29 29 30 29 30 29 30 30 29 0 354
-1373 */{ 11 , 1 , 24 , 53928 },/* 30 30 29 30 29 29 30 29 30 29 30 29 30 384
-1374 */{ 0 , 2 , 12 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-1375 */{ 0 , 2 , 1 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1376 */{ 9 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1377 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1378 */{ 0 , 1 , 29 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355
-1379 */{ 5 , 1 , 19 , 21224 },/* 29 30 29 30 29 29 30 29 30 30 30 29 30 384
-1380 */{ 0 , 2 , 7 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1381 */{ 0 , 1 , 26 , 43216 },/* 30 29 30 29 30 29 29 29 30 30 29 30 0 354
-1382 */{ 2 , 1 , 15 , 53928 },/* 30 30 29 30 29 29 30 29 30 29 30 29 30 384
-1383 */{ 0 , 2 , 3 , 45728 },/* 30 29 30 30 29 29 30 29 30 29 30 29 0 354
-1384 */{ 10 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1385 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1386 */{ 0 , 1 , 31 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
-1387 */{ 6 , 1 , 20 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 29 384
-1388 */{ 0 , 2 , 8 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1389 */{ 0 , 1 , 28 , 20912 },/* 29 30 29 30 29 29 29 30 30 29 30 30 0 354
-1390 */{ 4 , 1 , 17 , 43192 },/* 30 29 30 29 30 29 29 29 30 29 30 30 30 384
-1391 */{ 0 , 2 , 5 , 25904 },/* 29 30 30 29 29 30 29 30 29 29 30 30 0 354
-1392 */{ 12 , 1 , 25 , 27288 },/* 29 30 30 29 30 29 30 29 30 29 29 30 30 384
-1393 */{ 0 , 2 , 12 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1394 */{ 0 , 2 , 1 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1395 */{ 9 , 1 , 22 , 11176 },/* 29 29 30 29 30 29 30 30 30 29 30 29 30 384
-1396 */{ 0 , 2 , 10 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1397 */{ 0 , 1 , 29 , 50032 },/* 30 30 29 29 29 29 30 30 29 30 30 30 0 355
-1398 */{ 5 , 1 , 19 , 20848 },/* 29 30 29 30 29 29 29 30 29 30 30 30 29 383
-1399 */{ 0 , 2 , 6 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1400 */{ 0 , 1 , 26 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1401 */{ 3 , 1 , 15 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 29 383
-1402 */{ 0 , 2 , 2 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355
-1403 */{ 11 , 1 , 23 , 23376 },/* 29 30 29 30 30 29 30 30 29 30 29 30 29 384
-1404 */{ 0 , 2 , 11 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1405 */{ 0 , 1 , 31 , 10976 },/* 29 29 30 29 30 29 30 29 30 30 30 29 0 354
-1406 */{ 7 , 1 , 20 , 41704 },/* 30 29 30 29 29 29 30 29 30 30 30 29 30 384
-1407 */{ 0 , 2 , 8 , 41680 },/* 30 29 30 29 29 29 30 29 30 30 29 30 0 354
-1408 */{ 0 , 1 , 28 , 53584 },/* 30 30 29 30 29 29 29 30 29 30 29 30 0 354
-1409 */{ 4 , 1 , 16 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1410 */{ 0 , 2 , 4 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1411 */{ 12 , 1 , 24 , 46736 },/* 30 29 30 30 29 30 30 29 30 29 29 30 29 384
-1412 */{ 0 , 2 , 12 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-1413 */{ 0 , 2 , 1 , 21968 },/* 29 30 29 30 29 30 29 30 30 30 29 30 0 355
-1414 */{ 9 , 1 , 22 , 9688 },/* 29 29 30 29 29 30 29 30 30 30 29 30 30 384
-1415 */{ 0 , 2 , 10 , 17840 },/* 29 30 29 29 29 30 29 30 30 29 30 30 0 354
-1416 */{ 0 , 1 , 30 , 41648 },/* 30 29 30 29 29 29 30 29 30 29 30 30 0 354
-1417 */{ 5 , 1 , 18 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1418 */{ 0 , 2 , 6 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1419 */{ 0 , 1 , 26 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1420 */{ 1 , 1 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1421 */{ 0 , 2 , 2 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1422 */{ 12 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-1423 */{ 0 , 2 , 11 , 19312 },/* 29 30 29 29 30 29 30 30 29 30 30 30 0 355
-1424 */{ 0 , 2 , 1 , 17776 },/* 29 30 29 29 29 30 29 30 29 30 30 30 0 354
-1425 */{ 7 , 1 , 20 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1426 */{ 0 , 2 , 8 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1427 */{ 0 , 1 , 28 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1428 */{ 4 , 1 , 17 , 27816 },/* 29 30 30 29 30 30 29 29 30 29 30 29 30 384
-1429 */{ 0 , 2 , 4 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1430 */{ 12 , 1 , 24 , 39760 },/* 30 29 29 30 30 29 30 30 29 30 29 30 29 384
-1431 */{ 0 , 2 , 12 , 42720 },/* 30 29 30 29 29 30 30 29 30 30 30 29 0 355
-1432 */{ 0 , 2 , 2 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1433 */{ 8 , 1 , 21 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1434 */{ 0 , 2 , 9 , 42336 },/* 30 29 30 29 29 30 29 30 29 30 30 29 0 354
-1435 */{ 0 , 1 , 29 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-1436 */{ 6 , 1 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 29 384
-1437 */{ 0 , 2 , 5 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1438 */{ 0 , 1 , 26 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1439 */{ 2 , 1 , 15 , 43728 },/* 30 29 30 29 30 29 30 29 30 30 29 30 29 384
-1440 */{ 0 , 2 , 3 , 38368 },/* 30 29 29 30 29 30 29 30 30 30 30 29 0 355
-1441 */{ 11 , 1 , 23 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1442 */{ 0 , 2 , 11 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1443 */{ 0 , 1 , 31 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1444 */{ 7 , 1 , 20 , 53872 },/* 30 30 29 30 29 29 30 29 29 30 30 30 29 384
-1445 */{ 0 , 2 , 7 , 45728 },/* 30 29 30 30 29 29 30 29 30 29 30 29 0 354
-1446 */{ 0 , 1 , 27 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1447 */{ 4 , 1 , 17 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1448 */{ 0 , 2 , 5 , 11680 },/* 29 29 30 29 30 30 29 30 30 29 30 29 0 354
-1449 */{ 0 , 1 , 24 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1450 */{ 1 , 1 , 14 , 19128 },/* 29 30 29 29 30 29 30 29 30 29 30 30 30 384
-1451 */{ 0 , 2 , 2 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1452 */{ 9 , 1 , 22 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1453 */{ 0 , 2 , 9 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1454 */{ 0 , 1 , 29 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 0 354
-1455 */{ 6 , 1 , 18 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1456 */{ 0 , 2 , 6 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 0 355
-1457 */{ 0 , 1 , 26 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1458 */{ 2 , 1 , 15 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 29 384
-1459 */{ 0 , 2 , 3 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1460 */{ 11 , 1 , 24 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 29 383
-1461 */{ 0 , 2 , 10 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1462 */{ 0 , 1 , 30 , 58544 },/* 30 30 30 29 29 30 29 29 30 29 30 30 0 355
-1463 */{ 7 , 1 , 20 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 29 383
-1464 */{ 0 , 2 , 7 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355
-1465 */{ 0 , 1 , 27 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1466 */{ 3 , 1 , 17 , 11112 },/* 29 29 30 29 30 29 30 30 29 30 30 29 30 384
-1467 */{ 0 , 2 , 5 , 9952 },/* 29 29 30 29 29 30 30 29 30 30 30 29 0 354
-1468 */{ 0 , 1 , 25 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1469 */{ 2 , 1 , 13 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1470 */{ 0 , 2 , 1 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1471 */{ 9 , 1 , 21 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1472 */{ 0 , 2 , 9 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1473 */{ 0 , 1 , 28 , 46736 },/* 30 29 30 30 29 30 30 29 30 29 29 30 0 355
-1474 */{ 6 , 1 , 18 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 29 384
-1475 */{ 0 , 2 , 6 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1476 */{ 0 , 1 , 27 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1477 */{ 2 , 1 , 15 , 37592 },/* 30 29 29 30 29 29 30 29 30 30 29 30 30 384
-1478 */{ 0 , 2 , 3 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-1479 */{ 10 , 1 , 23 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1480 */{ 0 , 2 , 11 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1481 */{ 0 , 1 , 30 , 29856 },/* 29 30 30 30 29 30 29 29 30 29 30 29 0 354
-1482 */{ 8 , 1 , 19 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1483 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1484 */{ 0 , 1 , 28 , 21424 },/* 29 30 29 30 29 29 30 30 30 29 30 30 0 355
-1485 */{ 4 , 1 , 17 , 9656 },/* 29 29 30 29 29 30 29 30 30 29 30 30 30 384
-1486 */{ 0 , 2 , 5 , 9584 },/* 29 29 30 29 29 30 29 30 29 30 30 30 0 354
-1487 */{ 0 , 1 , 25 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1488 */{ 1 , 1 , 14 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1489 */{ 0 , 2 , 1 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1490 */{ 9 , 1 , 21 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1491 */{ 0 , 2 , 9 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1492 */{ 0 , 1 , 29 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1493 */{ 5 , 1 , 18 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1494 */{ 0 , 2 , 6 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1495 */{ 0 , 1 , 26 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1496 */{ 3 , 1 , 16 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 29 383
-1497 */{ 0 , 2 , 2 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-1498 */{ 11 , 1 , 22 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 29 384
-1499 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1500 */{ 0 , 1 , 31 , 5792 },/* 29 29 29 30 29 30 30 29 30 29 30 29 0 353
-1501 */{ 7 , 1 , 19 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1502 */{ 0 , 2 , 7 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1503 */{ 0 , 1 , 28 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1504 */{ 4 , 1 , 17 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1505 */{ 0 , 2 , 4 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1506 */{ 0 , 1 , 24 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1507 */{ 1 , 1 , 13 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 29 384
-1508 */{ 0 , 2 , 1 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1509 */{ 9 , 1 , 21 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1510 */{ 0 , 2 , 9 , 11680 },/* 29 29 30 29 30 30 29 30 30 29 30 29 0 354
-1511 */{ 0 , 1 , 29 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1512 */{ 5 , 1 , 19 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1513 */{ 0 , 2 , 6 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1514 */{ 0 , 1 , 26 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1515 */{ 4 , 1 , 15 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1516 */{ 0 , 2 , 3 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 0 354
-1517 */{ 12 , 1 , 22 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1518 */{ 0 , 2 , 10 , 23376 },/* 29 30 29 30 30 29 30 30 29 30 29 30 0 355
-1519 */{ 0 , 1 , 31 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1520 */{ 8 , 1 , 20 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 29 384
-1521 */{ 0 , 2 , 7 , 37616 },/* 30 29 29 30 29 29 30 29 30 30 30 30 0 355
-1522 */{ 0 , 1 , 28 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1523 */{ 4 , 1 , 17 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-1524 */{ 0 , 2 , 4 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1525 */{ 12 , 1 , 23 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 29 384
-1526 */{ 0 , 2 , 11 , 54928 },/* 30 30 29 30 29 30 30 29 30 29 29 30 0 355
-1527 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1528 */{ 10 , 1 , 22 , 11112 },/* 29 29 30 29 30 29 30 30 29 30 30 29 30 384
-1529 */{ 0 , 2 , 9 , 9952 },/* 29 29 30 29 29 30 30 29 30 30 30 29 0 354
-1530 */{ 0 , 1 , 29 , 21216 },/* 29 30 29 30 29 29 30 29 30 30 30 29 0 354
-1531 */{ 6 , 1 , 18 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1532 */{ 0 , 2 , 6 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1533 */{ 0 , 1 , 25 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1534 */{ 2 , 1 , 14 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1535 */{ 0 , 2 , 2 , 46480 },/* 30 29 30 30 29 30 29 30 30 29 29 30 0 355
-1536 */{ 12 , 1 , 23 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 29 384
-1537 */{ 0 , 2 , 10 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1538 */{ 0 , 1 , 31 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1539 */{ 7 , 1 , 20 , 37592 },/* 30 29 29 30 29 29 30 29 30 30 29 30 30 384
-1540 */{ 0 , 2 , 8 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-1541 */{ 0 , 1 , 27 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1542 */{ 5 , 1 , 16 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-1543 */{ 0 , 2 , 4 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
-1544 */{ 0 , 1 , 24 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1545 */{ 1 , 1 , 13 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-1546 */{ 0 , 2 , 1 , 19376 },/* 29 30 29 29 30 29 30 30 30 29 30 30 0 355
-1547 */{ 9 , 1 , 22 , 9656 },/* 29 29 30 29 29 30 29 30 30 29 30 30 30 384
-1548 */{ 0 , 2 , 10 , 9584 },/* 29 29 30 29 29 30 29 30 29 30 30 30 0 354
-1549 */{ 0 , 1 , 29 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1550 */{ 6 , 1 , 18 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
-1551 */{ 0 , 2 , 5 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
-1552 */{ 0 , 1 , 26 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1553 */{ 3 , 1 , 14 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1554 */{ 0 , 2 , 2 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1555 */{ 11 , 1 , 23 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1556 */{ 0 , 2 , 11 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1557 */{ 0 , 1 , 30 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1558 */{ 7 , 1 , 20 , 21096 },/* 29 30 29 30 29 29 30 29 29 30 30 29 30 383
-1559 */{ 0 , 2 , 7 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1560 */{ 0 , 1 , 27 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1561 */{ 5 , 1 , 16 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1562 */{ 0 , 2 , 4 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1563 */{ 0 , 1 , 24 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1564 */{ 2 , 1 , 14 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1565 */{ 0 , 2 , 1 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1566 */{ 10 , 1 , 21 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1567 */{ 0 , 2 , 9 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1568 */{ 0 , 1 , 29 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1569 */{ 6 , 1 , 17 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384
-1570 */{ 0 , 2 , 5 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1571 */{ 0 , 1 , 26 , 13728 },/* 29 29 30 30 29 30 29 30 30 29 30 29 0 354
-1572 */{ 2 , 1 , 15 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 29 384
-1573 */{ 0 , 2 , 2 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1574 */{ 12 , 1 , 23 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1575 */{ 0 , 2 , 11 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1576 */{ 0 , 1 , 31 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1577 */{ 8 , 1 , 19 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1578 */{ 0 , 2 , 7 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1579 */{ 0 , 1 , 27 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1580 */{ 4 , 1 , 16 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
-1581 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1582 */{ 0 , 1 , 24 , 39024 },/* 30 29 29 30 29 29 30 30 39 30 30 30 0 365
-1583 */{ 2 , 1 , 24 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-1584 */{ 0 , 2 , 12 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1585 */{ 9 , 1 , 31 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-1586 */{ 0 , 2 , 18 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1587 */{ 0 , 3 , 9 , 53968 },/* 30 30 29 30 29 30 29 29 30 29 30 0 0 325
-1588 */{ 6 , 1 , 28 , 27464 },/* 29 30 30 29 30 29 30 30 29 30 29 29 30 384
-1589 */{ 0 , 2 , 15 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1590 */{ 0 , 2 , 5 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1591 */{ 3 , 1 , 25 , 37616 },/* 30 29 29 30 29 29 30 29 30 30 30 30 29 384
-1592 */{ 0 , 2 , 13 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1593 */{ 11 , 2 , 1 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1594 */{ 0 , 2 , 20 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1595 */{ 0 , 2 , 9 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1596 */{ 8 , 1 , 29 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1597 */{ 0 , 2 , 16 , 46288 },/* 30 29 30 30 29 30 29 29 30 30 29 30 0 355
-1598 */{ 0 , 2 , 6 , 22192 },/* 29 30 29 30 29 30 30 29 30 29 30 30 0 355
-1599 */{ 4 , 1 , 27 , 9944 },/* 29 29 30 29 29 30 30 29 30 30 29 30 30 384
-1600 */{ 0 , 2 , 15 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1601 */{ 0 , 2 , 3 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-1602 */{ 2 , 1 , 23 , 51608 },/* 30 30 29 29 30 29 29 30 30 29 29 30 30 384
-1603 */{ 0 , 2 , 11 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1604 */{ 9 , 1 , 31 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-1605 */{ 0 , 2 , 18 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1606 */{ 0 , 2 , 7 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1607 */{ 6 , 1 , 28 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-1608 */{ 0 , 2 , 16 , 19376 },/* 29 30 29 29 30 29 30 30 30 29 30 30 0 355
-1609 */{ 0 , 2 , 5 , 9648 },/* 29 29 30 29 29 30 29 30 30 29 30 30 0 354
-1610 */{ 3 , 1 , 25 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1611 */{ 0 , 2 , 13 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1612 */{ 11 , 2 , 2 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
-1613 */{ 0 , 2 , 19 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
-1614 */{ 0 , 2 , 9 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1615 */{ 8 , 1 , 29 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1616 */{ 0 , 2 , 17 , 39760 },/* 30 29 29 30 30 29 30 30 29 30 29 30 0 355
-1617 */{ 0 , 2 , 6 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1618 */{ 4 , 1 , 26 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1619 */{ 0 , 2 , 14 , 42224 },/* 30 29 30 29 29 30 29 29 30 30 30 30 0 355
-1620 */{ 0 , 2 , 4 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
-1621 */{ 2 , 1 , 22 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1622 */{ 0 , 2 , 10 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1623 */{ 10 , 1 , 31 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1624 */{ 0 , 2 , 19 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1625 */{ 0 , 2 , 7 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1626 */{ 6 , 1 , 28 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1627 */{ 0 , 2 , 16 , 18912 },/* 29 30 29 29 30 29 29 30 30 30 30 29 0 354
-1628 */{ 0 , 2 , 5 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1629 */{ 4 , 1 , 24 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1630 */{ 0 , 2 , 12 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1631 */{ 11 , 2 , 1 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1632 */{ 0 , 2 , 20 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1633 */{ 0 , 2 , 8 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
-1634 */{ 8 , 1 , 29 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 29 384
-1635 */{ 0 , 2 , 17 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1636 */{ 0 , 2 , 7 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1637 */{ 4 , 1 , 26 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1638 */{ 0 , 2 , 14 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1639 */{ 0 , 2 , 3 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1640 */{ 1 , 1 , 23 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-1641 */{ 0 , 2 , 10 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1642 */{ 11 , 1 , 30 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
-1643 */{ 0 , 2 , 19 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1644 */{ 0 , 2 , 8 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1645 */{ 6 , 1 , 28 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-1646 */{ 0 , 2 , 16 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1647 */{ 0 , 2 , 5 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1648 */{ 3 , 1 , 24 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1649 */{ 0 , 2 , 11 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-1650 */{ 11 , 2 , 1 , 27464 },/* 29 30 30 29 30 29 30 30 29 30 29 29 30 384
-1651 */{ 0 , 2 , 20 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1652 */{ 0 , 2 , 10 , 11168 },/* 29 29 30 29 30 29 30 30 30 29 30 29 0 354
-1653 */{ 7 , 1 , 29 , 37616 },/* 30 29 29 30 29 29 30 29 30 30 30 30 29 384
-1654 */{ 0 , 2 , 17 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1655 */{ 0 , 2 , 6 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1656 */{ 5 , 1 , 26 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1657 */{ 0 , 2 , 13 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1658 */{ 0 , 2 , 2 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-1659 */{ 3 , 1 , 23 , 39592 },/* 30 29 29 30 30 29 30 29 30 29 30 29 30 384
-1660 */{ 0 , 2 , 11 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1661 */{ 7 , 1 , 30 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 29 384
-1662 */{ 0 , 2 , 18 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 0 355
-1663 */{ 0 , 2 , 8 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-1664 */{ 6 , 1 , 28 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1665 */{ 0 , 2 , 15 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1666 */{ 0 , 2 , 4 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1667 */{ 4 , 1 , 24 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1668 */{ 0 , 2 , 12 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1669 */{ 0 , 2 , 1 , 21920 },/* 29 30 29 30 29 30 29 30 30 29 30 29 0 354
-1670 */{ 2 , 1 , 21 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 29 384
-1671 */{ 0 , 2 , 9 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-1672 */{ 7 , 1 , 30 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1673 */{ 0 , 2 , 17 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1674 */{ 0 , 2 , 6 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 0 354
-1675 */{ 5 , 1 , 26 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
-1676 */{ 0 , 2 , 14 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1677 */{ 0 , 2 , 2 , 44432 },/* 30 29 30 29 30 30 29 30 30 29 29 30 0 355
-1678 */{ 3 , 1 , 23 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
-1679 */{ 0 , 2 , 11 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1680 */{ 8 , 1 , 31 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1681 */{ 0 , 2 , 18 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
-1682 */{ 0 , 2 , 7 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1683 */{ 6 , 1 , 27 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1684 */{ 0 , 2 , 15 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-1685 */{ 0 , 2 , 3 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355
-1686 */{ 4 , 1 , 24 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
-1687 */{ 0 , 2 , 12 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1688 */{ 0 , 2 , 2 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1689 */{ 3 , 1 , 21 , 42216 },/* 30 29 30 29 29 30 29 29 30 30 30 29 30 384
-1690 */{ 0 , 2 , 9 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1691 */{ 7 , 1 , 29 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
-1692 */{ 0 , 2 , 17 , 45136 },/* 30 29 29 32 29 29 29 29 29 30 29 30 0 354
-1693 */{ 0 , 2 , 5 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-1694 */{ 5 , 1 , 25 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 29 384
-1695 */{ 0 , 2 , 13 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
-1696 */{ 0 , 2 , 3 , 21968 },/* 29 30 29 30 29 30 29 30 30 30 29 30 0 355
-1697 */{ 3 , 1 , 23 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-1698 */{ 0 , 2 , 11 , 18896 },/* 29 30 29 29 30 29 29 30 30 30 29 30 0 354
-1699 */{ 7 , 1 , 31 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1700 */{ 0 , 2 , 19 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1701 */{ 0 , 2 , 8 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1702 */{ 6 , 1 , 28 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-1703 */{ 0 , 2 , 16 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
-1704 */{ 0 , 2 , 5 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-1705 */{ 4 , 1 , 25 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-1706 */{ 0 , 2 , 13 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1707 */{ 0 , 2 , 3 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1708 */{ 3 , 1 , 23 , 25784 },/* 29 30 30 29 29 30 29 29 30 29 30 30 30 384
-1709 */{ 0 , 2 , 10 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1710 */{ 7 , 1 , 30 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1711 */{ 0 , 2 , 17 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-1712 */{ 0 , 2 , 7 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1713 */{ 5 , 1 , 26 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 29 384
-1714 */{ 0 , 2 , 14 , 43744 },/* 30 29 30 29 30 29 30 29 30 30 30 29 0 355
-1715 */{ 0 , 2 , 4 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1716 */{ 3 , 1 , 24 , 51568 },/* 30 30 29 29 30 29 29 30 29 30 30 30 29 384
-1717 */{ 0 , 2 , 11 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-1718 */{ 8 , 1 , 31 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1719 */{ 0 , 2 , 19 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1720 */{ 0 , 2 , 8 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1721 */{ 6 , 1 , 28 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1722 */{ 0 , 2 , 16 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1723 */{ 0 , 2 , 5 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355
-1724 */{ 4 , 1 , 26 , 21224 },/* 29 30 29 30 29 29 30 29 30 30 30 29 30 384
-1725 */{ 0 , 2 , 13 , 21200 },/* 29 30 29 30 29 29 30 29 30 30 29 30 0 354
-1726 */{ 0 , 2 , 2 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1727 */{ 3 , 1 , 22 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384
-1728 */{ 0 , 2 , 10 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1729 */{ 7 , 1 , 29 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1730 */{ 0 , 2 , 17 , 40272 },/* 30 29 29 30 30 30 29 30 29 30 29 30 0 355
-1731 */{ 0 , 2 , 7 , 21920 },/* 29 30 29 30 29 30 29 30 30 29 30 29 0 354
-1732 */{ 5 , 1 , 27 , 42448 },/* 30 29 30 29 29 30 29 30 30 30 29 30 29 384
-1733 */{ 0 , 2 , 14 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-1734 */{ 0 , 2 , 4 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1735 */{ 4 , 1 , 24 , 43192 },/* 30 29 30 29 30 29 29 29 30 29 30 30 30 384
-1736 */{ 0 , 2 , 12 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 0 354
-1737 */{ 9 , 1 , 31 , 27288 },/* 29 30 30 29 30 29 30 29 30 29 29 30 30 384
-1738 */{ 0 , 2 , 19 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1739 */{ 0 , 2 , 8 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1740 */{ 6 , 1 , 29 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
-1741 */{ 0 , 2 , 16 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1742 */{ 0 , 2 , 5 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1743 */{ 4 , 1 , 26 , 20848 },/* 29 30 29 30 29 29 29 30 29 30 30 30 29 383
-1744 */{ 0 , 2 , 13 , 53600 },/* 30 30 29 30 29 29 29 30 29 30 30 29 0 354
-1745 */{ 0 , 2 , 1 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 0 355
-1746 */{ 3 , 1 , 22 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 29 383
-1747 */{ 0 , 2 , 9 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 0 355
-1748 */{ 7 , 1 , 30 , 23376 },/* 29 30 29 30 30 29 30 30 29 30 29 30 29 384
-1749 */{ 0 , 2 , 17 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1750 */{ 0 , 2 , 7 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1751 */{ 5 , 1 , 27 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1752 */{ 0 , 2 , 15 , 41680 },/* 30 29 30 29 29 29 30 29 30 30 29 30 0 354
-1753 */{ 0 , 2 , 3 , 53592 },/* 30 30 29 30 29 29 29 30 29 30 29 30 30 384
-1754 */{ 4 , 2 , 22 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-1755 */{ 0 , 2 , 11 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1756 */{ 9 , 1 , 31 , 54928 },/* 30 30 29 30 29 30 30 29 30 29 29 30 29 384
-1757 */{ 0 , 2 , 18 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-1758 */{ 0 , 2 , 8 , 21968 },/* 29 30 29 30 29 30 29 30 30 30 29 30 0 355
-1759 */{ 6 , 1 , 29 , 10968 },/* 29 29 30 29 30 29 30 29 30 30 29 30 30 384
-1760 */{ 0 , 2 , 17 , 17840 },/* 29 30 29 29 29 30 29 30 30 29 30 30 0 354
-1761 */{ 0 , 2 , 5 , 41648 },/* 30 29 30 29 29 29 30 29 30 29 30 30 0 354
-1762 */{ 5 , 1 , 25 , 45400 },/* 30 29 30 30 29 29 29 30 29 30 29 30 30 384
-1763 */{ 0 , 2 , 13 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1764 */{ 0 , 2 , 2 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1765 */{ 2 , 1 , 21 , 46480 },/* 30 29 30 30 29 30 29 30 30 29 29 30 29 384
-1766 */{ 0 , 2 , 9 , 44384 },/* 30 29 30 29 30 30 29 30 29 30 30 29 0 355
-1767 */{ 7 , 1 , 30 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
-1768 */{ 0 , 2 , 18 , 21360 },/* 29 30 29 30 29 29 30 30 29 30 30 30 0 355
-1769 */{ 0 , 2 , 7 , 17776 },/* 29 30 29 29 29 30 29 30 29 30 30 30 0 354
-1770 */{ 5 , 1 , 27 , 25272 },/* 29 30 30 29 29 29 30 29 30 29 30 30 30 384
-1771 */{ 0 , 2 , 15 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1772 */{ 0 , 2 , 4 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1773 */{ 3 , 1 , 23 , 27816 },/* 29 30 30 29 30 30 29 29 30 29 30 29 30 384
-1774 */{ 0 , 2 , 11 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1775 */{ 10 , 1 , 31 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
-1776 */{ 0 , 2 , 19 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355
-1777 */{ 0 , 2 , 8 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1778 */{ 6 , 1 , 28 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 29 384
-1779 */{ 0 , 2 , 16 , 42336 },/* 30 29 30 29 29 30 29 30 29 30 30 29 0 354
-1780 */{ 0 , 2 , 5 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-1781 */{ 5 , 1 , 24 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 29 384
-1782 */{ 0 , 2 , 12 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1783 */{ 0 , 2 , 2 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1784 */{ 3 , 1 , 22 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
-1785 */{ 0 , 2 , 9 , 42704 },/* 30 29 30 29 29 30 30 29 30 30 29 30 0 355
-1786 */{ 7 , 1 , 30 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1787 */{ 0 , 2 , 18 , 19120 },/* 29 30 29 29 30 29 30 29 30 29 30 30 0 354
-1788 */{ 0 , 2 , 7 , 43216 },/* 30 29 30 29 30 29 29 29 30 30 29 30 0 354
-1789 */{ 5 , 1 , 26 , 53928 },/* 30 30 29 30 29 29 30 29 30 29 30 29 30 384
-1790 */{ 0 , 2 , 14 , 45728 },/* 30 29 30 30 29 29 30 29 30 29 30 29 0 354
-1791 */{ 0 , 2 , 3 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1792 */{ 4 , 1 , 24 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1793 */{ 0 , 2 , 11 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
-1794 */{ 0 , 1 , 31 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1795 */{ 2 , 1 , 21 , 19128 },/* 29 30 29 29 30 29 30 29 30 29 30 30 30 384
-1796 */{ 0 , 2 , 9 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1797 */{ 6 , 1 , 28 , 43192 },/* 30 29 30 29 30 29 29 29 30 29 30 30 30 384
-1798 */{ 0 , 2 , 16 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1799 */{ 0 , 2 , 5 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 0 354
-1800 */{ 4 , 1 , 25 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1801 */{ 0 , 2 , 13 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 0 355
-1802 */{ 0 , 2 , 3 , 11168 },/* 29 29 30 29 30 29 30 30 30 29 30 29 0 354
-1803 */{ 2 , 1 , 23 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 29 384
-1804 */{ 0 , 2 , 11 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1805 */{ 6 , 1 , 31 , 20848 },/* 29 30 29 30 29 29 29 30 29 30 30 30 29 383
-1806 */{ 0 , 2 , 18 , 53600 },/* 30 30 29 30 29 29 29 30 29 30 30 29 0 354
-1807 */{ 0 , 2 , 7 , 58544 },/* 30 30 30 29 29 30 29 29 30 29 30 30 0 355
-1808 */{ 5 , 1 , 28 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 29 383
-1809 */{ 0 , 2 , 14 , 55952 },/* 30 30 29 30 30 29 30 29 30 29 29 30 0 355
-1810 */{ 0 , 2 , 4 , 23376 },/* 29 30 29 30 30 29 30 30 29 30 29 30 0 355
-1811 */{ 3 , 1 , 25 , 11112 },/* 29 29 30 29 30 29 30 30 29 30 30 29 30 384
-1812 */{ 0 , 2 , 13 , 10976 },/* 29 29 30 29 30 29 30 29 30 30 30 29 0 354
-1813 */{ 0 , 2 , 1 , 41696 },/* 30 29 30 29 29 29 30 29 30 30 30 29 0 354
-1814 */{ 2 , 1 , 21 , 53608 },/* 30 30 29 30 29 29 29 30 29 30 30 29 30 384
-1815 */{ 0 , 2 , 9 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1816 */{ 6 , 1 , 29 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1817 */{ 0 , 2 , 16 , 46368 },/* 30 29 30 30 29 30 29 30 29 29 30 29 0 354
-1818 */{ 0 , 2 , 5 , 46736 },/* 30 29 30 30 29 30 30 29 30 29 29 30 0 355
-1819 */{ 4 , 1 , 26 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 29 384
-1820 */{ 0 , 2 , 14 , 21968 },/* 29 30 29 30 29 30 29 30 30 30 29 30 0 355
-1821 */{ 0 , 2 , 3 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1822 */{ 3 , 1 , 23 , 41688 },/* 30 29 30 29 29 29 30 29 30 30 29 30 30 384
-1823 */{ 0 , 2 , 11 , 41648 },/* 30 29 30 29 29 29 30 29 30 29 30 30 0 354
-1824 */{ 7 , 1 , 31 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1825 */{ 0 , 2 , 18 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1826 */{ 0 , 2 , 7 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1827 */{ 5 , 1 , 27 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-1828 */{ 0 , 2 , 15 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-1829 */{ 0 , 2 , 4 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1830 */{ 4 , 1 , 25 , 9656 },/* 29 29 30 29 29 30 29 30 30 29 30 30 30 384
-1831 */{ 0 , 2 , 13 , 9584 },/* 29 29 30 29 29 30 29 30 29 30 30 30 0 354
-1832 */{ 9 , 2 , 2 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1833 */{ 0 , 2 , 20 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1834 */{ 0 , 2 , 9 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1835 */{ 6 , 1 , 29 , 27816 },/* 29 30 30 29 30 30 29 29 30 29 30 29 30 384
-1836 */{ 0 , 2 , 17 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1837 */{ 0 , 2 , 5 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1838 */{ 4 , 1 , 26 , 21352 },/* 29 30 29 30 29 29 30 30 29 30 30 29 30 384
-1839 */{ 0 , 2 , 14 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1840 */{ 0 , 2 , 3 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1841 */{ 3 , 1 , 23 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 29 383
-1842 */{ 0 , 2 , 10 , 53920 },/* 30 30 29 30 29 29 30 29 30 29 30 29 0 354
-1843 */{ 7 , 1 , 30 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 29 384
-1844 */{ 0 , 2 , 18 , 54608 },/* 30 30 29 30 29 30 29 30 29 30 29 30 0 355
-1845 */{ 0 , 2 , 7 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-1846 */{ 5 , 1 , 27 , 43728 },/* 30 29 30 29 30 29 30 29 30 30 29 30 29 384
-1847 */{ 0 , 2 , 15 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1848 */{ 0 , 2 , 5 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1849 */{ 4 , 1 , 24 , 42328 },/* 30 29 30 29 29 30 29 30 29 30 29 30 30 384
-1850 */{ 0 , 2 , 12 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1851 */{ 8 , 2 , 1 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
-1852 */{ 0 , 2 , 20 , 45712 },/* 30 29 30 30 29 29 30 29 30 29 29 30 0 354
-1853 */{ 0 , 2 , 8 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1854 */{ 7 , 1 , 29 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1855 */{ 0 , 2 , 17 , 11680 },/* 29 29 30 29 30 30 29 30 30 29 30 29 0 354
-1856 */{ 0 , 2 , 6 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1857 */{ 5 , 1 , 26 , 19128 },/* 29 30 29 29 30 29 30 29 30 29 30 30 30 384
-1858 */{ 0 , 2 , 14 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1859 */{ 0 , 2 , 3 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1860 */{ 3 , 1 , 23 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1861 */{ 0 , 2 , 10 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 0 354
-1862 */{ 8 , 1 , 30 , 44360 },/* 30 29 30 29 30 30 29 30 29 30 29 29 30 384
-1863 */{ 0 , 2 , 18 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 0 355
-1864 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1865 */{ 5 , 1 , 27 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 29 384
-1866 */{ 0 , 2 , 15 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 0 355
-1867 */{ 0 , 2 , 5 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1868 */{ 4 , 1 , 25 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-1869 */{ 0 , 2 , 11 , 58528 },/* 30 30 30 29 29 30 29 29 30 29 30 29 0 354
-1870 */{ 10 , 1 , 31 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 29 384
-1871 */{ 0 , 2 , 19 , 55952 },/* 30 30 29 30 30 29 30 29 30 29 29 30 0 355
-1872 */{ 0 , 2 , 9 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1873 */{ 6 , 1 , 29 , 11112 },/* 29 29 30 29 30 29 30 30 29 30 30 29 30 384
-1874 */{ 0 , 2 , 17 , 10976 },/* 29 29 30 29 30 29 30 29 30 30 30 29 0 354
-1875 */{ 0 , 2 , 6 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1876 */{ 5 , 1 , 26 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1877 */{ 0 , 2 , 13 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1878 */{ 0 , 2 , 2 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1879 */{ 3 , 1 , 22 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1880 */{ 0 , 2 , 10 , 46736 },/* 30 29 30 30 29 30 30 29 30 29 29 30 0 355
-1881 */{ 7 , 1 , 30 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 29 384
-1882 */{ 0 , 2 , 18 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1883 */{ 0 , 2 , 8 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1884 */{ 5 , 1 , 28 , 37592 },/* 30 29 29 30 29 29 30 29 30 30 29 30 30 384
-1885 */{ 0 , 2 , 15 , 37552 },/* 30 29 29 30 29 29 30 29 30 29 30 30 0 354
-1886 */{ 0 , 2 , 4 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1887 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1888 */{ 0 , 2 , 12 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1889 */{ 0 , 1 , 31 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1890 */{ 2 , 1 , 21 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1891 */{ 0 , 2 , 9 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 0 355
-1892 */{ 6 , 1 , 30 , 9656 },/* 29 29 30 29 29 30 29 30 30 29 30 30 30 384
-1893 */{ 0 , 2 , 17 , 9584 },/* 29 29 30 29 29 30 29 30 29 30 30 30 0 354
-1894 */{ 0 , 2 , 6 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1895 */{ 5 , 1 , 26 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
-1896 */{ 0 , 2 , 13 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
-1897 */{ 0 , 2 , 2 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1898 */{ 3 , 1 , 22 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1899 */{ 0 , 2 , 10 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1900 */{ 8 , 1 , 31 , 19304 },/* 29 30 29 29 30 29 30 30 29 30 30 29 30 384
-1901 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1902 */{ 0 , 2 , 8 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1903 */{ 5 , 1 , 29 , 21096 },/* 29 30 29 30 29 29 30 29 29 30 30 29 30 383
-1904 */{ 0 , 2 , 16 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-1905 */{ 0 , 2 , 4 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1906 */{ 4 , 1 , 25 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1907 */{ 0 , 2 , 13 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1908 */{ 0 , 2 , 2 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355
-1909 */{ 2 , 1 , 22 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1910 */{ 0 , 2 , 10 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1911 */{ 6 , 1 , 30 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1912 */{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1914 */{ 5 , 1 , 26 , 55624 },/* 30 30 29 30 30 29 29 30 29 30 29 29 30 384
-1915 */{ 0 , 2 , 14 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1916 */{ 0 , 2 , 4 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1918 */{ 0 , 2 , 11 , 38352 },/* 30 29 29 30 29 30 29 30 30 30 29 30 0 355
-1919 */{ 7 , 2 , 1 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-1920 */{ 0 , 2 , 20 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1923 */{ 0 , 2 , 16 , 27280 },/* 29 30 30 29 30 29 30 29 30 29 29 30 0 354
-1924 */{ 0 , 2 , 5 , 44352 },/* 30 29 30 29 30 30 29 30 29 30 29 29 0 354
-1925 */{ 4 , 1 , 24 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385
-1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1927 */{ 0 , 2 , 2 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1928 */{ 2 , 1 , 23 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-1931 */{ 0 , 2 , 17 , 58528 },/* 30 30 30 29 29 30 29 29 30 29 30 29 0 354
-1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
-1934 */{ 0 , 2 , 14 , 23376 },/* 29 30 29 30 30 29 30 30 29 30 29 30 0 355
-1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1936 */{ 3 , 1 , 24 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 29 384
-1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1942 */{ 0 , 2 , 15 , 46736 },/* 30 29 30 30 29 30 30 29 30 29 29 30 0 355
-1943 */{ 0 , 2 , 5 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-1944 */{ 4 , 1 , 26 , 10968 },/* 29 29 30 29 30 29 30 29 30 30 29 30 30 384
-1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1949 */{ 7 , 1 , 29 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-1950 */{ 0 , 2 , 17 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1952 */{ 5 , 1 , 27 , 22184 },/* 29 30 29 30 29 30 30 29 30 29 30 29 30 384
-1953 */{ 0 , 2 , 14 , 19888 },/* 29 30 29 29 30 30 29 30 30 29 30 30 0 355
-1954 */{ 0 , 2 , 4 , 9648 },/* 29 29 30 29 29 30 29 30 30 29 30 30 0 354
-1955 */{ 3 , 1 , 24 , 37560 },/* 30 29 29 30 29 29 30 29 30 29 30 30 30 384
-1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1957 */{ 8 , 1 , 31 , 43352 },/* 30 29 30 29 30 29 29 30 29 30 29 30 30 384
-1958 */{ 0 , 2 , 19 , 26960 },/* 29 30 30 29 30 29 29 30 29 30 29 30 0 354
-1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
-1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
-1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384
-1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355
-1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
-1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384
-1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
-1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384
-1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385
-1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
-1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384
-2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354
-2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384
-2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
-2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354
-2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383
-2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355
-2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384
-2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354
-2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
-2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
-2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354
-2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-2050 */{ 3 , 1 , 23 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 29 384
- */};
-
-
- internal override int MinCalendarYear {
- get
- {
- return (MIN_LUNISOLAR_YEAR);
- }
- }
-
- internal override int MaxCalendarYear {
- get
- {
- return (MAX_LUNISOLAR_YEAR);
- }
- }
-
- internal override DateTime MinDate {
- get
- {
- return (minDate);
- }
- }
-
- internal override DateTime MaxDate {
- get
- {
- return (maxDate);
- }
- }
-
- internal override EraInfo[] CalEraInfo {
- get
- {
- return null;
- }
- }
-
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MIN_LUNISOLAR_YEAR,
- MAX_LUNISOLAR_YEAR ));
- }
- Contract.EndContractBlock();
- return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
- }
-
- internal override int GetYear(int year, DateTime time)
- {
- return year;
- }
-
- internal override int GetGregorianYear(int year, int era)
- {
- if (era != CurrentEra && era != GregorianEra)
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
-
- if (year < MIN_LUNISOLAR_YEAR || year > MAX_LUNISOLAR_YEAR)
- {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR));
- }
- Contract.EndContractBlock();
-
- return year;
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of KoreanLunisolarCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance()
- {
- if (m_defaultInstance == null) {
- m_defaultInstance = new KoreanLunisolarCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
- // Construct an instance of KoreanLunisolar calendar.
-
- public KoreanLunisolarCalendar() {
- }
-
-
-
- public override int GetEra(DateTime time) {
- CheckTicksRange(time.Ticks);
- return (GregorianEra);
- }
-
- internal override int BaseCalendarID {
- get {
- return (CAL_KOREA);
- }
- }
-
- internal override int ID {
- get {
- return (CAL_KOREANLUNISOLAR);
- }
- }
-
-
-
- public override int[] Eras {
- get {
- return (new int[] {GregorianEra});
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
index d95aac3d3d..c44c085a69 100644
--- a/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
+++ b/src/mscorlib/src/System/Globalization/NumberFormatInfo.cs
@@ -2,11 +2,13 @@
// 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.Globalization {
- using System.Runtime.Serialization;
- using System.Text;
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Text;
+
+namespace System.Globalization
+{
//
// Property Default Description
// PositiveSign '+' Character used to indicate positive values.
@@ -40,19 +42,19 @@ namespace System.Globalization {
//
[Serializable]
- sealed public partial class NumberFormatInfo : ICloneable, IFormatProvider
+ sealed public class NumberFormatInfo : IFormatProvider, ICloneable
{
// invariantInfo is constant irrespective of your current culture.
- private static volatile NumberFormatInfo invariantInfo;
+ private static volatile NumberFormatInfo s_invariantInfo;
// READTHIS READTHIS READTHIS
// This class has an exact mapping onto a native structure defined in COMNumber.cpp
// DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END.
// ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets.
// READTHIS READTHIS READTHIS
- internal int[] numberGroupSizes = new int[] {3};
- internal int[] currencyGroupSizes = new int[] {3};
- internal int[] percentGroupSizes = new int[] {3};
+ internal int[] numberGroupSizes = new int[] { 3 };
+ internal int[] currencyGroupSizes = new int[] { 3 };
+ internal int[] percentGroupSizes = new int[] { 3 };
internal String positiveSign = "+";
internal String negativeSign = "-";
internal String numberDecimalSeparator = ".";
@@ -60,10 +62,6 @@ namespace System.Globalization {
internal String currencyGroupSeparator = ",";
internal String currencyDecimalSeparator = ".";
internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund.
- // The alternative currency symbol used in Win9x ANSI codepage, that can not roundtrip between ANSI and Unicode.
- // Currently, only ja-JP and ko-KR has non-null values (which is U+005c, backslash)
- // NOTE: The only legal values for this string are null and "\x005c"
- internal String ansiCurrencySymbol = null;
internal String nanSymbol = "NaN";
internal String positiveInfinitySymbol = "Infinity";
internal String negativeInfinitySymbol = "-Infinity";
@@ -72,14 +70,9 @@ namespace System.Globalization {
internal String percentSymbol = "%";
internal String perMilleSymbol = "\u2030";
- [OptionalField(VersionAdded = 2)]
- internal String[] nativeDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
- // an index which points to a record in Culture Data Table.
- // We shouldn't be persisting dataItem (since its useless & we weren't using it),
- // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now.
- [OptionalField(VersionAdded = 1)]
- internal int m_dataItem = 0; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
+ [OptionalField(VersionAdded = 2)]
+ internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
internal int numberDecimalDigits = 2;
internal int currencyDecimalDigits = 2;
@@ -91,109 +84,100 @@ namespace System.Globalization {
internal int percentDecimalDigits = 2;
[OptionalField(VersionAdded = 2)]
- internal int digitSubstitution = 1; // DigitShapes.None
+ internal int digitSubstitution = (int) DigitShapes.None;
- internal bool isReadOnly=false;
- // We shouldn't be persisting m_useUserOverride (since its useless & we weren't using it),
- // but since COMNumber.cpp uses it and since serialization isn't implimented, its stuck for now.
- [OptionalField(VersionAdded = 1)]
- internal bool m_useUserOverride=false; // NEVER USED, DO NOT USE THIS! (Serialized in Everett)
+ internal bool isReadOnly = false;
// Is this NumberFormatInfo for invariant culture?
+
[OptionalField(VersionAdded = 2)]
- internal bool m_isInvariant=false;
+ internal bool m_isInvariant = false;
- public NumberFormatInfo() : this(null) {
+ public NumberFormatInfo() : this(null)
+ {
}
-#region Serialization
- // Check if NumberFormatInfo was not set up ambiguously for parsing as number and currency
- // eg. if the NumberDecimalSeparator and the NumberGroupSeparator were the same. This check
- // is solely for backwards compatibility / version tolerant serialization
- [OptionalField(VersionAdded = 1)]
- internal bool validForParseAsNumber = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
- [OptionalField(VersionAdded = 1)]
- internal bool validForParseAsCurrency = true; // NEVER USED, DO NOT USE THIS! (Serialized in Whidbey/Everett)
-
[OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
- }
+ private void OnSerializing(StreamingContext ctx) { }
[OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- }
+ private void OnDeserializing(StreamingContext ctx) { }
[OnDeserialized]
- private void OnDeserialized(StreamingContext ctx)
- {
- }
-#endregion Serialization
+ private void OnDeserialized(StreamingContext ctx) { }
- static private void VerifyDecimalSeparator(String decSep, String propertyName) {
- if (decSep==null) {
+ private static void VerifyDecimalSeparator(String decSep, String propertyName)
+ {
+ if (decSep == null)
+ {
throw new ArgumentNullException(propertyName,
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
- if (decSep.Length==0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyDecString"));
+ if (decSep.Length == 0)
+ {
+ throw new ArgumentException(SR.Argument_EmptyDecString);
}
Contract.EndContractBlock();
-
}
- static private void VerifyGroupSeparator(String groupSep, String propertyName) {
- if (groupSep==null) {
+ private static void VerifyGroupSeparator(String groupSep, String propertyName)
+ {
+ if (groupSep == null)
+ {
throw new ArgumentNullException(propertyName,
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
}
- static private void VerifyNativeDigits(String [] nativeDig, String propertyName) {
- if (nativeDig==null) {
- throw new ArgumentNullException(propertyName,
- Environment.GetResourceString("ArgumentNull_Array"));
+ private static void VerifyNativeDigits(string [] nativeDig, string propertyName)
+ {
+ if (nativeDig == null)
+ {
+ throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array);
}
if (nativeDig.Length != 10)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitCount"), propertyName);
+ throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName);
}
Contract.EndContractBlock();
- for(int i = 0; i < nativeDig.Length; i++)
+ for (int i = 0; i < nativeDig.Length; i++)
{
if (nativeDig[i] == null)
{
- throw new ArgumentNullException(propertyName,
- Environment.GetResourceString("ArgumentNull_ArrayValue"));
+ throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue);
}
-
- if (nativeDig[i].Length != 1) {
- if(nativeDig[i].Length != 2) {
+ if (nativeDig[i].Length != 1)
+ {
+ if (nativeDig[i].Length != 2)
+ {
// Not 1 or 2 UTF-16 code points
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
- } else if(!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) {
+ throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
+ }
+ else if (!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1]))
+ {
// 2 UTF-6 code points, but not a surrogate pair
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
+ throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
}
if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i &&
- CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) {
+ CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse)
+ {
// Not the appropriate digit according to the Unicode data properties
// (Digit 0 must be a 0, etc.).
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNativeDigitValue"), propertyName);
+ throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName);
}
}
}
- static private void VerifyDigitSubstitution(DigitShapes digitSub, String propertyName) {
- switch(digitSub)
+ private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName)
+ {
+ switch (digitSub)
{
case DigitShapes.Context:
case DigitShapes.None:
@@ -202,12 +186,10 @@ namespace System.Globalization {
break;
default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDigitSubstitution"), propertyName);
+ throw new ArgumentException(SR.Argument_InvalidDigitSubstitution, propertyName);
}
}
- // We aren't persisting dataItem any more (since its useless & we weren't using it),
- // Ditto with m_useUserOverride. Don't use them, we use a local copy of everything.
internal NumberFormatInfo(CultureData cultureData)
{
if (cultureData != null)
@@ -225,9 +207,11 @@ namespace System.Globalization {
}
[Pure]
- private void VerifyWritable() {
- if (isReadOnly) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ private void VerifyWritable()
+ {
+ if (isReadOnly)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
Contract.EndContractBlock();
}
@@ -237,41 +221,50 @@ namespace System.Globalization {
// Used by FromString methods.
//
- public static NumberFormatInfo InvariantInfo {
- get {
- if (invariantInfo == null) {
+ public static NumberFormatInfo InvariantInfo
+ {
+ get
+ {
+ if (s_invariantInfo == null)
+ {
// Lazy create the invariant info. This cannot be done in a .cctor because exceptions can
// be thrown out of a .cctor stack that will need this.
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.m_isInvariant = true;
- invariantInfo = ReadOnly(nfi);
+ s_invariantInfo = ReadOnly(nfi);
}
- return invariantInfo;
+ return s_invariantInfo;
}
}
-
- public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) {
+ public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
+ {
// Fast case for a regular CultureInfo
NumberFormatInfo info;
CultureInfo cultureProvider = formatProvider as CultureInfo;
- if (cultureProvider != null && !cultureProvider.m_isInherited) {
+ if (cultureProvider != null && !cultureProvider._isInherited)
+ {
info = cultureProvider.numInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
- else {
+ else
+ {
return cultureProvider.NumberFormat;
}
}
// Fast case for an NFI;
info = formatProvider as NumberFormatInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
- if (formatProvider != null) {
+ if (formatProvider != null)
+ {
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
}
@@ -280,22 +273,26 @@ namespace System.Globalization {
- public Object Clone() {
+ public Object Clone()
+ {
NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone();
n.isReadOnly = false;
return n;
}
- public int CurrencyDecimalDigits {
+ public int CurrencyDecimalDigits
+ {
get { return currencyDecimalDigits; }
- set {
- if (value < 0 || value > 99) {
+ set
+ {
+ if (value < 0 || value > 99)
+ {
throw new ArgumentOutOfRangeException(
nameof(CurrencyDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
99));
}
@@ -306,18 +303,22 @@ namespace System.Globalization {
}
- public String CurrencyDecimalSeparator {
+ public String CurrencyDecimalSeparator
+ {
get { return currencyDecimalSeparator; }
- set {
+ set
+ {
VerifyWritable();
- VerifyDecimalSeparator(value, nameof(CurrencyDecimalSeparator));
+ VerifyDecimalSeparator(value, "CurrencyDecimalSeparator");
currencyDecimalSeparator = value;
}
}
- public bool IsReadOnly {
- get {
+ public bool IsReadOnly
+ {
+ get
+ {
return isReadOnly;
}
}
@@ -328,7 +329,7 @@ namespace System.Globalization {
// Every element in the groupSize array should be between 1 and 9
// excpet the last element could be zero.
//
- static internal void CheckGroupSize(String propName, int[] groupSize)
+ internal static void CheckGroupSize(String propName, int[] groupSize)
{
for (int i = 0; i < groupSize.Length; i++)
{
@@ -336,49 +337,56 @@ namespace System.Globalization {
{
if (i == groupSize.Length - 1 && groupSize[i] == 0)
return;
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName);
+ throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
else if (groupSize[i] > 9)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGroupSize"), propName);
+ throw new ArgumentException(SR.Argument_InvalidGroupSize, propName);
}
}
}
- public int[] CurrencyGroupSizes {
- get {
+ public int[] CurrencyGroupSizes
+ {
+ get
+ {
return ((int[])currencyGroupSizes.Clone());
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(CurrencyGroupSizes),
- Environment.GetResourceString("ArgumentNull_Obj"));
+ SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
- VerifyWritable();
-
+ VerifyWritable();
+
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(CurrencyGroupSizes), inputSizes);
currencyGroupSizes = inputSizes;
}
-
}
- public int[] NumberGroupSizes {
- get {
+ public int[] NumberGroupSizes
+ {
+ get
+ {
return ((int[])numberGroupSizes.Clone());
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(NumberGroupSizes),
- Environment.GetResourceString("ArgumentNull_Obj"));
+ SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
-
+
Int32[] inputSizes = (Int32[])value.Clone();
CheckGroupSize(nameof(NumberGroupSizes), inputSizes);
numberGroupSizes = inputSizes;
@@ -386,28 +394,33 @@ namespace System.Globalization {
}
- public int[] PercentGroupSizes {
- get {
+ public int[] PercentGroupSizes
+ {
+ get
+ {
return ((int[])percentGroupSizes.Clone());
}
- set {
- if (value == null) {
- throw new ArgumentNullException(nameof(PercentGroupSizes),
- Environment.GetResourceString("ArgumentNull_Obj"));
+ set
+ {
+ if (value == null)
+ {
+ throw new ArgumentNullException("PercentGroupSizes",
+ SR.ArgumentNull_Obj);
}
Contract.EndContractBlock();
VerifyWritable();
Int32[] inputSizes = (Int32[])value.Clone();
- CheckGroupSize(nameof(PercentGroupSizes), inputSizes);
+ CheckGroupSize("PercentGroupSizes", inputSizes);
percentGroupSizes = inputSizes;
}
-
}
- public String CurrencyGroupSeparator {
+ public String CurrencyGroupSeparator
+ {
get { return currencyGroupSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyGroupSeparator(value, nameof(CurrencyGroupSeparator));
currencyGroupSeparator = value;
@@ -415,12 +428,15 @@ namespace System.Globalization {
}
- public String CurrencySymbol {
+ public String CurrencySymbol
+ {
get { return currencySymbol; }
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(CurrencySymbol),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -431,12 +447,16 @@ namespace System.Globalization {
// Returns the current culture's NumberFormatInfo. Used by Parse methods.
//
- public static NumberFormatInfo CurrentInfo {
- get {
- System.Globalization.CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture;
- if (!culture.m_isInherited) {
+ public static NumberFormatInfo CurrentInfo
+ {
+ get
+ {
+ System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture;
+ if (!culture._isInherited)
+ {
NumberFormatInfo info = culture.numInfo;
- if (info != null) {
+ if (info != null)
+ {
return info;
}
}
@@ -445,14 +465,18 @@ namespace System.Globalization {
}
- public String NaNSymbol {
- get {
+ public String NaNSymbol
+ {
+ get
+ {
return nanSymbol;
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(NaNSymbol),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -462,15 +486,18 @@ namespace System.Globalization {
- public int CurrencyNegativePattern {
+ public int CurrencyNegativePattern
+ {
get { return currencyNegativePattern; }
- set {
- if (value < 0 || value > 15) {
+ set
+ {
+ if (value < 0 || value > 15)
+ {
throw new ArgumentOutOfRangeException(
nameof(CurrencyNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
15));
}
@@ -481,18 +508,21 @@ namespace System.Globalization {
}
- public int NumberNegativePattern {
+ public int NumberNegativePattern
+ {
get { return numberNegativePattern; }
- set {
+ set
+ {
//
// NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp.
//
- if (value < 0 || value > 4) {
+ if (value < 0 || value > 4)
+ {
throw new ArgumentOutOfRangeException(
nameof(NumberNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
4));
}
@@ -503,18 +533,21 @@ namespace System.Globalization {
}
- public int PercentPositivePattern {
+ public int PercentPositivePattern
+ {
get { return percentPositivePattern; }
- set {
+ set
+ {
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
- if (value < 0 || value > 3) {
+ if (value < 0 || value > 3)
+ {
throw new ArgumentOutOfRangeException(
nameof(PercentPositivePattern),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
3));
}
@@ -525,18 +558,21 @@ namespace System.Globalization {
}
- public int PercentNegativePattern {
+ public int PercentNegativePattern
+ {
get { return percentNegativePattern; }
- set {
+ set
+ {
//
// NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp.
//
- if (value < 0 || value > 11) {
+ if (value < 0 || value > 11)
+ {
throw new ArgumentOutOfRangeException(
nameof(PercentNegativePattern),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
11));
}
@@ -547,14 +583,18 @@ namespace System.Globalization {
}
- public String NegativeInfinitySymbol {
- get {
+ public String NegativeInfinitySymbol
+ {
+ get
+ {
return negativeInfinitySymbol;
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(NegativeInfinitySymbol),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -563,12 +603,15 @@ namespace System.Globalization {
}
- public String NegativeSign {
+ public String NegativeSign
+ {
get { return negativeSign; }
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(NegativeSign),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -577,15 +620,18 @@ namespace System.Globalization {
}
- public int NumberDecimalDigits {
+ public int NumberDecimalDigits
+ {
get { return numberDecimalDigits; }
- set {
- if (value < 0 || value > 99) {
+ set
+ {
+ if (value < 0 || value > 99)
+ {
throw new ArgumentOutOfRangeException(
nameof(NumberDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
99));
}
@@ -596,9 +642,11 @@ namespace System.Globalization {
}
- public String NumberDecimalSeparator {
+ public String NumberDecimalSeparator
+ {
get { return numberDecimalSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyDecimalSeparator(value, nameof(NumberDecimalSeparator));
numberDecimalSeparator = value;
@@ -606,9 +654,11 @@ namespace System.Globalization {
}
- public String NumberGroupSeparator {
+ public String NumberGroupSeparator
+ {
get { return numberGroupSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyGroupSeparator(value, nameof(NumberGroupSeparator));
numberGroupSeparator = value;
@@ -616,15 +666,18 @@ namespace System.Globalization {
}
- public int CurrencyPositivePattern {
+ public int CurrencyPositivePattern
+ {
get { return currencyPositivePattern; }
- set {
- if (value < 0 || value > 3) {
+ set
+ {
+ if (value < 0 || value > 3)
+ {
throw new ArgumentOutOfRangeException(
nameof(CurrencyPositivePattern),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
3));
}
@@ -635,14 +688,18 @@ namespace System.Globalization {
}
- public String PositiveInfinitySymbol {
- get {
+ public String PositiveInfinitySymbol
+ {
+ get
+ {
return positiveInfinitySymbol;
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(PositiveInfinitySymbol),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -651,12 +708,15 @@ namespace System.Globalization {
}
- public String PositiveSign {
+ public String PositiveSign
+ {
get { return positiveSign; }
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(PositiveSign),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -665,15 +725,18 @@ namespace System.Globalization {
}
- public int PercentDecimalDigits {
+ public int PercentDecimalDigits
+ {
get { return percentDecimalDigits; }
- set {
- if (value < 0 || value > 99) {
+ set
+ {
+ if (value < 0 || value > 99)
+ {
throw new ArgumentOutOfRangeException(
nameof(PercentDecimalDigits),
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
+ SR.ArgumentOutOfRange_Range,
0,
99));
}
@@ -684,9 +747,11 @@ namespace System.Globalization {
}
- public String PercentDecimalSeparator {
+ public String PercentDecimalSeparator
+ {
get { return percentDecimalSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyDecimalSeparator(value, nameof(PercentDecimalSeparator));
percentDecimalSeparator = value;
@@ -694,9 +759,11 @@ namespace System.Globalization {
}
- public String PercentGroupSeparator {
+ public String PercentGroupSeparator
+ {
get { return percentGroupSeparator; }
- set {
+ set
+ {
VerifyWritable();
VerifyGroupSeparator(value, nameof(PercentGroupSeparator));
percentGroupSeparator = value;
@@ -704,14 +771,18 @@ namespace System.Globalization {
}
- public String PercentSymbol {
- get {
+ public String PercentSymbol
+ {
+ get
+ {
return percentSymbol;
}
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(PercentSymbol),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -720,12 +791,15 @@ namespace System.Globalization {
}
- public String PerMilleSymbol {
+ public String PerMilleSymbol
+ {
get { return perMilleSymbol; }
- set {
- if (value == null) {
+ set
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(PerMilleSymbol),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
VerifyWritable();
@@ -733,10 +807,9 @@ namespace System.Globalization {
}
}
-
- public String[] NativeDigits
+ public string [] NativeDigits
{
- get { return (String[])nativeDigits.Clone(); }
+ get { return (String[]) nativeDigits.Clone(); }
set
{
VerifyWritable();
@@ -747,25 +820,29 @@ namespace System.Globalization {
public DigitShapes DigitSubstitution
{
- get { return (DigitShapes)digitSubstitution; }
+ get { return (DigitShapes) digitSubstitution; }
set
{
VerifyWritable();
VerifyDigitSubstitution(value, nameof(DigitSubstitution));
- digitSubstitution = (int)value;
+ digitSubstitution = (int) value;
}
}
- public Object GetFormat(Type formatType) {
- return formatType == typeof(NumberFormatInfo)? this: null;
+ public Object GetFormat(Type formatType)
+ {
+ return formatType == typeof(NumberFormatInfo) ? this : null;
}
- public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) {
- if (nfi == null) {
+ public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi)
+ {
+ if (nfi == null)
+ {
throw new ArgumentNullException(nameof(nfi));
}
Contract.EndContractBlock();
- if (nfi.IsReadOnly) {
+ if (nfi.IsReadOnly)
+ {
return (nfi);
}
NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone());
@@ -780,27 +857,34 @@ namespace System.Globalization {
| NumberStyles.AllowThousands | NumberStyles.AllowExponent
| NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier);
- internal static void ValidateParseStyleInteger(NumberStyles style) {
+ internal static void ValidateParseStyleInteger(NumberStyles style)
+ {
// Check for undefined flags
- if ((style & InvalidNumberStyles) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style));
+ if ((style & InvalidNumberStyles) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
Contract.EndContractBlock();
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
- if ((style & ~NumberStyles.HexNumber) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidHexStyle"));
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // Check for hex number
+ if ((style & ~NumberStyles.HexNumber) != 0)
+ {
+ throw new ArgumentException(SR.Arg_InvalidHexStyle);
}
}
}
- internal static void ValidateParseStyleFloatingPoint(NumberStyles style) {
+ internal static void ValidateParseStyleFloatingPoint(NumberStyles style)
+ {
// Check for undefined flags
- if ((style & InvalidNumberStyles) != 0) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNumberStyles"), nameof(style));
+ if ((style & InvalidNumberStyles) != 0)
+ {
+ throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style));
}
Contract.EndContractBlock();
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number
- throw new ArgumentException(Environment.GetResourceString("Arg_HexStyleNotSupported"));
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // Check for hex number
+ throw new ArgumentException(SR.Arg_HexStyleNotSupported);
}
}
} // NumberFormatInfo
diff --git a/src/mscorlib/src/System/Globalization/NumberStyles.cs b/src/mscorlib/src/System/Globalization/NumberStyles.cs
deleted file mode 100644
index 969c07fc2a..0000000000
--- a/src/mscorlib/src/System/Globalization/NumberStyles.cs
+++ /dev/null
@@ -1,66 +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: Contains valid formats for Numbers recognized by
-** the Number class' parsing code.
-**
-**
-===========================================================*/
-namespace System.Globalization {
-
- using System;
- [Serializable]
- [Flags]
- public enum NumberStyles {
- // Bit flag indicating that leading whitespace is allowed. Character values
- // 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, and 0x0020 are considered to be
- // whitespace.
-
- None = 0x00000000,
-
- AllowLeadingWhite = 0x00000001,
-
- AllowTrailingWhite = 0x00000002, //Bitflag indicating trailing whitespace is allowed.
-
- AllowLeadingSign = 0x00000004, //Can the number start with a sign char.
- //Specified by NumberFormatInfo.PositiveSign and NumberFormatInfo.NegativeSign
-
- AllowTrailingSign = 0x00000008, //Allow the number to end with a sign char
-
- AllowParentheses = 0x00000010, //Allow the number to be enclosed in parens
-
- AllowDecimalPoint = 0x00000020, //Allow a decimal point
-
- AllowThousands = 0x00000040, //Allow thousands separators (more properly, allow group separators)
-
- AllowExponent = 0x00000080, //Allow an exponent
-
- AllowCurrencySymbol = 0x00000100, //Allow a currency symbol.
-
- AllowHexSpecifier = 0x00000200, //Allow specifiying hexadecimal.
- //Common uses. These represent some of the most common combinations of these flags.
-
-
- Integer = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign,
-
- HexNumber = AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier,
-
- Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
- AllowDecimalPoint | AllowThousands,
-
- Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
- AllowDecimalPoint | AllowExponent,
-
- Currency = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
- AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol,
-
- Any = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
- AllowParentheses | AllowDecimalPoint | AllowThousands | AllowCurrencySymbol | AllowExponent,
-
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/PersianCalendar.cs b/src/mscorlib/src/System/Globalization/PersianCalendar.cs
deleted file mode 100644
index e61a007a02..0000000000
--- a/src/mscorlib/src/System/Globalization/PersianCalendar.cs
+++ /dev/null
@@ -1,578 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about PersianCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
- // Modern Persian calendar is a solar observation based calendar. Each new year begins on the day when the vernal equinox occurs before noon.
- // The epoch is the date of the vernal equinox prior to the epoch of the Islamic calendar (March 19, 622 Julian or March 22, 622 Gregorian)
-
- // There is no Persian year 0. Ordinary years have 365 days. Leap years have 366 days with the last month (Esfand) gaining the extra day.
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 0622/03/22 9999/12/31
- ** Persian 0001/01/01 9378/10/13
- */
-
- [Serializable]
- public class PersianCalendar : Calendar {
-
-
- public static readonly int PersianEra = 1;
-
- internal static long PersianEpoch = new DateTime(622, 3, 22).Ticks / GregorianCalendar.TicksPerDay;
- const int ApproximateHalfYear = 180;
-
- internal const int DatePartYear = 0;
- internal const int DatePartDayOfYear = 1;
- internal const int DatePartMonth = 2;
- internal const int DatePartDay = 3;
- internal const int MonthsPerYear = 12;
-
- internal static int[] DaysToMonth = { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 };
-
- internal const int MaxCalendarYear = 9378;
- internal const int MaxCalendarMonth = 10;
- internal const int MaxCalendarDay = 13;
-
- // Persian calendar (year: 1, month: 1, day:1 ) = Gregorian (year: 622, month: 3, day: 22)
- // This is the minimal Gregorian date that we support in the PersianCalendar.
- internal static DateTime minDate = new DateTime(622, 3, 22);
- internal static DateTime maxDate = DateTime.MaxValue;
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of PersianCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance() {
- if (m_defaultInstance == null) {
- m_defaultInstance = new PersianCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (minDate);
- }
- }
-
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (maxDate);
- }
- }
-
- // Return the type of the Persian calendar.
- //
-
-
- public override CalendarAlgorithmType AlgorithmType {
- get {
- return CalendarAlgorithmType.SolarCalendar;
- }
- }
-
- // Construct an instance of Persian calendar.
-
- public PersianCalendar() {
- }
-
-
- internal override int BaseCalendarID {
- get {
- return (CAL_GREGORIAN);
- }
- }
-
- internal override int ID {
- get {
- return (CAL_PERSIAN);
- }
- }
-
-
- /*=================================GetAbsoluteDatePersian==========================
- **Action: Gets the Absolute date for the given Persian date. The absolute date means
- ** the number of days from January 1st, 1 A.D.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
-
- long GetAbsoluteDatePersian(int year, int month, int day) {
- if (year >= 1 && year <= MaxCalendarYear && month >= 1 && month <= 12)
- {
- int ordinalDay = DaysInPreviousMonths(month) + day - 1; // day is one based, make 0 based since this will be the number of days we add to beginning of year below
- int approximateDaysFromEpochForYearStart = (int)(CalendricalCalculationsHelper.MeanTropicalYearInDays * (year - 1));
- long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(PersianEpoch + approximateDaysFromEpochForYearStart + ApproximateHalfYear);
- yearStart += ordinalDay;
- return yearStart;
- }
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
-
- static internal void CheckTicksRange(long ticks) {
- if (ticks < minDate.Ticks || ticks > maxDate.Ticks) {
- throw new ArgumentOutOfRangeException(
- "time",
- String.Format(
- CultureInfo.InvariantCulture,
- Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
- minDate,
- maxDate));
- }
- }
-
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != PersianEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
- }
-
- static internal void CheckYearRange(int year, int era) {
- CheckEraRange(era);
- if (year < 1 || year > MaxCalendarYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxCalendarYear));
- }
- }
-
- static internal void CheckYearMonthRange(int year, int month, int era) {
- CheckYearRange(year, era);
- if (year == MaxCalendarYear) {
- if (month > MaxCalendarMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(month),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxCalendarMonth));
- }
- }
-
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
- }
-
- static int MonthFromOrdinalDay(int ordinalDay)
- {
- Debug.Assert(ordinalDay <= 366);
- int index = 0;
- while (ordinalDay > DaysToMonth[index])
- index++;
-
- return index;
- }
-
- static int DaysInPreviousMonths(int month)
- {
- Debug.Assert(1 <= month && month <= 12);
- --month; // months are one based but for calculations use 0 based
- return DaysToMonth[month];
- }
-
- /*=================================GetDatePart==========================
- **Action: Returns a given date part of this <i>DateTime</i>. This method is used
- ** to compute the year, day-of-year, month, or day part.
- **Returns:
- **Arguments:
- **Exceptions: ArgumentException if part is incorrect.
- ============================================================================*/
-
- internal int GetDatePart(long ticks, int part) {
- long NumDays; // The calculation buffer in number of days.
-
- CheckTicksRange(ticks);
-
- //
- // Get the absolute date. The absolute date is the number of days from January 1st, 1 A.D.
- // 1/1/0001 is absolute date 1.
- //
- NumDays = ticks / GregorianCalendar.TicksPerDay + 1;
-
- //
- // Calculate the appromixate Persian Year.
- //
-
- long yearStart = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(NumDays);
- int y = (int)(Math.Floor(((yearStart - PersianEpoch) / CalendricalCalculationsHelper.MeanTropicalYearInDays) + 0.5)) + 1;
- Debug.Assert(y >= 1);
-
- if (part == DatePartYear)
- {
- return y;
- }
-
- //
- // Calculate the Persian Month.
- //
-
- int ordinalDay = (int)(NumDays - CalendricalCalculationsHelper.GetNumberOfDays(this.ToDateTime(y, 1, 1, 0, 0, 0, 0, 1)));
-
- if (part == DatePartDayOfYear)
- {
- return ordinalDay;
- }
-
- int m = MonthFromOrdinalDay(ordinalDay);
- Debug.Assert(ordinalDay >= 1);
- Debug.Assert(m >= 1 && m <= 12);
- if (part == DatePartMonth)
- {
- return m;
- }
-
- int d = ordinalDay - DaysInPreviousMonths(m);
- Debug.Assert(1 <= d);
- Debug.Assert(d <= 31);
-
- //
- // Calculate the Persian Day.
- //
-
- if (part == DatePartDay)
- {
- return (d);
- }
-
- // Incorrect part value.
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DateTimeParsing"));
- }
-
- // Returns the DateTime resulting from adding the given number of
- // months to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year and month parts of the specified DateTime by
- // value months, and, if required, adjusting the day part of the
- // resulting date downwards to the last day of the resulting month in the
- // resulting year. The time-of-day part of the result is the same as the
- // time-of-day part of the specified DateTime.
- //
- // In more precise terms, considering the specified DateTime to be of the
- // form y / m / d + t, where y is the
- // year, m is the month, d is the day, and t is the
- // time-of-day, the result is y1 / m1 / d1 + t,
- // where y1 and m1 are computed by adding value months
- // to y and m, and d1 is the largest value less than
- // or equal to d that denotes a valid day in month m1 of year
- // y1.
- //
-
-
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
- throw new ArgumentOutOfRangeException(
- nameof(months),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- -120000,
- 120000));
- }
- Contract.EndContractBlock();
- // Get the date in Persian calendar.
- int y = GetDatePart(time.Ticks, DatePartYear);
- int m = GetDatePart(time.Ticks, DatePartMonth);
- int d = GetDatePart(time.Ticks, DatePartDay);
- int i = m - 1 + months;
- if (i >= 0) {
- m = i % 12 + 1;
- y = y + i / 12;
- } else {
- m = 12 + (i + 1) % 12;
- y = y + (i - 11) / 12;
- }
- int days = GetDaysInMonth(y, m);
- if (d > days) {
- d = days;
- }
- long ticks = GetAbsoluteDatePersian(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay;
- Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (new DateTime(ticks));
- }
-
- // Returns the DateTime resulting from adding the given number of
- // years to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year part of the specified DateTime by value
- // years. If the month and day of the specified DateTime is 2/29, and if the
- // resulting year is not a leap year, the month and day of the resulting
- // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
- // parts of the result are the same as those of the specified DateTime.
- //
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (AddMonths(time, years * 12));
- }
-
- // Returns the day-of-month part of the specified DateTime. The returned
- // value is an integer between 1 and 31.
- //
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDay));
- }
-
- // Returns the day-of-week part of the specified DateTime. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
- }
-
- // Returns the day-of-year part of the specified DateTime. The returned value
- // is an integer between 1 and 366.
- //
-
-
- public override int GetDayOfYear(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartDayOfYear));
- }
-
- // Returns the number of days in the month given by the year and
- // month arguments.
- //
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- CheckYearMonthRange(year, month, era);
-
- if ((month==MaxCalendarMonth) && (year==MaxCalendarYear)) {
- return MaxCalendarDay;
- }
-
- int daysInMonth = DaysToMonth[month] - DaysToMonth[month - 1];
- if ((month == MonthsPerYear) && !IsLeapYear(year))
- {
- Debug.Assert(daysInMonth == 30);
- --daysInMonth;
- }
- return daysInMonth;
- }
-
- // Returns the number of days in the year given by the year argument for the current era.
- //
-
- public override int GetDaysInYear(int year, int era) {
- CheckYearRange(year, era);
- if (year==MaxCalendarYear) {
- return DaysToMonth[MaxCalendarMonth-1] + MaxCalendarDay;
- }
- // Common years have 365 days. Leap years have 366 days.
- return (IsLeapYear(year, CurrentEra) ? 366: 365);
- }
-
- // Returns the era for the specified DateTime value.
-
-
- public override int GetEra(DateTime time) {
- CheckTicksRange(time.Ticks);
- return (PersianEra);
- }
-
-
-
- public override int[] Eras {
- get {
- return (new int[] {PersianEra});
- }
- }
-
- // Returns the month part of the specified DateTime. The returned value is an
- // integer between 1 and 12.
- //
-
-
- public override int GetMonth(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartMonth));
- }
-
- // Returns the number of months in the specified year and era.
-
-
- public override int GetMonthsInYear(int year, int era) {
- CheckYearRange(year, era);
- if (year==MaxCalendarYear) {
- return MaxCalendarMonth;
- }
- return (12);
- }
-
- // Returns the year part of the specified DateTime. The returned value is an
- // integer between 1 and MaxCalendarYear.
- //
-
-
- public override int GetYear(DateTime time) {
- return (GetDatePart(time.Ticks, DatePartYear));
- }
-
- // Checks whether a given day in the specified era is a leap day. This method returns true if
- // the date is a leap day, or false if not.
- //
-
-
- public override bool IsLeapDay(int year, int month, int day, int era) {
- // The year/month/era value checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Day"),
- daysInMonth,
- month));
- }
- return (IsLeapYear(year, era) && month == 12 && day == 30);
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
-
- public override int GetLeapMonth(int year, int era)
- {
- CheckYearRange(year, era);
- return (0);
- }
-
- // Checks whether a given month in the specified era is a leap month. This method returns true if
- // month is a leap month, or false if not.
- //
-
-
- public override bool IsLeapMonth(int year, int month, int era) {
- CheckYearMonthRange(year, month, era);
- return (false);
- }
-
- // Checks whether a given year in the specified era is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
-
- public override bool IsLeapYear(int year, int era) {
- CheckYearRange(year, era);
-
- if (year == MaxCalendarYear)
- {
- return false;
- }
-
- return (GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1)) == 366;
- }
-
- // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
- //
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- // The year/month/era checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
- BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Day"),
- daysInMonth,
- month));
- }
-
- long lDate = GetAbsoluteDatePersian(year, month, day);
-
- if (lDate >= 0) {
- return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
- } else {
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1410;
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > MaxCalendarYear)
- {
- throw new ArgumentOutOfRangeException(
- nameof(value),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- MaxCalendarYear));
- }
- twoDigitYearMax = value;
- }
- }
-
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- if (year < 100) {
- return (base.ToFourDigitYear(year));
- }
-
- if (year > MaxCalendarYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- MaxCalendarYear));
- }
- return (year);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/RegionInfo.cs b/src/mscorlib/src/System/Globalization/RegionInfo.cs
index b719af7128..c3d5e659ca 100644
--- a/src/mscorlib/src/System/Globalization/RegionInfo.cs
+++ b/src/mscorlib/src/System/Globalization/RegionInfo.cs
@@ -2,7 +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.
-
////////////////////////////////////////////////////////////////////////////
//
//
@@ -15,15 +14,14 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
- [Serializable]
- public partial class RegionInfo
+namespace System.Globalization
+{
+ [Serializable]
+ public class RegionInfo
{
//--------------------------------------------------------------------//
// Internal Information //
@@ -36,12 +34,12 @@ namespace System.Globalization {
//
// Name of this region (ie: es-US): serialized, the field used for deserialization
//
- internal String m_name;
+ internal String _name;
//
// The CultureData instance that we are going to read data from.
//
- [NonSerialized]internal CultureData m_cultureData;
+ internal CultureData _cultureData;
//
// The RegionInfo for our current region
@@ -59,125 +57,94 @@ namespace System.Globalization {
// In Silverlight we enforce that RegionInfos must be created with a full culture name
//
////////////////////////////////////////////////////////////////////////
- public RegionInfo(String name) {
- if (name==null)
+ public RegionInfo(String name)
+ {
+ if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0) //The InvariantCulture has no matching region
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"), nameof(name));
+ {
+ throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name));
}
-
+
Contract.EndContractBlock();
//
- // First try it as an entire culture. We must have user override as true here so
- // that we can pick up custom cultures *before* built-in ones (if they want to
- // prefer built-in cultures they will pass "us" instead of "en-US").
+ // For CoreCLR we only want the region names that are full culture names
//
- this.m_cultureData = CultureData.GetCultureDataForRegion(name,true);
- // this.m_name = name.ToUpper(CultureInfo.InvariantCulture);
-
- if (this.m_cultureData == null)
+ _cultureData = CultureData.GetCultureDataForRegion(name, true);
+ if (_cultureData == null)
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_InvalidCultureName"), name), nameof(name));
+ SR.Argument_InvalidCultureName, name), nameof(name));
// Not supposed to be neutral
- if (this.m_cultureData.IsNeutralCulture)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNeutralRegionName", name), nameof(name));
+ if (_cultureData.IsNeutralCulture)
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name));
SetName(name);
}
-#if FEATURE_USE_LCID
- // We'd rather people use the named version since this doesn't allow custom locales
public RegionInfo(int culture)
{
if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region
{
- throw new ArgumentException(Environment.GetResourceString("Argument_NoRegionInvariantCulture"));
+ throw new ArgumentException(SR.Argument_NoRegionInvariantCulture);
}
-
+
if (culture == CultureInfo.LOCALE_NEUTRAL)
{
// Not supposed to be neutral
- throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), nameof(culture));
+ throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture));
}
if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT)
{
// Not supposed to be neutral
- throw new ArgumentException(Environment.GetResourceString("Argument_CustomCultureCannotBePassedByNumber", culture), nameof(culture));
+ throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture));
}
- this.m_cultureData = CultureData.GetCultureData(culture,true);
- this.m_name = this.m_cultureData.SREGIONNAME;
+ _cultureData = CultureData.GetCultureData(culture, true);
+ _name = _cultureData.SREGIONNAME;
- if (this.m_cultureData.IsNeutralCulture)
+ if (_cultureData.IsNeutralCulture)
{
// Not supposed to be neutral
- throw new ArgumentException(Environment.GetResourceString("Argument_CultureIsNeutral", culture), nameof(culture));
+ throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture));
}
- m_cultureId = culture;
}
-#endif
-
+
internal RegionInfo(CultureData cultureData)
{
- this.m_cultureData = cultureData;
- this.m_name = this.m_cultureData.SREGIONNAME;
+ _cultureData = cultureData;
+ _name = _cultureData.SREGIONNAME;
}
private void SetName(string name)
{
// Use the name of the region we found
- this.m_name = this.m_cultureData.SREGIONNAME;
+ _name = _cultureData.SREGIONNAME;
}
-#region Serialization
- //
- // m_cultureId is needed for serialization only to detect the case if the region info is created using the name or using the LCID.
- // in case m_cultureId is zero means that the RigionInfo is created using name. otherwise it is created using LCID.
- //
-
- [OptionalField(VersionAdded = 2)]
- int m_cultureId;
- // the following field is defined to keep the compatibility with Everett.
- // don't change/remove the names/types of these field.
- [OptionalField(VersionAdded = 2)]
- internal int m_dataItem = 0;
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx) { }
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
- // This won't happen anyway since CoreCLR doesn't support serialization
- this.m_cultureData = CultureData.GetCultureData(m_name, true);
-
- if (this.m_cultureData == null)
- throw new ArgumentException(
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("Argument_InvalidCultureName"), m_name), nameof(m_name));
+ _cultureData = CultureData.GetCultureData(_name, true);
- if (m_cultureId == 0)
+ if (_cultureData == null)
{
- SetName(this.m_name);
- }
- else
- {
- this.m_name = this.m_cultureData.SREGIONNAME;
+ throw new ArgumentException(
+ String.Format(CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, _name),
+ "_name");
}
- }
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
- // Used to fill in everett data item, unnecessary now
- }
-#endregion Serialization
+ _name = _cultureData.SREGIONNAME;
+ }
////////////////////////////////////////////////////////////////////////
//
@@ -188,15 +155,17 @@ namespace System.Globalization {
// thread.
//
////////////////////////////////////////////////////////////////////////
- public static RegionInfo CurrentRegion {
- get {
+ public static RegionInfo CurrentRegion
+ {
+ get
+ {
RegionInfo temp = s_currentRegionInfo;
if (temp == null)
{
- temp = new RegionInfo(CultureInfo.CurrentCulture.m_cultureData);
+ temp = new RegionInfo(CultureInfo.CurrentCulture._cultureData);
// Need full name for custom cultures
- temp.m_name=temp.m_cultureData.SREGIONNAME;
+ temp._name = temp._cultureData.SREGIONNAME;
s_currentRegionInfo = temp;
}
return temp;
@@ -210,10 +179,12 @@ namespace System.Globalization {
// Returns the name of the region (ie: en-US)
//
////////////////////////////////////////////////////////////////////////
- public virtual String Name {
- get {
- Debug.Assert(m_name != null, "Expected RegionInfo.m_name to be populated already");
- return (m_name);
+ public virtual String Name
+ {
+ get
+ {
+ Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already");
+ return (_name);
}
}
@@ -228,7 +199,7 @@ namespace System.Globalization {
{
get
{
- return (this.m_cultureData.SENGCOUNTRY);
+ return (_cultureData.SENGCOUNTRY);
}
}
@@ -241,11 +212,11 @@ namespace System.Globalization {
// if the current UI language is en-US)
//
////////////////////////////////////////////////////////////////////////
- public virtual String DisplayName
+ public virtual String DisplayName
{
- get
+ get
{
- return (this.m_cultureData.SLOCALIZEDCOUNTRY);
+ return (_cultureData.SLOCALIZEDCOUNTRY);
}
}
@@ -262,7 +233,7 @@ namespace System.Globalization {
{
get
{
- return (this.m_cultureData.SNATIVECOUNTRY);
+ return (_cultureData.SNATIVECOUNTRY);
}
}
@@ -277,11 +248,10 @@ namespace System.Globalization {
{
get
{
- return (this.m_cultureData.SISO3166CTRYNAME);
+ return (_cultureData.SISO3166CTRYNAME);
}
}
-
////////////////////////////////////////////////////////////////////////
//
// ThreeLetterISORegionName
@@ -293,7 +263,7 @@ namespace System.Globalization {
{
get
{
- return (this.m_cultureData.SISO3166CTRYNAME2);
+ return (_cultureData.SISO3166CTRYNAME2);
}
}
@@ -308,10 +278,12 @@ namespace System.Globalization {
{
get
{
- return (this.m_cultureData.SABBREVCTRYNAME);
+ // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName
+ return ThreeLetterISORegionName;
}
}
+
////////////////////////////////////////////////////////////////////////
//
// IsMetric
@@ -319,19 +291,20 @@ namespace System.Globalization {
// Returns true if this region uses the metric measurement system
//
////////////////////////////////////////////////////////////////////////
- public virtual bool IsMetric {
- get {
- int value = this.m_cultureData.IMEASURE;
- return (value==0);
+ public virtual bool IsMetric
+ {
+ get
+ {
+ int value = _cultureData.IMEASURE;
+ return (value == 0);
}
}
-
public virtual int GeoId
{
- get
+ get
{
- return (this.m_cultureData.IGEOID);
+ return (_cultureData.IGEOID);
}
}
@@ -342,27 +315,27 @@ namespace System.Globalization {
// English name for this region's currency, ie: Swiss Franc
//
////////////////////////////////////////////////////////////////////////
- public virtual String CurrencyEnglishName
+ public virtual string CurrencyEnglishName
{
get
{
- return (this.m_cultureData.SENGLISHCURRENCY);
+ return (_cultureData.SENGLISHCURRENCY);
}
}
////////////////////////////////////////////////////////////////////////
//
- // CurrencyEnglishName
+ // CurrencyNativeName
//
- // English name for this region's currency, ie: Schweizer Franken
+ // Native name for this region's currency, ie: Schweizer Franken
// WARNING: You need a full locale name for this to make sense.
//
////////////////////////////////////////////////////////////////////////
- public virtual String CurrencyNativeName
+ public virtual string CurrencyNativeName
{
get
{
- return (this.m_cultureData.SNATIVECURRENCY);
+ return (_cultureData.SNATIVECURRENCY);
}
}
@@ -373,9 +346,11 @@ namespace System.Globalization {
// Currency Symbol for this locale, ie: Fr. or $
//
////////////////////////////////////////////////////////////////////////
- public virtual String CurrencySymbol {
- get {
- return (this.m_cultureData.SCURRENCY);
+ public virtual String CurrencySymbol
+ {
+ get
+ {
+ return (_cultureData.SCURRENCY);
}
}
@@ -386,9 +361,11 @@ namespace System.Globalization {
// ISO Currency Symbol for this locale, ie: CHF
//
////////////////////////////////////////////////////////////////////////
- public virtual String ISOCurrencySymbol {
- get {
- return (this.m_cultureData.SINTLSYMBOL);
+ public virtual String ISOCurrencySymbol
+ {
+ get
+ {
+ return (_cultureData.SINTLSYMBOL);
}
}
@@ -439,6 +416,6 @@ namespace System.Globalization {
public override String ToString()
{
return (Name);
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Globalization/SortKey.cs b/src/mscorlib/src/System/Globalization/SortKey.cs
index 7c7408b009..0930965e5d 100644
--- a/src/mscorlib/src/System/Globalization/SortKey.cs
+++ b/src/mscorlib/src/System/Globalization/SortKey.cs
@@ -11,8 +11,8 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
+namespace System.Globalization
+{
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
@@ -25,21 +25,17 @@ namespace System.Globalization {
//--------------------------------------------------------------------//
// Internal Information //
//--------------------------------------------------------------------//
-
- //
- // Variables.
- //
[OptionalField(VersionAdded = 3)]
- internal String localeName; // locale identifier
+ internal string _localeName; // locale identifier
[OptionalField(VersionAdded = 1)] // LCID field so serialization is Whidbey compatible though we don't officially support it
- internal int win32LCID;
+ internal int _win32LCID;
// Whidbey serialization
- internal CompareOptions options; // options
- internal String m_String; // original string
- internal byte[] m_KeyData; // sortkey data
+ internal CompareOptions _options; // options
+ internal string _string; // original string
+ internal byte[] _keyData; // sortkey data
//
// The following constructor is designed to be called from CompareInfo to get the
@@ -47,20 +43,19 @@ namespace System.Globalization {
//
internal SortKey(String localeName, String str, CompareOptions options, byte[] keyData)
{
- this.m_KeyData = keyData;
- this.localeName = localeName;
- this.options = options;
- this.m_String = str;
+ _keyData = keyData;
+ _localeName = localeName;
+ _options = options;
+ _string = str;
}
-#if FEATURE_USE_LCID
[OnSerializing]
private void OnSerializing(StreamingContext context)
{
//set LCID to proper value for Whidbey serialization (no other use)
- if (win32LCID == 0)
+ if (_win32LCID == 0)
{
- win32LCID = CultureInfo.GetCultureInfo(localeName).LCID;
+ _win32LCID = CultureInfo.GetCultureInfo(_localeName).LCID;
}
}
@@ -68,13 +63,12 @@ namespace System.Globalization {
private void OnDeserialized(StreamingContext context)
{
//set locale name to proper value after Whidbey deserialization
- if (String.IsNullOrEmpty(localeName) && win32LCID != 0)
+ if (String.IsNullOrEmpty(_localeName) && _win32LCID != 0)
{
- localeName = CultureInfo.GetCultureInfo(win32LCID).Name;
+ _localeName = CultureInfo.GetCultureInfo(_win32LCID).Name;
}
}
-#endif //FEATURE_USE_LCID
-
+
////////////////////////////////////////////////////////////////////////
//
// GetOriginalString
@@ -85,12 +79,12 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public virtual String OriginalString
{
- get {
- return (m_String);
+ get
+ {
+ return (_string);
}
}
-
////////////////////////////////////////////////////////////////////////
//
// GetKeyData
@@ -101,12 +95,12 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public virtual byte[] KeyData
{
- get {
- return (byte[])(m_KeyData.Clone());
+ get
+ {
+ return (byte[])(_keyData.Clone());
}
}
-
////////////////////////////////////////////////////////////////////////
//
// Compare
@@ -116,45 +110,49 @@ namespace System.Globalization {
// and a number greater than 0 if sortkey1 is greater than sortkey2.
//
////////////////////////////////////////////////////////////////////////
- public static int Compare(SortKey sortkey1, SortKey sortkey2) {
-
- if (sortkey1==null || sortkey2==null) {
- throw new ArgumentNullException((sortkey1==null ? nameof(sortkey1): nameof(sortkey2)));
+ public static int Compare(SortKey sortkey1, SortKey sortkey2)
+ {
+ if (sortkey1==null || sortkey2==null)
+ {
+ throw new ArgumentNullException((sortkey1 == null ? nameof(sortkey1) : nameof(sortkey2)));
}
Contract.EndContractBlock();
+ byte[] key1Data = sortkey1._keyData;
+ byte[] key2Data = sortkey2._keyData;
- byte[] key1Data = sortkey1.m_KeyData;
- byte[] key2Data = sortkey2.m_KeyData;
-
- Debug.Assert(key1Data!=null, "key1Data!=null");
- Debug.Assert(key2Data!=null, "key2Data!=null");
+ Debug.Assert(key1Data != null, "key1Data != null");
+ Debug.Assert(key2Data != null, "key2Data != null");
- if (key1Data.Length == 0) {
- if (key2Data.Length == 0) {
+ if (key1Data.Length == 0)
+ {
+ if (key2Data.Length == 0)
+ {
return (0);
}
return (-1);
}
- if (key2Data.Length == 0) {
+ if (key2Data.Length == 0)
+ {
return (1);
}
-
- int compLen = (key1Data.Length<key2Data.Length)?key1Data.Length:key2Data.Length;
- for (int i=0; i<compLen; i++) {
- if (key1Data[i]>key2Data[i]) {
+ int compLen = (key1Data.Length < key2Data.Length) ? key1Data.Length : key2Data.Length;
+
+ for (int i=0; i<compLen; i++)
+ {
+ if (key1Data[i]>key2Data[i])
+ {
return (1);
}
- if (key1Data[i]<key2Data[i]) {
+ if (key1Data[i]<key2Data[i])
+ {
return (-1);
}
}
-
+
return 0;
-
}
-
-
+
////////////////////////////////////////////////////////////////////////
//
// Equals
@@ -166,7 +164,7 @@ namespace System.Globalization {
public override bool Equals(Object value)
{
SortKey that = value as SortKey;
-
+
if (that != null)
{
return Compare(this, that) == 0;
@@ -174,8 +172,7 @@ namespace System.Globalization {
return (false);
}
-
-
+
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
@@ -187,11 +184,9 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
- return (CompareInfo.GetCompareInfo(
- this.localeName).GetHashCodeOfString(this.m_String, this.options));
+ return (CompareInfo.GetCompareInfo(_localeName).GetHashCodeOfString(_string, _options));
}
-
-
+
////////////////////////////////////////////////////////////////////////
//
// ToString
@@ -202,7 +197,7 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
- return ("SortKey - " + localeName + ", " + options + ", " + m_String);
+ return ("SortKey - " + _localeName + ", " + _options + ", " + _string);
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/SortVersion.cs b/src/mscorlib/src/System/Globalization/SortVersion.cs
deleted file mode 100644
index 24fe8546fc..0000000000
--- a/src/mscorlib/src/System/Globalization/SortVersion.cs
+++ /dev/null
@@ -1,102 +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.
-
-namespace System.Globalization
-{
- using System;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- public sealed class SortVersion : IEquatable<SortVersion>
- {
- private int m_NlsVersion;
- private Guid m_SortId;
-
- public int FullVersion
- {
- get
- {
- return m_NlsVersion;
- }
- }
-
- public Guid SortId
- {
- get
- {
- return m_SortId;
- }
- }
-
- public SortVersion(int fullVersion, Guid sortId)
- {
- m_SortId = sortId;
- m_NlsVersion = fullVersion;
- }
-
- internal SortVersion(int nlsVersion, int effectiveId, Guid customVersion)
- {
- m_NlsVersion = nlsVersion;
-
- if (customVersion == Guid.Empty)
- {
- byte[] b = BitConverter.GetBytes(effectiveId);
- byte b1 = (byte) ((uint) effectiveId >> 24);
- byte b2 = (byte) ((effectiveId & 0x00FF0000) >> 16);
- byte b3 = (byte) ((effectiveId & 0x0000FF00) >> 8);
- byte b4 = (byte) (effectiveId & 0xFF);
- customVersion = new Guid(0,0,0,0,0,0,0,b1,b2,b3,b4);
- }
-
- m_SortId = customVersion;
- }
-
- public override bool Equals(object obj)
- {
- SortVersion n = obj as SortVersion;
- if(n != null)
- {
- return this.Equals(n);
- }
-
- return false;
- }
-
- public bool Equals(SortVersion other)
- {
- if (other == null)
- {
- return false;
- }
-
- return m_NlsVersion == other.m_NlsVersion && m_SortId == other.m_SortId;
- }
-
- public override int GetHashCode()
- {
- return m_NlsVersion * 7 | m_SortId.GetHashCode();
- }
-
- public static bool operator ==(SortVersion left, SortVersion right)
- {
- if (((object) left) != null)
- {
- return left.Equals(right);
- }
-
- if (((object) right) != null)
- {
- return right.Equals(left);
- }
-
- // Both null.
- return true;
- }
-
- public static bool operator !=(SortVersion left, SortVersion right)
- {
- return !(left == right);
- }
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Globalization/StringInfo.cs b/src/mscorlib/src/System/Globalization/StringInfo.cs
index dc32fe9493..f1dd30561b 100644
--- a/src/mscorlib/src/System/Globalization/StringInfo.cs
+++ b/src/mscorlib/src/System/Globalization/StringInfo.cs
@@ -12,158 +12,166 @@
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
-
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+namespace System.Globalization
+{
[Serializable]
- public class StringInfo
+ public class StringInfo
{
-
[OptionalField(VersionAdded = 2)]
- private String m_str;
-
- // We allow this class to be serialized but there is no conceivable reason
- // for them to do so. Thus, we do not serialize the instance variables.
- [NonSerialized] private int[] m_indexes;
+ private string _str;
+
+ [NonSerialized]
+ private int[] _indexes;
// Legacy constructor
- public StringInfo() : this(""){}
+ public StringInfo() : this("") { }
// Primary, useful constructor
- public StringInfo(String value) {
+ public StringInfo(string value)
+ {
this.String = value;
}
-
-#region Serialization
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- m_str = String.Empty;
- }
+
+ [OnDeserializing]
+ private void OnDeserializing(StreamingContext ctx)
+ {
+ _str = String.Empty;
+ }
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
- if (m_str.Length == 0)
+ if (_str.Length == 0)
{
- m_indexes = null;
+ _indexes = null;
}
- }
-#endregion Serialization
+ }
public override bool Equals(Object value)
{
StringInfo that = value as StringInfo;
if (that != null)
{
- return (this.m_str.Equals(that.m_str));
+ return (_str.Equals(that._str));
}
return (false);
}
public override int GetHashCode()
{
- return this.m_str.GetHashCode();
+ return _str.GetHashCode();
}
// Our zero-based array of index values into the string. Initialize if
// our private array is not yet, in fact, initialized.
- private int[] Indexes {
- get {
- if((null == this.m_indexes) && (0 < this.String.Length)) {
- this.m_indexes = StringInfo.ParseCombiningCharacters(this.String);
+ private int[] Indexes
+ {
+ get
+ {
+ if ((null == _indexes) && (0 < this.String.Length))
+ {
+ _indexes = StringInfo.ParseCombiningCharacters(this.String);
}
- return(this.m_indexes);
+ return (_indexes);
}
}
- public String String {
- get {
- return(this.m_str);
+ public string String
+ {
+ get
+ {
+ return (_str);
}
- set {
- if (null == value) {
- throw new ArgumentNullException(nameof(String),
- Environment.GetResourceString("ArgumentNull_String"));
+ set
+ {
+ if (null == value)
+ {
+ throw new ArgumentNullException("String",
+ SR.ArgumentNull_String);
}
Contract.EndContractBlock();
- this.m_str = value;
- this.m_indexes = null;
+ _str = value;
+ _indexes = null;
}
}
- public int LengthInTextElements {
- get {
- if(null == this.Indexes) {
+ public int LengthInTextElements
+ {
+ get
+ {
+ if (null == this.Indexes)
+ {
// Indexes not initialized, so assume length zero
- return(0);
+ return (0);
}
- return(this.Indexes.Length);
+ return (this.Indexes.Length);
}
}
- public String SubstringByTextElements(int startingTextElement) {
+ public string SubstringByTextElements(int startingTextElement)
+ {
// If the string is empty, no sense going further.
- if(null == this.Indexes) {
+ if (null == this.Indexes)
+ {
// Just decide which error to give depending on the param they gave us....
- if(startingTextElement < 0) {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ if (startingTextElement < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
}
- else {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement),
- Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
+ else
+ {
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
}
}
- return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement));
+ return (SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement));
}
- public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) {
-
- //
- // Parameter checking
- //
- if(startingTextElement < 0) {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
+ {
+ if (startingTextElement < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.ArgumentOutOfRange_NeedPosNum);
}
- if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) {
- throw new ArgumentOutOfRangeException(nameof(startingTextElement),
- Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
+ if (this.String.Length == 0 || startingTextElement >= Indexes.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startingTextElement), SR.Arg_ArgumentOutOfRangeException);
}
- if(lengthInTextElements < 0) {
- throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ if (lengthInTextElements < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.ArgumentOutOfRange_NeedPosNum);
}
- if(startingTextElement > this.Indexes.Length - lengthInTextElements) {
- throw new ArgumentOutOfRangeException(nameof(lengthInTextElements),
- Environment.GetResourceString("Arg_ArgumentOutOfRangeException"));
+ if (startingTextElement > Indexes.Length - lengthInTextElements)
+ {
+ throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), SR.Arg_ArgumentOutOfRangeException);
}
- int start = this.Indexes[startingTextElement];
+ int start = Indexes[startingTextElement];
- if(startingTextElement + lengthInTextElements == this.Indexes.Length) {
+ if (startingTextElement + lengthInTextElements == Indexes.Length)
+ {
// We are at the last text element in the string and because of that
// must handle the call differently.
- return(this.String.Substring(start));
+ return (this.String.Substring(start));
}
- else {
- return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start)));
+ else
+ {
+ return (this.String.Substring(start, (Indexes[lengthInTextElements + startingTextElement] - start)));
}
}
-
- public static String GetNextTextElement(String str)
+
+ public static string GetNextTextElement(string str)
{
return (GetNextTextElement(str, 0));
}
@@ -200,8 +208,8 @@ namespace System.Globalization {
// currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element.
//
////////////////////////////////////////////////////////////////////////
-
- internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
+
+ internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
@@ -214,30 +222,34 @@ namespace System.Globalization {
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
- if (CharUnicodeInfo.IsCombiningCategory(ucNext)) {
+ if (CharUnicodeInfo.IsCombiningCategory(ucNext))
+ {
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
- if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
- || (ucCurrent == UnicodeCategory.Format)
- || (ucCurrent == UnicodeCategory.Control)
+ if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
+ || (ucCurrent == UnicodeCategory.Format)
+ || (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
- {
- // Will fall thru and return the currentCharCount
- } else {
+ {
+ // Will fall thru and return the currentCharCount
+ }
+ else
+ {
int startIndex = index; // Remember the current index.
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
-
+
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
- if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) {
+ if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
+ {
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
@@ -254,27 +266,31 @@ namespace System.Globalization {
currentCharCount = nextCharCount;
return (ret);
}
-
+
// Returns the str containing the next text element in str starting at
// index index. If index is not supplied, then it will start at the beginning
// of str. It recognizes a base character plus one or more combining
// characters or a properly formed surrogate pair as a text element. See also
// the ParseCombiningCharacters() and the ParseSurrogates() methods.
- public static String GetNextTextElement(String str, int index) {
+ public static string GetNextTextElement(string str, int index)
+ {
//
// Validate parameters.
//
- if (str==null) {
+ if (str == null)
+ {
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
-
+
int len = str.Length;
- if (index < 0 || index >= len) {
- if (index == len) {
+ if (index < 0 || index >= len)
+ {
+ if (index == len)
+ {
return (String.Empty);
- }
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ }
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
int charLen;
@@ -282,26 +298,26 @@ namespace System.Globalization {
return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen)));
}
- public static TextElementEnumerator GetTextElementEnumerator(String str)
+ public static TextElementEnumerator GetTextElementEnumerator(string str)
{
return (GetTextElementEnumerator(str, 0));
}
-
- public static TextElementEnumerator GetTextElementEnumerator(String str, int index)
+
+ public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
{
//
// Validate parameters.
//
- if (str==null)
+ if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
-
+
int len = str.Length;
if (index < 0 || (index > len))
{
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
}
return (new TextElementEnumerator(str, index, len));
@@ -319,14 +335,14 @@ namespace System.Globalization {
* return the indices: 0, 2, 4.
*/
- public static int[] ParseCombiningCharacters(String str)
+ public static int[] ParseCombiningCharacters(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
-
+
int len = str.Length;
int[] result = new int[len];
if (len == 0)
@@ -338,11 +354,12 @@ namespace System.Globalization {
int i = 0;
int currentCharLen;
- UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
-
- while (i < len) {
+ UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
+
+ while (i < len)
+ {
result[resultCount++] = i;
- i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
+ i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
@@ -352,7 +369,6 @@ namespace System.Globalization {
return (returnArray);
}
return (result);
-
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/Tables/charinfo.nlp b/src/mscorlib/src/System/Globalization/Tables/charinfo.nlp
deleted file mode 100644
index 2d5444f524..0000000000
--- a/src/mscorlib/src/System/Globalization/Tables/charinfo.nlp
+++ /dev/null
Binary files differ
diff --git a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
deleted file mode 100644
index ec84a06b76..0000000000
--- a/src/mscorlib/src/System/Globalization/TaiwanCalendar.cs
+++ /dev/null
@@ -1,256 +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.
-
-namespace System.Globalization {
-
- using System;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
- /* SSS_DROP_BEGIN */ /* SSS_WARNINGS_OFF */
- /*=================================TaiwanCalendar==========================
- **
- ** Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar.
- ** That is,
- ** Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01
- **
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1912/01/01 9999/12/31
- ** Taiwan 01/01/01 8088/12/31
- ============================================================================*/
- /* SSS_WARNINGS_ON */ /* SSS_DROP_END */
-
- [Serializable] public class TaiwanCalendar: Calendar {
- //
- // The era value for the current era.
- //
-
- // Since
- // Gregorian Year = Era Year + yearOffset
- // When Gregorian Year 1912 is year 1, so that
- // 1912 = 1 + yearOffset
- // So yearOffset = 1911
- //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
-
- // Initialize our era info.
- static internal EraInfo[] taiwanEraInfo = new EraInfo[] {
- new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
- };
-
- internal static volatile Calendar s_defaultInstance;
-
- internal GregorianCalendarHelper helper;
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of TaiwanCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
-
- internal static Calendar GetDefaultInstance() {
- if (s_defaultInstance == null) {
- s_defaultInstance = new TaiwanCalendar();
- }
- return (s_defaultInstance);
- }
-
- internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1);
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (calendarMinValue);
- }
- }
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (DateTime.MaxValue);
- }
- }
-
- // Return the type of the Taiwan calendar.
- //
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.SolarCalendar;
- }
- }
-
-
- public TaiwanCalendar() {
- try {
- new CultureInfo("zh-TW");
- } catch (ArgumentException e) {
- throw new TypeInitializationException(this.GetType().FullName, e);
- }
- helper = new GregorianCalendarHelper(this, taiwanEraInfo);
- }
-
- internal override int ID {
- get {
- return (CAL_TAIWAN);
- }
- }
-
-
- public override DateTime AddMonths(DateTime time, int months) {
- return (helper.AddMonths(time, months));
- }
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (helper.AddYears(time, years));
- }
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- return (helper.GetDaysInMonth(year, month, era));
- }
-
-
- public override int GetDaysInYear(int year, int era) {
- return (helper.GetDaysInYear(year, era));
- }
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (helper.GetDayOfMonth(time));
- }
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return (helper.GetDayOfWeek(time));
- }
-
-
- public override int GetDayOfYear(DateTime time)
- {
- return (helper.GetDayOfYear(time));
- }
-
-
- public override int GetMonthsInYear(int year, int era) {
- return (helper.GetMonthsInYear(year, era));
- }
-
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
- {
- return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
- }
-
-
- public override int GetEra(DateTime time) {
- return (helper.GetEra(time));
- }
-
- public override int GetMonth(DateTime time) {
- return (helper.GetMonth(time));
- }
-
-
- public override int GetYear(DateTime time) {
- return (helper.GetYear(time));
- }
-
-
- public override bool IsLeapDay(int year, int month, int day, int era)
- {
- return (helper.IsLeapDay(year, month, day, era));
- }
-
-
- public override bool IsLeapYear(int year, int era) {
- return (helper.IsLeapYear(year, era));
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era)
- {
- return (helper.GetLeapMonth(year, era));
- }
-
-
- public override bool IsLeapMonth(int year, int month, int era) {
- return (helper.IsLeapMonth(year, month, era));
- }
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
- }
-
-
- public override int[] Eras {
- get {
- return (helper.Eras);
- }
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99;
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > helper.MaxYear)
- {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- helper.MaxYear));
-
- }
- twoDigitYearMax = value;
- }
- }
-
- // For Taiwan calendar, four digit year is not used.
- // Therefore, for any two digit number, we just return the original number.
-
- public override int ToFourDigitYear(int year) {
- if (year <= 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- }
- Contract.EndContractBlock();
-
- if (year > helper.MaxYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 1,
- helper.MaxYear));
- }
- return (year);
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs b/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs
deleted file mode 100644
index d96c450f49..0000000000
--- a/src/mscorlib/src/System/Globalization/TaiwanLunisolarCalendar.cs
+++ /dev/null
@@ -1,330 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics.Contracts;
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about TaiwanLunisolarCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1912/02/18 2051/02/10
- ** TaiwanLunisolar 1912/01/01 2050/13/29
- */
-
- [Serializable]
- public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar {
-
- // Since
- // Gregorian Year = Era Year + yearOffset
- // When Gregorian Year 1912 is year 1, so that
- // 1912 = 1 + yearOffset
- // So yearOffset = 1911
- //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911);
-
- // Initialize our era info.
- static internal EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] {
- new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear
- };
-
- internal GregorianCalendarHelper helper;
-
- internal const int MIN_LUNISOLAR_YEAR = 1912;
- internal const int MAX_LUNISOLAR_YEAR = 2050;
-
- internal const int MIN_GREGORIAN_YEAR = 1912;
- internal const int MIN_GREGORIAN_MONTH = 2;
- internal const int MIN_GREGORIAN_DAY = 18;
-
- internal const int MAX_GREGORIAN_YEAR = 2051;
- internal const int MAX_GREGORIAN_MONTH = 2;
- internal const int MAX_GREGORIAN_DAY = 10;
-
- internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY);
- internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999);
-
- public override DateTime MinSupportedDateTime {
- get
- {
- return (minDate);
- }
- }
-
-
-
- public override DateTime MaxSupportedDateTime {
- get
- {
- return (maxDate);
- }
- }
-
- protected override int DaysInYearBeforeMinSupportedYear
- {
- get
- {
- // 1911 from ChineseLunisolarCalendar
- return 384;
- }
- }
-
- static readonly int [,] yinfo =
- {
-/*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days
-1912 */{ 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355
-1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384
-1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385
-1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
-1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383
-1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384
-1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355
-1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354
-1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384
-1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384
-1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354
-1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384
-1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384
-1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354
-1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355
-1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354
-1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383
-1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355
-1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384
-1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355
-1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355
-1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353
-1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355
-1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
-1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384
-1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384
-1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354
-1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355
-1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384
-1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355
-1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384
-1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354
-1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354
-1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384
-1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355
-1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384
-1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354
-1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354
-1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383
-1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355
-1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384
-1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354
-1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355
-1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384
-1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354
-2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354
-2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384
-2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354
-2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355
-2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384
-2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354
-2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385
-2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354
-2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354
-2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384
-2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354
-2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354
-2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384
-2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384
-2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354
-2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355
-2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384
-2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354
-2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354
-2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384
-2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354
-2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355
-2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384
-2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354
-2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384
-2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354
-2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354
-2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384
-2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355
-2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354
-2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384
-2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355
-2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384
-2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354
-2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354
-2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384
-2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354
-2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354
-2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384
-2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355
-2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355
-2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384
-2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354
-2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384
-2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354
-2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354
-2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384
-2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354
-2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355
-2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384
- */};
-
-
- internal override int MinCalendarYear {
- get
- {
- return (MIN_LUNISOLAR_YEAR);
- }
- }
-
- internal override int MaxCalendarYear {
- get
- {
- return (MAX_LUNISOLAR_YEAR);
- }
- }
-
- internal override DateTime MinDate {
- get
- {
- return (minDate);
- }
- }
-
- internal override DateTime MaxDate {
- get
- {
- return (maxDate);
- }
- }
-
- internal override EraInfo[] CalEraInfo {
- get
- {
- return (taiwanLunisolarEraInfo);
- }
- }
-
- internal override int GetYearInfo(int LunarYear, int Index) {
- if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MIN_LUNISOLAR_YEAR,
- MAX_LUNISOLAR_YEAR ));
- }
- Contract.EndContractBlock();
-
- return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index];
- }
-
- internal override int GetYear(int year, DateTime time) {
- return helper.GetYear(year, time);
- }
-
- internal override int GetGregorianYear(int year, int era) {
- return helper.GetGregorianYear(year, era);
- }
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of TaiwanLunisolarCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance()
- {
- if (m_defaultInstance == null) {
- m_defaultInstance = new TaiwanLunisolarCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
- // Construct an instance of TaiwanLunisolar calendar.
-
- public TaiwanLunisolarCalendar() {
- helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo);
- }
-
-
-
- public override int GetEra(DateTime time) {
- return (helper.GetEra(time));
- }
-
- internal override int BaseCalendarID {
- get {
- return (CAL_TAIWAN);
- }
- }
-
- internal override int ID {
- get {
- return (CAL_TAIWANLUNISOLAR);
- }
- }
-
-
-
- public override int[] Eras {
- get {
- return (helper.Eras);
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
index 0fee7a0745..464897b03f 100644
--- a/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
+++ b/src/mscorlib/src/System/Globalization/TextElementEnumerator.cs
@@ -10,93 +10,86 @@
//
////////////////////////////////////////////////////////////////////////////
+using System.Collections;
+using System.Diagnostics;
using System.Runtime.Serialization;
-
-namespace System.Globalization {
- using System.Collections;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
+namespace System.Globalization
+{
//
// This is public because GetTextElement() is public.
//
[Serializable]
- public class TextElementEnumerator: IEnumerator
+ public class TextElementEnumerator : IEnumerator
{
- private String str;
- private int index;
- private int startIndex;
-
+ private String _str;
+ private int _index;
+ private int _startIndex;
+
[NonSerialized]
- private int strLen; // This is the length of the total string, counting from the beginning of string.
-
- [NonSerialized]
- private int currTextElementLen; // The current text element lenght after MoveNext() is called.
-
+ private int _strLen; // This is the length of the total string, counting from the beginning of string.
+
+ [NonSerialized]
+ private int _currTextElementLen; // The current text element lenght after MoveNext() is called.
+
[OptionalField(VersionAdded = 2)]
- private UnicodeCategory uc;
-
+ private UnicodeCategory _uc;
+
[OptionalField(VersionAdded = 2)]
- private int charLen; // The next abstract char to look at after MoveNext() is called. It could be 1 or 2, depending on if it is a surrogate or not.
+ private int _charLen; // The next abstract char to look at after MoveNext() is called. It could be 1 or 2, depending on if it is a surrogate or not.
internal TextElementEnumerator(String str, int startIndex, int strLen)
{
Debug.Assert(str != null, "TextElementEnumerator(): str != null");
Debug.Assert(startIndex >= 0 && strLen >= 0, "TextElementEnumerator(): startIndex >= 0 && strLen >= 0");
Debug.Assert(strLen >= startIndex, "TextElementEnumerator(): strLen >= startIndex");
- this.str = str;
- this.startIndex = startIndex;
- this.strLen = strLen;
+ _str = str;
+ _startIndex = startIndex;
+ _strLen = strLen;
Reset();
}
-#region Serialization
// the following fields is defined to keep the compatibility with Everett.
// don't change/remove the names/types of these fields.
- private int endIndex;
- private int nextTextElementLen;
-
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- charLen = -1;
- }
-
+ private int _endIndex;
+ private int _nextTextElementLen;
+
+ [OnDeserializing]
+ private void OnDeserializing(StreamingContext ctx)
+ {
+ _charLen = -1;
+ }
+
[OnDeserialized]
private void OnDeserialized(StreamingContext ctx)
{
- strLen = endIndex + 1;
- currTextElementLen = nextTextElementLen;
+ _strLen = _endIndex + 1;
+ _currTextElementLen = _nextTextElementLen;
- if (charLen == -1)
+ if (_charLen == -1)
{
- uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
+ _uc = CharUnicodeInfo.InternalGetUnicodeCategory(_str, _index, out _charLen);
}
- }
-
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
- {
- endIndex = strLen - 1;
- nextTextElementLen = currTextElementLen;
- }
-
-#endregion Serialization
-
+ }
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx)
+ {
+ _endIndex = _strLen - 1;
+ _nextTextElementLen = _currTextElementLen;
+ }
public bool MoveNext()
{
- if (index >= strLen)
+ if (_index >= _strLen)
{
- // Make the index to be greater than strLen so that we can throw exception if GetTextElement() is called.
- index = strLen + 1;
+ // Make the _index to be greater than _strLen so that we can throw exception if GetTextElement() is called.
+ _index = _strLen + 1;
return (false);
}
- currTextElementLen = StringInfo.GetCurrentTextElementLen(str, index, strLen, ref uc, ref charLen);
- index += currTextElementLen;
+ _currTextElementLen = StringInfo.GetCurrentTextElementLen(_str, _index, _strLen, ref _uc, ref _charLen);
+ _index += _currTextElementLen;
return (true);
}
@@ -104,8 +97,10 @@ namespace System.Globalization {
// Get the current text element.
//
- public Object Current {
- get {
+ public Object Current
+ {
+ get
+ {
return (GetTextElement());
}
}
@@ -116,16 +111,18 @@ namespace System.Globalization {
public String GetTextElement()
{
- if (index == startIndex) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));
+ if (_index == _startIndex)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
}
- if (index > strLen) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumEnded"));
- }
-
- return (str.Substring(index - currTextElementLen, currTextElementLen));
+ if (_index > _strLen)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
+ }
+
+ return (_str.Substring(_index - _currTextElementLen, _currTextElementLen));
}
-
+
//
// Get the starting index of the current text element.
//
@@ -134,22 +131,23 @@ namespace System.Globalization {
{
get
{
- if (index == startIndex)
+ if (_index == _startIndex)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumNotStarted"));
+ throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
}
- return (index - currTextElementLen);
+ return (_index - _currTextElementLen);
}
}
public void Reset()
{
- index = startIndex;
- if (index < strLen) {
+ _index = _startIndex;
+ if (_index < _strLen)
+ {
// If we have more than 1 character, get the category of the current char.
- uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
- }
+ _uc = CharUnicodeInfo.InternalGetUnicodeCategory(_str, _index, out _charLen);
+ }
}
}
}
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs b/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs
new file mode 100644
index 0000000000..f7f64c684a
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs
@@ -0,0 +1,117 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Security;
+using System.Text;
+
+namespace System.Globalization
+{
+ public partial class TextInfo
+ {
+ [NonSerialized]
+ private Tristate _needsTurkishCasing = Tristate.NotInitialized;
+
+ private void FinishInitialization(string textInfoName)
+ {
+ }
+
+ private unsafe string ChangeCase(string s, bool toUpper)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(s != null);
+
+ if (s.Length == 0)
+ {
+ return string.Empty;
+ }
+
+ string result = string.FastAllocateString(s.Length);
+
+ fixed (char* pSource = s)
+ {
+ fixed (char* pResult = result)
+ {
+ if (IsAsciiCasingSameAsInvariant && s.IsAscii())
+ {
+ int length = s.Length;
+ char* a = pSource, b = pResult;
+ if (toUpper)
+ {
+ while (length-- != 0)
+ {
+ *b++ = ToUpperAsciiInvariant(*a++);
+ }
+ }
+ else
+ {
+ while (length-- != 0)
+ {
+ *b++ = ToLowerAsciiInvariant(*a++);
+ }
+ }
+ }
+ else
+ {
+ ChangeCase(pSource, s.Length, pResult, result.Length, toUpper);
+ }
+ }
+ }
+
+ return result;
+ }
+
+ private unsafe char ChangeCase(char c, bool toUpper)
+ {
+ Debug.Assert(!_invariantMode);
+
+ char dst = default(char);
+
+ ChangeCase(&c, 1, &dst, 1, toUpper);
+
+ return dst;
+ }
+
+ // -----------------------------
+ // ---- PAL layer ends here ----
+ // -----------------------------
+
+ private bool NeedsTurkishCasing(string localeName)
+ {
+ Debug.Assert(localeName != null);
+
+ return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("\u0131", "I", CompareOptions.IgnoreCase) == 0;
+ }
+
+ private bool IsInvariant { get { return _cultureName.Length == 0; } }
+
+ internal unsafe void ChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper)
+ {
+ Debug.Assert(!_invariantMode);
+
+ if (IsInvariant)
+ {
+ Interop.GlobalizationInterop.ChangeCaseInvariant(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper);
+ }
+ else
+ {
+ if (_needsTurkishCasing == Tristate.NotInitialized)
+ {
+ _needsTurkishCasing = NeedsTurkishCasing(_textInfoName) ? Tristate.True : Tristate.False;
+ }
+ if (_needsTurkishCasing == Tristate.True)
+ {
+ Interop.GlobalizationInterop.ChangeCaseTurkish(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper);
+ }
+ else
+ {
+ Interop.GlobalizationInterop.ChangeCase(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper);
+ }
+ }
+ }
+
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs b/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs
new file mode 100644
index 0000000000..cc7c4df1da
--- /dev/null
+++ b/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs
@@ -0,0 +1,113 @@
+// 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.Globalization
+{
+ public partial class TextInfo
+ {
+ private unsafe void FinishInitialization(string textInfoName)
+ {
+ if (_invariantMode)
+ {
+ _sortHandle = IntPtr.Zero;
+ return;
+ }
+
+ const uint LCMAP_SORTHANDLE = 0x20000000;
+
+ long 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;
+ }
+
+ private unsafe string ChangeCase(string s, bool toUpper)
+ {
+ Debug.Assert(!_invariantMode);
+
+ Debug.Assert(s != null);
+
+ //
+ // Get the length of the string.
+ //
+ int nLengthInput = s.Length;
+
+ //
+ // Check if we have the empty string.
+ //
+ if (nLengthInput == 0)
+ {
+ return s;
+ }
+
+ int ret;
+
+ // Check for Invariant to avoid A/V in LCMapStringEx
+ uint linguisticCasing = IsInvariantLocale(_textInfoName) ? 0 : LCMAP_LINGUISTIC_CASING;
+
+ //
+ // Create the result string.
+ //
+ string result = string.FastAllocateString(nLengthInput);
+
+ fixed (char* pSource = s)
+ fixed (char* pResult = result)
+ {
+ ret = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _textInfoName,
+ linguisticCasing | (toUpper ? LCMAP_UPPERCASE : LCMAP_LOWERCASE),
+ pSource,
+ nLengthInput,
+ pResult,
+ nLengthInput,
+ null,
+ null,
+ _sortHandle);
+ }
+
+ if (ret == 0)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
+ }
+
+ Debug.Assert(ret == nLengthInput, "Expected getting the same length of the original string");
+ return result;
+ }
+
+ private unsafe char ChangeCase(char c, bool toUpper)
+ {
+ Debug.Assert(!_invariantMode);
+
+ char retVal = '\0';
+
+ // Check for Invariant to avoid A/V in LCMapStringEx
+ uint linguisticCasing = IsInvariantLocale(_textInfoName) ? 0 : LCMAP_LINGUISTIC_CASING;
+
+ Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _textInfoName,
+ toUpper ? LCMAP_UPPERCASE | linguisticCasing : LCMAP_LOWERCASE | linguisticCasing,
+ &c,
+ 1,
+ &retVal,
+ 1,
+ null,
+ null,
+ _sortHandle);
+
+ return retVal;
+ }
+
+ // PAL Ends here
+
+ private IntPtr _sortHandle;
+
+ private const uint LCMAP_LINGUISTIC_CASING = 0x01000000;
+ private const uint LCMAP_LOWERCASE = 0x00000100;
+ private const uint LCMAP_UPPERCASE = 0x00000200;
+
+ private static bool IsInvariantLocale(string localeName)
+ {
+ return localeName == "";
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs
index 9ece275dd3..fecd2b2970 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.cs
@@ -12,27 +12,19 @@
//
////////////////////////////////////////////////////////////////////////////
-using System.Security;
-
-namespace System.Globalization {
- using System;
- using System.Text;
- using System.Threading;
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Text;
+namespace System.Globalization
+{
[Serializable]
public partial class TextInfo : ICloneable, IDeserializationCallback
{
- //--------------------------------------------------------------------//
- // Internal Information //
- //--------------------------------------------------------------------//
+ ////--------------------------------------------------------------------//
+ //// Internal Information //
+ ////--------------------------------------------------------------------//
private enum Tristate : byte
{
@@ -41,49 +33,42 @@ namespace System.Globalization {
False,
}
- //
- // Variables.
- //
+ ////
+ //// Variables.
+ ////
[OptionalField(VersionAdded = 2)]
- private String m_listSeparator;
-
+ private String _listSeparator;
[OptionalField(VersionAdded = 2)]
- private bool m_isReadOnly = false;
-
- //
- // In Whidbey we had several names:
- // m_win32LangID is the name of the culture, but only used for (de)serialization.
- // customCultureName is the name of the creating custom culture (if custom) In combination with m_win32LangID
- // this is authoratative, ie when deserializing.
- // m_cultureTableRecord was the data record of the creating culture. (could have different name if custom)
- // m_textInfoID is the LCID of the textinfo itself (no longer used)
- // m_name is the culture name (from cultureinfo.name)
- //
- // In Silverlight/Arrowhead this is slightly different:
- // m_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.
- // m_cultureData is the data that backs this class.
- // m_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
- // m_textInfoName can be the same as m_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.
- //
+ 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)]
- private String m_cultureName; // Name of the culture that created this text info
- [NonSerialized]private CultureData m_cultureData; // Data record for the culture that made us, not for this textinfo
- [NonSerialized]private String m_textInfoName; // Name of the text info we're using (ie: m_cultureData.STEXTINFO)
- [NonSerialized]private IntPtr m_dataHandle; // Sort handle
- [NonSerialized]private IntPtr m_handleOrigin;
- [NonSerialized]private Tristate m_IsAsciiCasingSameAsInvariant = Tristate.NotInitialized;
-
+ 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
- internal static TextInfo Invariant
+ internal static TextInfo Invariant
{
- get
+ get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
@@ -92,88 +77,31 @@ namespace System.Globalization {
}
internal volatile static TextInfo s_Invariant;
- ////////////////////////////////////////////////////////////////////////
- //
- // TextInfo Constructors
- //
- // Implements CultureInfo.TextInfo.
- //
- ////////////////////////////////////////////////////////////////////////
- internal TextInfo(CultureData cultureData)
+ //////////////////////////////////////////////////////////////////////////
+ ////
+ //// TextInfo Constructors
+ ////
+ //// Implements CultureInfo.TextInfo.
+ ////
+ //////////////////////////////////////////////////////////////////////////
+ internal unsafe TextInfo(CultureData cultureData)
{
// This is our primary data source, we don't need most of the rest of this
- this.m_cultureData = cultureData;
- this.m_cultureName = this.m_cultureData.CultureName;
- this.m_textInfoName = this.m_cultureData.STEXTINFO;
+ _cultureData = cultureData;
+ _cultureName = _cultureData.CultureName;
+ _textInfoName = _cultureData.STEXTINFO;
+ FinishInitialization(_textInfoName);
}
- ////////////////////////////////////////////////////////////////////////
- //
- // Serialization / Deserialization
- //
- // Note that we have to respect the Whidbey behavior for serialization compatibility
- //
- ////////////////////////////////////////////////////////////////////////
-
-#region Serialization
- // the following fields are defined to keep the compatibility with Whidbey.
- // don't change/remove the names/types of these fields.
- [OptionalField(VersionAdded = 2)]
- private string customCultureName;
-
- // the following fields are defined to keep compatibility with Everett.
- // don't change/remove the names/types of these fields.
- [OptionalField(VersionAdded = 1)]
- internal int m_nDataItem;
- [OptionalField(VersionAdded = 1)]
- internal bool m_useUserOverride;
- [OptionalField(VersionAdded = 1)]
- internal int m_win32LangID;
-
-
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- // Clear these so we can check if we've fixed them yet
- this.m_cultureData = null;
- this.m_cultureName = null;
- }
+ [OnSerializing]
+ private void OnSerializing(StreamingContext ctx) { }
- private void OnDeserialized()
+ [OnDeserializing]
+ private void OnDeserializing(StreamingContext ctx)
{
- // this method will be called twice because of the support of IDeserializationCallback
- if (this.m_cultureData == null)
- {
- if (this.m_cultureName == null)
- {
- // This is whidbey data, get it from customCultureName/win32langid
- if (this.customCultureName != null)
- {
- // They gave a custom cultuer name, so use that
- this.m_cultureName = this.customCultureName;
- }
-#if FEATURE_USE_LCID
- else
- {
- if (m_win32LangID == 0)
- {
- // m_cultureName and m_win32LangID are nulls which means we got uninitialized textinfo serialization stream.
- // To be compatible with v2/3/3.5 we need to return ar-SA TextInfo in this case.
- m_cultureName = "ar-SA";
- }
- else
- {
- // No custom culture, use the name from the LCID
- m_cultureName = CultureInfo.GetCultureInfo(m_win32LangID).m_cultureData.CultureName;
- }
- }
-#endif
- }
-
- // Get the text info name belonging to that culture
- this.m_cultureData = CultureInfo.GetCultureInfo(m_cultureName).m_cultureData;
- this.m_textInfoName = this.m_cultureData.STEXTINFO;
- }
+ // Clear these so we can check if we've fixed them yet
+ _cultureData = null;
+ _cultureName = null;
}
[OnDeserialized]
@@ -182,142 +110,56 @@ namespace System.Globalization {
OnDeserialized();
}
- [OnSerializing]
- private void OnSerializing(StreamingContext ctx)
+ void IDeserializationCallback.OnDeserialization(Object sender)
{
- // Relabel our name since Whidbey expects it to be called customCultureName
- this.customCultureName = this.m_cultureName;
+ OnDeserialized();
+ }
-#if FEATURE_USE_LCID
- // Ignore the m_win32LangId because whidbey'll just get it by name if we make it the LOCALE_CUSTOM_UNSPECIFIED.
- this.m_win32LangID = (CultureInfo.GetCultureInfo(m_cultureName)).LCID;
-#endif
- }
-
-#endregion Serialization
+ private void OnDeserialized()
+ {
+ // this method will be called twice because of the support of IDeserializationCallback
+ if (_cultureData == null)
+ {
+ // Get the text info name belonging to that culture
+ _cultureData = CultureInfo.GetCultureInfo(_cultureName)._cultureData;
+ _textInfoName = _cultureData.STEXTINFO;
+ FinishInitialization(_textInfoName);
+ }
+ }
//
// Internal ordinal comparison functions
//
- internal static int GetHashCodeOrdinalIgnoreCase(String s)
- {
- return GetHashCodeOrdinalIgnoreCase(s, false, 0);
- }
- internal static int GetHashCodeOrdinalIgnoreCase(String s, bool forceRandomizedHashing, long additionalEntropy)
+ internal static int GetHashCodeOrdinalIgnoreCase(String s)
{
// This is the same as an case insensitive hash for Invariant
// (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
- return (Invariant.GetCaseInsensitiveHashCode(s, forceRandomizedHashing, additionalEntropy));
- }
-
- internal static unsafe bool TryFastFindStringOrdinalIgnoreCase(int searchFlags, String source, int startIndex, String value, int count, ref int foundIndex)
- {
- return InternalTryFindStringOrdinalIgnoreCase(searchFlags, source, count, startIndex, value, value.Length, ref foundIndex);
- }
-
- // This function doesn't check arguments. Please do check in the caller.
- // The underlying unmanaged code will assert the sanity of arguments.
- internal static unsafe int CompareOrdinalIgnoreCase(String str1, String str2)
- {
- // Compare the whole string and ignore case.
- return InternalCompareStringOrdinalIgnoreCase(str1, 0, str2, 0, str1.Length, str2.Length);
- }
-
- // This function doesn't check arguments. Please do check in the caller.
- // The underlying unmanaged code will assert the sanity of arguments.
- internal static unsafe int CompareOrdinalIgnoreCaseEx(String strA, int indexA, String strB, int indexB, int lengthA, int lengthB )
- {
- Debug.Assert(strA.Length >= indexA + lengthA, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strA.Length >= indexA + lengthA");
- Debug.Assert(strB.Length >= indexB + lengthB, "[TextInfo.CompareOrdinalIgnoreCaseEx] Caller should've validated strB.Length >= indexB + lengthB");
- return InternalCompareStringOrdinalIgnoreCase(strA, indexA, strB, indexB, lengthA, lengthB);
+ return (Invariant.GetCaseInsensitiveHashCode(s));
}
+ // Currently we don't have native functions to do this, so we do it the hard way
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
- Debug.Assert(source != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
- Debug.Assert(value != null, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
- Debug.Assert(startIndex + count <= source.Length, "[TextInfo.IndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex + count <= source.Length");
-
- // We return 0 if both inputs are empty strings
- if (source.Length == 0 && value.Length == 0)
+ if (count > source.Length || count < 0 || startIndex < 0 || startIndex >= source.Length || startIndex + count > source.Length)
{
- return 0;
+ return -1;
}
- // fast path
- int ret = -1;
- if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMSTART, source, startIndex, value, count, ref ret))
- return ret;
-
- // the search space within [source] starts at offset [startIndex] inclusive and includes
- // [count] characters (thus the last included character is at index [startIndex + count -1]
- // [end] is the index of the next character after the search space
- // (it points past the end of the search space)
- int end = startIndex + count;
-
- // maxStartIndex is the index beyond which we never *start* searching, inclusive; in other words;
- // a search could include characters beyond maxStartIndex, but we'd never begin a search at an
- // index strictly greater than maxStartIndex.
- int maxStartIndex = end - value.Length;
-
- for (; startIndex <= maxStartIndex; startIndex++)
- {
- // We should always have the same or more characters left to search than our actual pattern
- Debug.Assert(end - startIndex >= value.Length);
- // since this is an ordinal comparison, we can assume that the lengths must match
- if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
- {
- return startIndex;
- }
- }
-
- // Not found
- return -1;
+ return CultureInfo.InvariantCulture.CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
+ // Currently we don't have native functions to do this, so we do it the hard way
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
- Debug.Assert(source != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated source != null");
- Debug.Assert(value != null, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated value != null");
- Debug.Assert(startIndex - count+1 >= 0, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex - count+1 >= 0");
- Debug.Assert(startIndex <= source.Length, "[TextInfo.LastIndexOfStringOrdinalIgnoreCase] Caller should've validated startIndex <= source.Length");
-
- // If value is Empty, the return value is startIndex
- if (value.Length == 0)
- {
- return startIndex;
- }
-
- // fast path
- int ret = -1;
- if (TryFastFindStringOrdinalIgnoreCase(Microsoft.Win32.Win32Native.FIND_FROMEND, source, startIndex, value, count, ref ret))
- return ret;
-
- // the search space within [source] ends at offset [startIndex] inclusive
- // and includes [count] characters
- // minIndex is the first included character and is at index [startIndex - count + 1]
- int minIndex = startIndex - count + 1;
-
- // First place we can find it is start index - (value.length -1)
- if (value.Length > 0)
+ if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0))
{
- startIndex -= (value.Length - 1);
+ return -1;
}
- for (; startIndex >= minIndex; startIndex--)
- {
- if (CompareOrdinalIgnoreCaseEx(source, startIndex, value, 0, value.Length, value.Length) == 0)
- {
- return startIndex;
- }
- }
-
- // Not found
- return -1;
+ return CultureInfo.InvariantCulture.CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
-
////////////////////////////////////////////////////////////////////////
//
// CodePage
@@ -331,72 +173,62 @@ namespace System.Globalization {
////////////////////////////////////////////////////////////////////////
- public virtual int ANSICodePage
+ public virtual int ANSICodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTANSICODEPAGE);
+ return (_cultureData.IDEFAULTANSICODEPAGE);
}
}
-
- public virtual int OEMCodePage
+
+ public virtual int OEMCodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTOEMCODEPAGE);
+ return (_cultureData.IDEFAULTOEMCODEPAGE);
}
}
- public virtual int MacCodePage
+ public virtual int MacCodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTMACCODEPAGE);
+ return (_cultureData.IDEFAULTMACCODEPAGE);
}
}
- public virtual int EBCDICCodePage
+ public virtual int EBCDICCodePage
{
- get
+ get
{
- return (this.m_cultureData.IDEFAULTEBCDICCODEPAGE);
+ return (_cultureData.IDEFAULTEBCDICCODEPAGE);
}
}
- ////////////////////////////////////////////////////////////////////////
- //
- // LCID
- //
- // We need a way to get an LCID from outside of the BCL. This prop is the way.
- // NOTE: neutral cultures will cause GPS incorrect LCIDS from this
- //
- ////////////////////////////////////////////////////////////////////////
-
-#if FEATURE_USE_LCID
public int LCID
{
- get
+ get
{
// Just use the LCID from our text info name
- return CultureInfo.GetCultureInfo(this.m_textInfoName).LCID;
+ return CultureInfo.GetCultureInfo(_textInfoName).LCID;
}
}
-#endif
- ////////////////////////////////////////////////////////////////////////
- //
- // CultureName
- //
- // The name of the culture associated with the current TextInfo.
- //
- ////////////////////////////////////////////////////////////////////////
- public string CultureName
+
+ //////////////////////////////////////////////////////////////////////////
+ ////
+ //// CultureName
+ ////
+ //// The name of the culture associated with the current TextInfo.
+ ////
+ //////////////////////////////////////////////////////////////////////////
+ public string CultureName
{
- get
+ get
{
- return(this.m_textInfoName);
+ return _textInfoName;
}
}
@@ -407,25 +239,25 @@ namespace System.Globalization {
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
- public bool IsReadOnly
+ public bool IsReadOnly
{
- get { return (m_isReadOnly); }
+ get { return (_isReadOnly); }
}
- ////////////////////////////////////////////////////////////////////////
- //
- // Clone
- //
- // Is the implementation of ICloneable.
- //
- ////////////////////////////////////////////////////////////////////////
- public virtual Object Clone()
+ //////////////////////////////////////////////////////////////////////////
+ ////
+ //// Clone
+ ////
+ //// Is the implementation of ICloneable.
+ ////
+ //////////////////////////////////////////////////////////////////////////
+ public virtual object Clone()
{
object o = MemberwiseClone();
- ((TextInfo) o).SetReadOnlyState(false);
+ ((TextInfo)o).SetReadOnlyState(false);
return (o);
}
-
+
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
@@ -434,30 +266,29 @@ namespace System.Globalization {
// readonly.
//
////////////////////////////////////////////////////////////////////////
- public static TextInfo ReadOnly(TextInfo textInfo)
+ public static TextInfo ReadOnly(TextInfo textInfo)
{
- if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
+ if (textInfo == null) { throw new ArgumentNullException(nameof(textInfo)); }
Contract.EndContractBlock();
- if (textInfo.IsReadOnly) { return (textInfo); }
-
+ if (textInfo.IsReadOnly) { return (textInfo); }
+
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
-
+
return (clonedTextInfo);
}
private void VerifyWritable()
{
- if (m_isReadOnly)
+ if (_isReadOnly)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
- Contract.EndContractBlock();
}
internal void SetReadOnlyState(bool readOnly)
{
- m_isReadOnly = readOnly;
+ _isReadOnly = readOnly;
}
@@ -468,27 +299,25 @@ namespace System.Globalization {
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
-
-
- public virtual String ListSeparator
+ public virtual String ListSeparator
{
- get
+ get
{
- if (m_listSeparator == null) {
- m_listSeparator = this.m_cultureData.SLIST;
+ if (_listSeparator == null)
+ {
+ _listSeparator = _cultureData.SLIST;
}
- return (m_listSeparator);
+ return (_listSeparator);
}
- set
+ set
{
- if (value == null)
+ if (value == null)
{
- throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String"));
+ throw new ArgumentNullException(nameof(value), SR.ArgumentNull_String);
}
- Contract.EndContractBlock();
VerifyWritable();
- m_listSeparator = value;
+ _listSeparator = value;
}
}
@@ -500,28 +329,123 @@ namespace System.Globalization {
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
-
- public unsafe virtual char ToLower(char c)
+ public unsafe virtual char ToLower(char c)
{
- if(IsAscii(c) && IsAsciiCasingSameAsInvariant)
+ if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToLowerAsciiInvariant(c);
}
- return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, false));
+
+ return (ChangeCase(c, toUpper: false));
}
- public unsafe virtual String ToLower(String str)
+ public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
- Contract.EndContractBlock();
- return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, false);
+ if (_invariantMode)
+ {
+ return ToLowerAsciiInvariant(str);
+ }
+ return ChangeCase(str, toUpper: false);
}
- static private Char ToLowerAsciiInvariant(Char c)
+ private unsafe string ToLowerAsciiInvariant(string s)
{
- if ('A' <= c && c <= 'Z')
+ if (s.Length == 0)
+ {
+ return string.Empty;
+ }
+
+ fixed (char* pSource = s)
+ {
+ int i = 0;
+ while (i < s.Length)
+ {
+ if ((uint)(pSource[i] - 'A') <= (uint)('Z' - 'A'))
+ {
+ break;
+ }
+ i++;
+ }
+
+ if (i >= s.Length)
+ {
+ return s;
+ }
+
+ string result = string.FastAllocateString(s.Length);
+ fixed (char* pResult = result)
+ {
+ for (int j = 0; j < i; j++)
+ {
+ pResult[j] = pSource[j];
+ }
+
+ pResult[i] = (Char)(pSource[i] | 0x20);
+ i++;
+
+ while (i < s.Length)
+ {
+ pResult[i] = ToLowerAsciiInvariant(pSource[i]);
+ i++;
+ }
+ }
+
+ return result;
+ }
+ }
+
+ private unsafe string ToUpperAsciiInvariant(string s)
+ {
+ if (s.Length == 0)
+ {
+ return string.Empty;
+ }
+
+ fixed (char* pSource = s)
+ {
+ int i = 0;
+ while (i < s.Length)
+ {
+ if ((uint)(pSource[i] - 'a') <= (uint)('z' - 'a'))
+ {
+ break;
+ }
+ i++;
+ }
+
+ if (i >= s.Length)
+ {
+ return s;
+ }
+
+ string result = string.FastAllocateString(s.Length);
+ fixed (char* pResult = result)
+ {
+ for (int j = 0; j < i; j++)
+ {
+ pResult[j] = pSource[j];
+ }
+
+ pResult[i] = (char)(pSource[i] & ~0x20);
+ i++;
+
+ while (i < s.Length)
+ {
+ pResult[i] = ToUpperAsciiInvariant(pSource[i]);
+ i++;
+ }
+ }
+
+ return result;
+ }
+ }
+
+ private static Char ToLowerAsciiInvariant(Char c)
+ {
+ if ((uint)(c - 'A') <= (uint)('Z' - 'A'))
{
c = (Char)(c | 0x20);
}
@@ -536,34 +460,38 @@ namespace System.Globalization {
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
-
- public unsafe virtual char ToUpper(char c)
+ public unsafe virtual char ToUpper(char c)
{
- if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
+ if (_invariantMode || (IsAscii(c) && IsAsciiCasingSameAsInvariant))
{
return ToUpperAsciiInvariant(c);
}
- return (InternalChangeCaseChar(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, c, true));
+
+ return (ChangeCase(c, toUpper: true));
}
-
- public unsafe virtual String ToUpper(String str)
+ public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException(nameof(str)); }
- Contract.EndContractBlock();
- return InternalChangeCaseString(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, true);
+
+ if (_invariantMode)
+ {
+ return ToUpperAsciiInvariant(str);
+ }
+
+ return ChangeCase(str, toUpper: true);
}
- static private Char ToUpperAsciiInvariant(Char c)
+ private static Char ToUpperAsciiInvariant(Char c)
{
- if ('a' <= c && c <= 'z')
+ if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
c = (Char)(c & ~0x20);
}
return c;
}
- static private bool IsAscii(Char c)
+ private static bool IsAscii(Char c)
{
return c < 0x80;
}
@@ -572,14 +500,25 @@ namespace System.Globalization {
{
get
{
- if (m_IsAsciiCasingSameAsInvariant == Tristate.NotInitialized)
+ if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized)
{
- m_IsAsciiCasingSameAsInvariant =
- CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
+ _isAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0 ? Tristate.True : Tristate.False;
}
- return m_IsAsciiCasingSameAsInvariant == Tristate.True;
+ return _isAsciiCasingSameAsInvariant == Tristate.True;
+ }
+ }
+
+ // IsRightToLeft
+ //
+ // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
+ //
+ public bool IsRightToLeft
+ {
+ get
+ {
+ return _cultureData.IsRightToLeft;
}
}
@@ -591,21 +530,18 @@ namespace System.Globalization {
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
-
-
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
-
+
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
-
+
return (false);
}
-
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
@@ -615,14 +551,11 @@ namespace System.Globalization {
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
-
-
public override int GetHashCode()
{
return (this.CultureName.GetHashCode());
}
-
////////////////////////////////////////////////////////////////////////
//
// ToString
@@ -631,14 +564,11 @@ namespace System.Globalization {
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
-
-
public override String ToString()
{
- return ("TextInfo - " + this.m_cultureData.CultureName);
+ return ("TextInfo - " + _cultureData.CultureName);
}
-
//
// Titlecasing:
// -----------
@@ -653,41 +583,44 @@ namespace System.Globalization {
// influence which letter or letters of a "word" are uppercased when titlecasing strings. For example
// "l'arbre" is considered two words in French, whereas "can't" is considered one word in English.
//
- //
- // Differences between UNICODE 5.0 and the .NET Framework:
- // -------------------------------------------------------------------------------------
- // The .NET Framework previously shipped a naive titlecasing implementation. Every word is titlecased
- // regardless of language or orthographic practice. Furthermore, apostrophe is always considered to be
- // a word joiner as used in English. The longterm vision is to depend on the operating system for
- // titlecasing. Windows 7 is expected to be the first release with this feature. On the Macintosh side,
- // titlecasing is not available as of version 10.5 of the operating system.
- //
- public unsafe String ToTitleCase(String str)
+ public unsafe String ToTitleCase(String str)
{
- if (str == null)
+ if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
Contract.EndContractBlock();
- if (str.Length == 0)
+ if (str.Length == 0)
{
return (str);
}
StringBuilder result = new StringBuilder();
- String lowercaseData = null;
+ string lowercaseData = null;
+ // Store if the current culture is Dutch (special case)
+ bool isDutchCulture = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase);
- for (int i = 0; i < str.Length; i++)
+ for (int i = 0; i < str.Length; i++)
{
UnicodeCategory charType;
int charLen;
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
- if (Char.CheckLetter(charType))
+ if (Char.CheckLetter(charType))
{
- // Do the titlecasing for the first character of the word.
- i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
-
+ // Special case to check for Dutch specific titlecasing with "IJ" characters
+ // at the beginning of a word
+ if (isDutchCulture && i < str.Length - 1 && (str[i] == 'i' || str[i] == 'I') && (str[i+1] == 'j' || str[i+1] == 'J'))
+ {
+ result.Append("IJ");
+ i += 2;
+ }
+ else
+ {
+ // Do the titlecasing for the first character of the word.
+ i = AddTitlecaseLetter(ref result, ref str, i, charLen) + 1;
+ }
+
//
// Convert the characters until the end of the this word
// to lowercase.
@@ -700,42 +633,42 @@ namespace System.Globalization {
//
bool hasLowerCase = (charType == UnicodeCategory.LowercaseLetter);
// Use a loop to find all of the other letters following this letter.
- while (i < str.Length)
+ while (i < str.Length)
{
charType = CharUnicodeInfo.InternalGetUnicodeCategory(str, i, out charLen);
- if (IsLetterCategory(charType))
+ if (IsLetterCategory(charType))
{
- if (charType == UnicodeCategory.LowercaseLetter)
+ if (charType == UnicodeCategory.LowercaseLetter)
{
hasLowerCase = true;
}
i += charLen;
- }
- else if (str[i] == '\'')
+ }
+ else if (str[i] == '\'')
{
i++;
- if (hasLowerCase)
+ if (hasLowerCase)
{
- if (lowercaseData == null)
+ if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, i - lowercaseStart);
- }
- else
+ }
+ else
{
result.Append(str, lowercaseStart, i - lowercaseStart);
}
lowercaseStart = i;
hasLowerCase = true;
- }
- else if (!IsWordSeparator(charType))
+ }
+ else if (!IsWordSeparator(charType))
{
// This category is considered to be part of the word.
// This is any category that is marked as false in wordSeprator array.
i+= charLen;
- }
- else
+ }
+ else
{
// A word separator. Break out of the loop.
break;
@@ -744,29 +677,29 @@ namespace System.Globalization {
int count = i - lowercaseStart;
- if (count>0)
+ if (count > 0)
{
- if (hasLowerCase)
+ if (hasLowerCase)
{
- if (lowercaseData == null)
+ if (lowercaseData == null)
{
lowercaseData = this.ToLower(str);
}
result.Append(lowercaseData, lowercaseStart, count);
- }
- else
+ }
+ else
{
result.Append(str, lowercaseStart, count);
}
}
- if (i < str.Length)
+ if (i < str.Length)
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
}
}
- else
+ else
{
// not a letter, just append it
i = AddNonLetter(ref result, ref str, i, charLen);
@@ -775,75 +708,73 @@ namespace System.Globalization {
return (result.ToString());
}
- private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
+ private static int AddNonLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddNonLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
- if (charLen == 2)
+ if (charLen == 2)
{
// Surrogate pair
result.Append(input[inputIndex++]);
result.Append(input[inputIndex]);
}
- else
+ else
{
result.Append(input[inputIndex]);
- }
+ }
return inputIndex;
}
-
- private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
+ private int AddTitlecaseLetter(ref StringBuilder result, ref String input, int inputIndex, int charLen)
{
Debug.Assert(charLen == 1 || charLen == 2, "[TextInfo.AddTitlecaseLetter] CharUnicodeInfo.InternalGetUnicodeCategory returned an unexpected charLen!");
// for surrogate pairs do a simple ToUpper operation on the substring
- if (charLen == 2)
+ if (charLen == 2)
{
// Surrogate pair
- result.Append( this.ToUpper(input.Substring(inputIndex, charLen)) );
+ result.Append(ToUpper(input.Substring(inputIndex, charLen)));
inputIndex++;
}
- else
+ else
{
- switch (input[inputIndex])
+ switch (input[inputIndex])
{
//
// For AppCompat, the Titlecase Case Mapping data from NDP 2.0 is used below.
- case (char)0x01C4: // DZ with Caron -> Dz with Caron
- case (char)0x01C5: // Dz with Caron -> Dz with Caron
- case (char)0x01C6: // dz with Caron -> Dz with Caron
- result.Append( (char)0x01C5 );
+ case (char) 0x01C4: // DZ with Caron -> Dz with Caron
+ case (char) 0x01C5: // Dz with Caron -> Dz with Caron
+ case (char) 0x01C6: // dz with Caron -> Dz with Caron
+ result.Append((char) 0x01C5);
break;
- case (char)0x01C7: // LJ -> Lj
- case (char)0x01C8: // Lj -> Lj
- case (char)0x01C9: // lj -> Lj
- result.Append( (char)0x01C8 );
+ case (char) 0x01C7: // LJ -> Lj
+ case (char) 0x01C8: // Lj -> Lj
+ case (char) 0x01C9: // lj -> Lj
+ result.Append((char) 0x01C8);
break;
- case (char)0x01CA: // NJ -> Nj
- case (char)0x01CB: // Nj -> Nj
- case (char)0x01CC: // nj -> Nj
- result.Append( (char)0x01CB );
+ case (char) 0x01CA: // NJ -> Nj
+ case (char) 0x01CB: // Nj -> Nj
+ case (char) 0x01CC: // nj -> Nj
+ result.Append((char) 0x01CB);
break;
- case (char)0x01F1: // DZ -> Dz
- case (char)0x01F2: // Dz -> Dz
- case (char)0x01F3: // dz -> Dz
- result.Append( (char)0x01F2 );
+ case (char) 0x01F1: // DZ -> Dz
+ case (char) 0x01F2: // Dz -> Dz
+ case (char) 0x01F3: // dz -> Dz
+ result.Append((char) 0x01F2);
break;
default:
- result.Append( this.ToUpper(input[inputIndex]) );
+ result.Append(ToUpper(input[inputIndex]));
break;
}
- }
+ }
return inputIndex;
}
-
//
// Used in ToTitleCase():
// When we find a starting letter, the following array decides if a category should be
// considered as word seprator or not.
//
- private const int wordSeparatorMask =
+ private const int c_wordSeparatorMask =
/* false */ (0 << 0) | // UppercaseLetter = 0,
/* false */ (0 << 1) | // LowercaseLetter = 1,
/* false */ (0 << 2) | // TitlecaseLetter = 2,
@@ -874,13 +805,13 @@ namespace System.Globalization {
/* true */ (1 << 27) | // ModifierSymbol = 27,
/* true */ (1 << 28) | // OtherSymbol = 28,
/* false */ (0 << 29); // OtherNotAssigned = 29;
-
+
private static bool IsWordSeparator(UnicodeCategory category)
{
- return (wordSeparatorMask & (1 << (int)category)) != 0;
+ return (c_wordSeparatorMask & (1 << (int) category)) != 0;
}
- private static bool IsLetterCategory(UnicodeCategory uc)
+ private static bool IsLetterCategory(UnicodeCategory uc)
{
return (uc == UnicodeCategory.UppercaseLetter
|| uc == UnicodeCategory.LowercaseLetter
@@ -889,76 +820,63 @@ namespace System.Globalization {
|| uc == UnicodeCategory.OtherLetter);
}
- // IsRightToLeft
//
- // Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
+ // Get case-insensitive hash code for the specified string.
//
- public bool IsRightToLeft
+ internal unsafe int GetCaseInsensitiveHashCode(String str)
{
- get
+ // Validate inputs
+ if (str == null)
{
- return this.m_cultureData.IsRightToLeft;
+ throw new ArgumentNullException(nameof(str));
}
- }
- /// <internalonly/>
- void IDeserializationCallback.OnDeserialization(Object sender)
- {
- OnDeserialized();
- }
+ // This code assumes that ASCII casing is safe for whatever context is passed in.
+ // this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor
+ // these methods so they were correct by construction and we could only ever use Invariant.
- //
- // Get case-insensitive hash code for the specified string.
- //
- // NOTENOTE: this is an internal function. The caller should verify the string
- // is not null before calling this. Currenlty, CaseInsensitiveHashCodeProvider
- // does that.
- //
- internal unsafe int GetCaseInsensitiveHashCode(String str)
- {
- return GetCaseInsensitiveHashCode(str, false, 0);
- }
+ uint hash = 5381;
+ uint c;
- internal unsafe int GetCaseInsensitiveHashCode(String str, bool forceRandomizedHashing, long additionalEntropy)
- {
- // Validate inputs
- if (str==null)
+ // Note: We assume that str contains only ASCII characters until
+ // we hit a non-ASCII character to optimize the common case.
+ for (int i = 0; i < str.Length; i++)
{
- throw new ArgumentNullException(nameof(str));
+ c = str[i];
+ if (c >= 0x80)
+ {
+ return GetCaseInsensitiveHashCodeSlow(str);
+ }
+
+ // If we have a lowercase character, ANDing off 0x20
+ // will make it an uppercase character.
+ if ((c - 'a') <= ('z' - 'a'))
+ {
+ c = (uint)((int)c & ~0x20);
+ }
+
+ hash = ((hash << 5) + hash) ^ c;
}
- Contract.EndContractBlock();
- // Return our result
- return (InternalGetCaseInsHash(this.m_dataHandle, this.m_handleOrigin, this.m_textInfoName, str, forceRandomizedHashing, additionalEntropy));
+ return (int)hash;
}
- // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseChar
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static unsafe extern char InternalChangeCaseChar(IntPtr handle, IntPtr handleOrigin, String localeName, char ch, bool isToUpper);
-
- // Change case (ToUpper/ToLower) -- COMNlsInfo::InternalChangeCaseString
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static unsafe extern String InternalChangeCaseString(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool isToUpper);
-
- // Get case insensitive hash -- ComNlsInfo::InternalGetCaseInsHash
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static unsafe extern int InternalGetCaseInsHash(IntPtr handle, IntPtr handleOrigin, String localeName, String str, bool forceRandomizedHashing, long additionalEntropy);
-
- // Call ::CompareStringOrdinal -- ComNlsInfo::InternalCompareStringOrdinalIgnoreCase
- // Start at indexes and compare for length characters (or remainder of string if length == -1)
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static unsafe extern int InternalCompareStringOrdinalIgnoreCase(String string1, int index1, String string2, int index2, int length1, int length2);
-
- // ComNlsInfo::InternalTryFindStringOrdinalIgnoreCase attempts a faster IndexOf/LastIndexOf OrdinalIgnoreCase using a kernel function.
- // Returns true if FindStringOrdinal was handled, with foundIndex set to the target's index into the source
- // Returns false when FindStringOrdinal wasn't handled
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- private static unsafe extern bool InternalTryFindStringOrdinalIgnoreCase(int searchFlags, String source, int sourceCount, int startIndex, String target, int targetCount, ref int foundIndex);
- }
+ private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
+ {
+ Debug.Assert(str != null);
-}
+ string upper = ToUpper(str);
+ uint hash = 5381;
+ uint c;
+
+ for (int i = 0; i < upper.Length; i++)
+ {
+ c = upper[i];
+ hash = ((hash << 5) + hash) ^ c;
+ }
+ return (int)hash;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs b/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
deleted file mode 100644
index 762c3ca7cb..0000000000
--- a/src/mscorlib/src/System/Globalization/ThaiBuddhistCalendar.cs
+++ /dev/null
@@ -1,219 +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.
-
-namespace System.Globalization {
-
- using System;
- using System.Diagnostics.CodeAnalysis;
- using System.Diagnostics.Contracts;
-
- /*=================================ThaiBuddhistCalendar==========================
- **
- ** ThaiBuddhistCalendar is based on Gregorian calendar. Its year value has
- ** an offset to the Gregorain calendar.
- **
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 0001/01/01 9999/12/31
- ** Thai 0544/01/01 10542/12/31
- ============================================================================*/
-
-
- [Serializable] public class ThaiBuddhistCalendar: Calendar {
-
- // Initialize our era info.
- static internal EraInfo[] thaiBuddhistEraInfo = new EraInfo[] {
- new EraInfo( 1, 1, 1, 1, -543, 544, GregorianCalendar.MaxYear + 543) // era #, start year/month/day, yearOffset, minEraYear
- };
-
- //
- // The era value for the current era.
- //
-
- public const int ThaiBuddhistEra = 1;
-
- //internal static Calendar m_defaultInstance;
-
- internal GregorianCalendarHelper helper;
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (DateTime.MinValue);
- }
- }
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (DateTime.MaxValue);
- }
- }
-
- // Return the type of the Thai Buddhist calendar.
- //
-
- public override CalendarAlgorithmType AlgorithmType
- {
- get
- {
- return CalendarAlgorithmType.SolarCalendar;
- }
- }
-
- public ThaiBuddhistCalendar() {
- helper = new GregorianCalendarHelper(this, thaiBuddhistEraInfo);
- }
-
- internal override int ID {
- get {
- return (CAL_THAI);
- }
- }
-
-
- public override DateTime AddMonths(DateTime time, int months) {
- return (helper.AddMonths(time, months));
- }
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (helper.AddYears(time, years));
- }
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- return (helper.GetDaysInMonth(year, month, era));
- }
-
-
- public override int GetDaysInYear(int year, int era) {
- return (helper.GetDaysInYear(year, era));
- }
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (helper.GetDayOfMonth(time));
- }
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return (helper.GetDayOfWeek(time));
- }
-
-
- public override int GetDayOfYear(DateTime time)
- {
- return (helper.GetDayOfYear(time));
- }
-
-
- public override int GetMonthsInYear(int year, int era) {
- return (helper.GetMonthsInYear(year, era));
- }
-
-
- [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek)
- {
- return (helper.GetWeekOfYear(time, rule, firstDayOfWeek));
- }
-
-
- public override int GetEra(DateTime time) {
- return (helper.GetEra(time));
- }
-
- public override int GetMonth(DateTime time) {
- return (helper.GetMonth(time));
- }
-
-
- public override int GetYear(DateTime time) {
- return (helper.GetYear(time));
- }
-
-
- public override bool IsLeapDay(int year, int month, int day, int era)
- {
- return (helper.IsLeapDay(year, month, day, era));
- }
-
-
- public override bool IsLeapYear(int year, int era) {
- return (helper.IsLeapYear(year, era));
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
- public override int GetLeapMonth(int year, int era)
- {
- return (helper.GetLeapMonth(year, era));
- }
-
-
- public override bool IsLeapMonth(int year, int month, int era) {
- return (helper.IsLeapMonth(year, month, era));
- }
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era));
- }
-
-
- public override int[] Eras {
- get {
- return (helper.Eras);
- }
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2572;
-
-
- public override int TwoDigitYearMax
- {
- get
- {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- VerifyWritable();
- if (value < 99 || value > helper.MaxYear) {
- throw new ArgumentOutOfRangeException(
- "year",
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- 99,
- helper.MaxYear));
-
- }
- twoDigitYearMax = value;
- }
- }
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- return (helper.ToFourDigitYear(year, this.TwoDigitYearMax));
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
index e5e615f1b3..ca053eded3 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
+++ b/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
@@ -3,44 +3,51 @@
// See the LICENSE file in the project root for more information.
//
-namespace System.Globalization {
- using System.Text;
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- internal static class TimeSpanFormat {
-
- private static String IntToString(int n, int digits) {
+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)
+ {
return ParseNumbers.IntToString(n, 10, digits, '0', 0);
}
- 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(false /*isNegative*/);
+ internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(true /*isNegative*/);
- internal enum Pattern {
- None = 0,
+ internal enum Pattern
+ {
+ None = 0,
Minimum = 1,
- Full = 2,
- }
+ Full = 2,
+ }
//
// Format
//
// Actions: Main method called from TimeSpan.ToString
//
- internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider) {
+ internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider)
+ {
if (format == null || format.Length == 0)
format = "c";
// standard formats
- if (format.Length == 1) {
+ 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') {
+ if (f == 'g' || f == 'G')
+ {
Pattern pattern;
DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
@@ -52,10 +59,10 @@ namespace System.Globalization {
pattern = Pattern.Minimum;
else
pattern = Pattern.Full;
-
+
return FormatStandard(value, false, format, pattern);
}
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
}
return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider));
@@ -66,32 +73,37 @@ namespace System.Globalization {
//
// Actions: Format the TimeSpan instance using the specified format.
//
- private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern) {
+ private static String 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;
- if (value._ticks < 0) {
+ if (value._ticks < 0)
+ {
day = -day;
time = -time;
}
- int hours = (int)(time / TimeSpan.TicksPerHour % 24);
- int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
- int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
+ int hours = (int)(time / TimeSpan.TicksPerHour % 24);
+ int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
+ int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
FormatLiterals literal;
- if (isInvariant) {
+ if (isInvariant)
+ {
if (value._ticks < 0)
literal = NegativeInvariantFormatLiterals;
else
literal = PositiveInvariantFormatLiterals;
}
- else {
+ else
+ {
literal = new FormatLiterals();
literal.Init(format, pattern == Pattern.Full);
}
- if (fraction != 0) { // truncate the partial second to the specified length
+ if (fraction != 0)
+ { // truncate the partial second to the specified length
fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
}
@@ -99,7 +111,8 @@ namespace System.Globalization {
// Pattern.Minimum: [-][d.]hh:mm:ss[.fffffff]
sb.Append(literal.Start); // [-]
- if (pattern == Pattern.Full || day != 0) { //
+ if (pattern == Pattern.Full || day != 0)
+ { //
sb.Append(day); // [dd]
sb.Append(literal.DayHourSep); // [.]
} //
@@ -108,23 +121,29 @@ namespace System.Globalization {
sb.Append(IntToString(minutes, literal.mm)); // mm
sb.Append(literal.MinuteSecondSep); // :
sb.Append(IntToString(seconds, literal.ss)); // ss
- if (!isInvariant && pattern == Pattern.Minimum) {
+ if (!isInvariant && pattern == Pattern.Minimum)
+ {
int effectiveDigits = literal.ff;
- while (effectiveDigits > 0) {
- if (fraction % 10 == 0) {
+ while (effectiveDigits > 0)
+ {
+ if (fraction % 10 == 0)
+ {
fraction = fraction / 10;
effectiveDigits--;
}
- else {
+ else
+ {
break;
}
}
- if (effectiveDigits > 0) {
+ if (effectiveDigits > 0)
+ {
sb.Append(literal.SecondFractionSep); // [.FFFFFFF]
sb.Append((fraction).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
}
- else if (pattern == Pattern.Full || fraction != 0) {
+ else if (pattern == Pattern.Full || fraction != 0)
+ {
sb.Append(literal.SecondFractionSep); // [.]
sb.Append(IntToString(fraction, literal.ff)); // [fffffff]
} //
@@ -141,47 +160,50 @@ namespace System.Globalization {
//
// Actions: Format the TimeSpan instance using the specified format.
//
- internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi) {
-
+ internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi)
+ {
Debug.Assert(dtfi != null, "dtfi == null");
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;
}
- int hours = (int)(time / TimeSpan.TicksPerHour % 24);
- int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
- int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
+ int hours = (int)(time / TimeSpan.TicksPerHour % 24);
+ int minutes = (int)(time / TimeSpan.TicksPerMinute % 60);
+ int seconds = (int)(time / TimeSpan.TicksPerSecond % 60);
int fraction = (int)(time % TimeSpan.TicksPerSecond);
long tmp = 0;
int i = 0;
int tokenLen;
StringBuilder result = StringBuilderCache.Acquire();
-
- while (i < format.Length) {
+
+ while (i < format.Length)
+ {
char ch = format[i];
int nextChar;
- switch (ch) {
+ switch (ch)
+ {
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ 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(Environment.GetResourceString("Format_InvalidString"));
+ 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(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
@@ -190,7 +212,7 @@ namespace System.Globalization {
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
@@ -202,21 +224,25 @@ namespace System.Globalization {
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
tmp = (long)fraction;
tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
- while (effectiveDigits > 0) {
- if (tmp % 10 == 0) {
+ while (effectiveDigits > 0)
+ {
+ if (tmp % 10 == 0)
+ {
tmp = tmp / 10;
effectiveDigits--;
}
- else {
+ else
+ {
break;
}
}
- if (effectiveDigits > 0) {
+ if (effectiveDigits > 0)
+ {
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[effectiveDigits - 1], CultureInfo.InvariantCulture));
}
break;
@@ -227,12 +253,12 @@ namespace System.Globalization {
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
case '\"':
- tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
+ tokenLen = DateTimeFormat.ParseQuoteString(format, i, result);
break;
case '%':
// Optional format character.
@@ -241,7 +267,8 @@ namespace System.Globalization {
nextChar = DateTimeFormat.ParseNextChar(format, i);
// nextChar will be -1 if we already reach the end of the format string.
// Besides, we will not allow "%%" appear in the pattern.
- if (nextChar >= 0 && nextChar != (int)'%') {
+ if (nextChar >= 0 && nextChar != (int)'%')
+ {
result.Append(TimeSpanFormat.FormatCustomized(value, ((char)nextChar).ToString(), dtfi));
tokenLen = 2;
}
@@ -251,7 +278,7 @@ namespace System.Globalization {
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
//
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
}
break;
case '\\':
@@ -263,55 +290,67 @@ namespace System.Globalization {
{
result.Append(((char)nextChar));
tokenLen = 2;
- }
+ }
else
{
//
// This means that '\' is at the end of the formatting string.
//
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
}
break;
default:
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
}
i += tokenLen;
}
return StringBuilderCache.GetStringAndRelease(result);
-
}
- internal struct FormatLiterals {
- internal String Start {
- get {
+ internal struct FormatLiterals
+ {
+ internal String Start
+ {
+ get
+ {
return literals[0];
}
}
- internal String DayHourSep {
- get {
+ internal String DayHourSep
+ {
+ get
+ {
return literals[1];
}
}
- internal String HourMinuteSep {
- get {
+ internal String HourMinuteSep
+ {
+ get
+ {
return literals[2];
}
}
- internal String MinuteSecondSep {
- get {
+ internal String MinuteSecondSep
+ {
+ get
+ {
return literals[3];
}
}
- internal String SecondFractionSep {
- get {
+ internal String SecondFractionSep
+ {
+ get
+ {
return literals[4];
}
}
- internal String End {
- get {
+ internal String End
+ {
+ get
+ {
return literals[5];
}
}
@@ -320,13 +359,14 @@ namespace System.Globalization {
internal int hh;
internal int mm;
internal int ss;
- internal int ff;
+ internal int ff;
private String[] literals;
/* factory method for static invariant FormatLiterals */
- internal static FormatLiterals InitInvariant(bool isNegative) {
+ internal static FormatLiterals InitInvariant(bool isNegative)
+ {
FormatLiterals x = new FormatLiterals();
x.literals = new String[6];
x.literals[0] = isNegative ? "-" : String.Empty;
@@ -334,7 +374,7 @@ namespace System.Globalization {
x.literals[2] = ":";
x.literals[3] = ":";
x.literals[4] = ".";
- x.literals[5] = String.Empty;
+ x.literals[5] = String.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
@@ -348,9 +388,10 @@ 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++)
+ for (int i = 0; i < literals.Length; i++)
literals[i] = String.Empty;
dd = 0;
hh = 0;
@@ -361,30 +402,37 @@ namespace System.Globalization {
StringBuilder sb = StringBuilderCache.Acquire();
bool inQuote = false;
char quote = '\'';
- int field = 0;
+ int field = 0;
- for (int i = 0; i < format.Length; i++) {
- switch (format[i]) {
+ for (int i = 0; i < format.Length; i++)
+ {
+ switch (format[i])
+ {
case '\'':
case '\"':
- if (inQuote && (quote == format[i])) {
+ 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) {
+ if (field >= 0 && field <= 5)
+ {
literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
- else {
+ else
+ {
return; // how did we get here?
}
}
- else if (!inQuote) {
+ else if (!inQuote)
+ {
/* we are at the start of a new quote block */
quote = format[i];
inQuote = true;
}
- else {
+ else
+ {
/* we were in a quote and saw the other type of quote character, so we are still in a quote */
}
break;
@@ -392,13 +440,15 @@ namespace System.Globalization {
Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
- if (!inQuote) {
+ if (!inQuote)
+ {
i++; /* skip next character that is escaped by this backslash or percent sign */
break;
}
goto default;
case 'd':
- if (!inQuote) {
+ if (!inQuote)
+ {
Debug.Assert((field == 0 && sb.Length == 0) || field == 1,
"field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
@@ -406,7 +456,8 @@ namespace System.Globalization {
}
break;
case 'h':
- if (!inQuote) {
+ if (!inQuote)
+ {
Debug.Assert((field == 1 && sb.Length == 0) || field == 2,
"field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
@@ -414,7 +465,8 @@ namespace System.Globalization {
}
break;
case 'm':
- if (!inQuote) {
+ if (!inQuote)
+ {
Debug.Assert((field == 2 && sb.Length == 0) || field == 3,
"field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
@@ -422,7 +474,8 @@ namespace System.Globalization {
}
break;
case 's':
- if (!inQuote) {
+ if (!inQuote)
+ {
Debug.Assert((field == 3 && sb.Length == 0) || field == 4,
"field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
@@ -431,7 +484,8 @@ namespace System.Globalization {
break;
case 'f':
case 'F':
- if (!inQuote) {
+ if (!inQuote)
+ {
Debug.Assert((field == 4 && sb.Length == 0) || field == 5,
"field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
@@ -453,14 +507,16 @@ namespace System.Globalization {
Debug.Assert(0 < ss && ss < 3, "0 < ss && ss < 3, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
Debug.Assert(0 < ff && ff < 8, "0 < ff && ff < 8, Bug in System.Globalization.DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
- if (useInvariantFieldLengths) {
+ if (useInvariantFieldLengths)
+ {
dd = 2;
hh = 2;
mm = 2;
ss = 2;
ff = DateTimeFormat.MaxSecondsFractionDigits;
}
- else {
+ else
+ {
if (dd < 1 || dd > 2) dd = 2; // The DTFI property has a problem. let's try to make the best of the situation.
if (hh < 1 || hh > 2) hh = 2;
if (mm < 1 || mm > 2) mm = 2;
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
index d83c5fa151..a29e6c2e29 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
+++ b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
@@ -50,83 +50,95 @@
// TimeSpanTokenizer.NextChar and TimeSpanTokenizer.BackOne() are called directly.
//
////////////////////////////////////////////////////////////////////////////
-namespace System.Globalization {
- using System.Text;
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
-
- internal static class TimeSpanParse {
+
+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 static void ValidateStyles(TimeSpanStyles style, String parameterName) {
+ internal static void ValidateStyles(TimeSpanStyles style, String parameterName)
+ {
if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTimeSpanStyles"), parameterName);
+ throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName);
}
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 maxDays = 10675199;
+ internal const int maxHours = 23;
+ internal const int maxMinutes = 59;
+ internal const int maxSeconds = 59;
internal const int maxFraction = 9999999;
#region InternalSupport
- enum TimeSpanThrowStyle {
- None = 0,
- All = 1,
+ private enum TimeSpanThrowStyle
+ {
+ None = 0,
+ All = 1,
}
- private enum ParseFailureKind {
- None = 0,
- ArgumentNull = 1,
- Format = 2,
- FormatWithParameter = 3,
- Overflow = 4,
+ private enum ParseFailureKind
+ {
+ None = 0,
+ ArgumentNull = 1,
+ Format = 2,
+ FormatWithParameter = 3,
+ Overflow = 4,
}
[Flags]
- 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,
+ 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 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);
- struct TimeSpanToken {
+ 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) {
+ public TimeSpanToken(int number)
+ {
ttt = TTT.Num;
num = number;
zeroes = 0;
sep = null;
}
- public TimeSpanToken(int leadingZeroes, int number) {
+ public TimeSpanToken(int leadingZeroes, int number)
+ {
ttt = TTT.Num;
num = number;
zeroes = leadingZeroes;
sep = null;
}
- public bool IsInvalidNumber(int maxValue, int maxPrecision) {
+ public bool IsInvalidNumber(int maxValue, int maxPrecision)
+ {
Debug.Assert(ttt == TTT.Num);
Debug.Assert(num > -1);
Debug.Assert(maxValue > 0);
@@ -138,12 +150,12 @@ namespace System.Globalization {
return false; // all validation past this point applies only to fields with precision limits
if (zeroes > maxPrecision)
return true;
- if (num == 0 || zeroes == 0)
+ if (num == 0 || zeroes == 0)
return false;
// num > 0 && zeroes > 0 && num <= maxValue && zeroes <= maxPrecision
- return (num >= (maxValue/(long)Math.Pow(10, zeroes-1)));
- }
+ return (num >= (maxValue / (long)Math.Pow(10, zeroes - 1)));
+ }
}
//
@@ -151,41 +163,50 @@ namespace System.Globalization {
//
// Actions: TimeSpanTokenizer.GetNextToken() returns the next token in the input string.
//
- struct TimeSpanTokenizer {
+ private struct TimeSpanTokenizer
+ {
private int m_pos;
private String m_value;
- internal void Init(String input) {
+ internal void Init(String input)
+ {
Init(input, 0);
}
- internal void Init(String input, int startPosition) {
+ 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() {
+ internal TimeSpanToken GetNextToken()
+ {
Debug.Assert(m_pos > -1);
TimeSpanToken tok = new TimeSpanToken();
char ch = CurrentChar;
- if (ch == (char)0) {
+ if (ch == (char)0)
+ {
tok.ttt = TTT.End;
return tok;
}
- if (ch >= '0' && ch <= '9') {
+ if (ch >= '0' && ch <= '9')
+ {
tok.ttt = TTT.Num;
tok.num = 0;
tok.zeroes = 0;
- do {
- if ((tok.num & 0xF0000000) != 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) {
+ if (tok.num < 0)
+ {
tok.ttt = TTT.NumOverflow;
return tok;
}
@@ -193,12 +214,14 @@ namespace System.Globalization {
} while (ch >= '0' && ch <= '9');
return tok;
}
- else {
+ else
+ {
tok.ttt = TTT.Sep;
int startIndex = m_pos;
int length = 0;
- while (ch != (char)0 && (ch < '0' || '9' < ch)) {
+ while (ch != (char)0 && (ch < '0' || '9' < ch))
+ {
ch = NextChar;
length++;
}
@@ -207,53 +230,70 @@ namespace System.Globalization {
}
}
- internal Boolean EOL {
- get {
- return m_pos >= (m_value.Length-1);
+ 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() {
+ internal void BackOne()
+ {
if (m_pos > 0) --m_pos;
}
- internal char NextChar {
- get {
+ internal char NextChar
+ {
+ get
+ {
m_pos++;
return CurrentChar;
}
}
- internal char CurrentChar {
- get {
- if (m_pos > -1 && m_pos < m_value.Length) {
+ internal char CurrentChar
+ {
+ get
+ {
+ if (m_pos > -1 && m_pos < m_value.Length)
+ {
return m_value[m_pos];
}
- else {
- return (char) 0;
+ else
+ {
+ return (char)0;
}
}
}
}
-
+
// This stores intermediary parsing state for the standard formats
- struct TimeSpanRawInfo {
- internal TimeSpanFormat.FormatLiterals PositiveInvariant {
- get {
+ private struct TimeSpanRawInfo
+ {
+ internal TimeSpanFormat.FormatLiterals PositiveInvariant
+ {
+ get
+ {
return TimeSpanFormat.PositiveInvariantFormatLiterals;
}
}
- internal TimeSpanFormat.FormatLiterals NegativeInvariant {
- get {
+ internal TimeSpanFormat.FormatLiterals NegativeInvariant
+ {
+ get
+ {
return TimeSpanFormat.NegativeInvariantFormatLiterals;
}
}
- internal TimeSpanFormat.FormatLiterals PositiveLocalized {
- get {
- if (!m_posLocInit) {
+ internal TimeSpanFormat.FormatLiterals PositiveLocalized
+ {
+ get
+ {
+ if (!m_posLocInit)
+ {
m_posLoc = new TimeSpanFormat.FormatLiterals();
m_posLoc.Init(m_fullPosPattern, false);
m_posLocInit = true;
@@ -261,99 +301,110 @@ namespace System.Globalization {
return m_posLoc;
}
}
- internal TimeSpanFormat.FormatLiterals NegativeLocalized {
- get {
- if (!m_negLocInit) {
+ internal TimeSpanFormat.FormatLiterals NegativeLocalized
+ {
+ get
+ {
+ if (!m_negLocInit)
+ {
m_negLoc = new TimeSpanFormat.FormatLiterals();
- m_negLoc.Init(m_fullNegPattern, false);
- m_negLocInit = true;
+ 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 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];
+ 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]
+ 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];
+ && 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];
+ 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];
+ 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];
-
+ 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];
+ 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];
+ 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]
+ 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];
+ && pattern.End == literals[4];
}
internal TTT lastSeenTTT;
@@ -374,7 +425,8 @@ namespace System.Globalization {
private const int MaxLiteralTokens = 6;
private const int MaxNumericTokens = 5;
- internal void Init(DateTimeFormatInfo dtfi) {
+ internal void Init(DateTimeFormatInfo dtfi)
+ {
Debug.Assert(dtfi != null);
lastSeenTTT = TTT.None;
@@ -383,7 +435,7 @@ namespace System.Globalization {
NumCount = 0;
literals = new String[MaxLiteralTokens];
- numbers = new TimeSpanToken[MaxNumericTokens];
+ numbers = new TimeSpanToken[MaxNumericTokens];
m_fullPosPattern = dtfi.FullTimeSpanPositivePattern;
m_fullNegPattern = dtfi.FullTimeSpanNegativePattern;
@@ -391,23 +443,28 @@ namespace System.Globalization {
m_negLocInit = false;
}
- internal Boolean ProcessToken(ref TimeSpanToken tok, ref TimeSpanResult result) {
- if (tok.ttt == TTT.NumOverflow) {
+ 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) {
+ 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) {
+ switch (tok.ttt)
+ {
case TTT.Sep:
if (!AddSep(tok.sep, ref result)) return false;
break;
case TTT.Num:
- if (tokenCount == 0) {
+ if (tokenCount == 0)
+ {
if (!AddSep(String.Empty, ref result)) return false;
}
if (!AddNum(tok, ref result)) return false;
@@ -421,8 +478,10 @@ namespace System.Globalization {
return true;
}
- private bool AddSep(String sep, ref TimeSpanResult result) {
- if (SepCount >= MaxLiteralTokens || tokenCount >= MaxTokens) {
+ private bool AddSep(String sep, ref TimeSpanResult result)
+ {
+ if (SepCount >= MaxLiteralTokens || tokenCount >= MaxTokens)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan", null);
return false;
}
@@ -430,19 +489,22 @@ namespace System.Globalization {
tokenCount++;
return true;
}
- private bool AddNum(TimeSpanToken num, ref TimeSpanResult result) {
- if (NumCount >= MaxNumericTokens || tokenCount >= MaxTokens) {
+ 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;
+ 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.
- struct TimeSpanResult {
+ private struct TimeSpanResult
+ {
internal TimeSpan parsedTimeSpan;
internal TimeSpanThrowStyle throwStyle;
@@ -451,60 +513,70 @@ namespace System.Globalization {
internal object m_failureMessageFormatArgument;
internal string m_failureArgumentName;
- internal void Init(TimeSpanThrowStyle canThrow) {
+ internal void Init(TimeSpanThrowStyle canThrow)
+ {
parsedTimeSpan = default(TimeSpan);
- throwStyle = canThrow;
+ throwStyle = canThrow;
}
- internal void SetFailure(ParseFailureKind failure, string failureMessageID) {
+ internal void SetFailure(ParseFailureKind failure, string failureMessageID)
+ {
SetFailure(failure, failureMessageID, null, null);
}
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) {
+ 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) {
+ string failureArgumentName)
+ {
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
m_failureArgumentName = failureArgumentName;
- if (throwStyle != TimeSpanThrowStyle.None) {
+ if (throwStyle != TimeSpanThrowStyle.None)
+ {
throw GetTimeSpanParseException();
}
}
- internal Exception GetTimeSpanParseException() {
- switch (m_failure) {
- case ParseFailureKind.ArgumentNull:
- return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID));
+ internal Exception GetTimeSpanParseException()
+ {
+ switch (m_failure)
+ {
+ case ParseFailureKind.ArgumentNull:
+ return new ArgumentNullException(m_failureArgumentName, SR.GetResourceString(m_failureMessageID));
- case ParseFailureKind.FormatWithParameter:
- return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
+ case ParseFailureKind.FormatWithParameter:
+ return new FormatException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
- case ParseFailureKind.Format:
- return new FormatException(Environment.GetResourceString(m_failureMessageID));
+ case ParseFailureKind.Format:
+ return new FormatException(SR.GetResourceString(m_failureMessageID));
- case ParseFailureKind.Overflow:
- return new OverflowException(Environment.GetResourceString(m_failureMessageID));
+ case ParseFailureKind.Overflow:
+ return new OverflowException(SR.GetResourceString(m_failureMessageID));
- default:
- Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
- return new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ default:
+ Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
+ return new FormatException(SR.Format_InvalidString);
}
}
}
- static bool TryTimeToTicks(bool positive, TimeSpanToken days, TimeSpanToken hours, TimeSpanToken minutes, TimeSpanToken seconds, TimeSpanToken fraction, out long result) {
+ 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)) {
+ || 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) {
+ if (ticks > TimeSpan.MaxMilliSeconds || ticks < TimeSpan.MinMilliSeconds)
+ {
result = 0;
return false;
}
@@ -518,18 +590,22 @@ namespace System.Globalization {
// ".01" => (1,1) => 100,000 ticks
// ".001" => (2,1) => 10,000 ticks
long f = fraction.num;
- if (f != 0) {
+ if (f != 0)
+ {
long lowerLimit = TimeSpan.TicksPerTenthSecond;
- if (fraction.zeroes > 0) {
+ if (fraction.zeroes > 0)
+ {
long divisor = (long)Math.Pow(10, fraction.zeroes);
lowerLimit = lowerLimit / divisor;
}
- while (f < lowerLimit) {
+ while (f < lowerLimit)
+ {
f *= 10;
}
}
result = ((long)ticks * TimeSpan.TicksPerMillisecond) + f;
- if (positive && result < 0) {
+ if (positive && result < 0)
+ {
result = 0;
return false;
}
@@ -544,74 +620,92 @@ namespace System.Globalization {
//
// Actions: Main methods called from TimeSpan.Parse
#region ParseMethods
- internal static TimeSpan Parse(String input, IFormatProvider formatProvider) {
+ internal static TimeSpan Parse(String input, IFormatProvider formatProvider)
+ {
TimeSpanResult parseResult = new TimeSpanResult();
parseResult.Init(TimeSpanThrowStyle.All);
- if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult)) {
+ if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult))
+ {
return parseResult.parsedTimeSpan;
}
- else {
+ else
+ {
throw parseResult.GetTimeSpanParseException();
}
}
- internal static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) {
+ 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)) {
+ if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult))
+ {
result = parseResult.parsedTimeSpan;
return true;
}
- else {
+ else
+ {
result = default(TimeSpan);
return false;
}
}
- internal static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) {
+ 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)) {
+ if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult))
+ {
return parseResult.parsedTimeSpan;
}
- else {
+ else
+ {
throw parseResult.GetTimeSpanParseException();
}
}
- internal static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
+ 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)) {
+ if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult))
+ {
result = parseResult.parsedTimeSpan;
return true;
}
- else {
+ else
+ {
result = default(TimeSpan);
return false;
}
}
- internal static TimeSpan ParseExactMultiple(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) {
+ 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)) {
+ if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult))
+ {
return parseResult.parsedTimeSpan;
}
- else {
+ else
+ {
throw parseResult.GetTimeSpanParseException();
}
}
- internal static Boolean TryParseExactMultiple(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
+ 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)) {
+ if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult))
+ {
result = parseResult.parsedTimeSpan;
return true;
}
- else {
+ else
+ {
result = default(TimeSpan);
return false;
}
@@ -626,14 +720,17 @@ namespace System.Globalization {
//
// 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) {
+ 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) {
+ if (input == String.Empty)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
@@ -648,19 +745,23 @@ namespace System.Globalization {
/* 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)) {
+ 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) {
+ if (!tokenizer.EOL)
+ {
// embedded nulls in the input string
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
- if (!ProcessTerminalState(ref raw, style, ref result)) {
+ if (!ProcessTerminalState(ref raw, style, ref result))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
@@ -685,18 +786,22 @@ namespace System.Globalization {
// 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) {
+ 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)) {
+ if (!raw.ProcessToken(ref tok, ref result))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
}
- switch (raw.NumCount) {
+ switch (raw.NumCount)
+ {
case 1:
return ProcessTerminal_D(ref raw, style, ref result);
case 2:
@@ -711,7 +816,7 @@ namespace System.Globalization {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
- }
+ }
//
// ProcessTerminal_DHMSF
@@ -719,8 +824,10 @@ namespace System.Globalization {
// 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) {
+ 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;
}
@@ -731,42 +838,52 @@ namespace System.Globalization {
bool positive = false;
bool match = false;
- if (inv) {
- if (raw.FullMatch(raw.PositiveInvariant)) {
+ if (inv)
+ {
+ if (raw.FullMatch(raw.PositiveInvariant))
+ {
match = true;
- positive = true;
+ positive = true;
}
- if (!match && raw.FullMatch(raw.NegativeInvariant)) {
+ if (!match && raw.FullMatch(raw.NegativeInvariant))
+ {
match = true;
- positive = false;
+ positive = false;
}
}
- if (loc) {
- if (!match && raw.FullMatch(raw.PositiveLocalized)) {
+ if (loc)
+ {
+ if (!match && raw.FullMatch(raw.PositiveLocalized))
+ {
match = true;
- positive = true;
+ positive = true;
}
- if (!match && raw.FullMatch(raw.NegativeLocalized)) {
+ if (!match && raw.FullMatch(raw.NegativeLocalized))
+ {
match = true;
- positive = false;
+ 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)) {
+ 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) {
+ }
+ if (!positive)
+ {
ticks = -ticks;
- if (ticks > 0) {
+ 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;
@@ -778,8 +895,10 @@ namespace System.Globalization {
// 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) {
+ 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;
}
@@ -792,75 +911,92 @@ namespace System.Globalization {
bool match = false;
bool overflow = false;
- if (inv) {
- if (raw.FullHMSFMatch(raw.PositiveInvariant)) {
- positive = true;
+ 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;
+ 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)) {
+ 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;
+ 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;
+ 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)) {
+ 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;
+ 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;
+ 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)) {
+ 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;
+ 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;
+ 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)) {
+ 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) {
+
+ if (match)
+ {
+ if (!positive)
+ {
ticks = -ticks;
- if (ticks > 0) {
+ if (ticks > 0)
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
return false;
}
@@ -869,12 +1005,14 @@ namespace System.Globalization {
return true;
}
- if (overflow) {
+ 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 {
+ else
+ {
// we couldn't find a thing
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
@@ -886,8 +1024,10 @@ namespace System.Globalization {
//
// 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) {
+ 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;
}
@@ -901,89 +1041,108 @@ namespace System.Globalization {
long ticks = 0;
- if (inv) {
- if (raw.FullHMSMatch(raw.PositiveInvariant)) {
- positive = true;
+ 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)) {
+ 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)) {
+ }
+ 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)) {
+ 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)) {
+ 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)) {
+ }
+ 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;
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ 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)) {
+ }
+ 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) {
+ if (match)
+ {
+ if (!positive)
+ {
ticks = -ticks;
- if (ticks > 0) {
+ if (ticks > 0)
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
return false;
}
}
result.parsedTimeSpan._ticks = ticks;
return true;
- }
+ }
- if (overflow) {
+ 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 {
+ else
+ {
// we couldn't find a thing
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
@@ -995,8 +1154,10 @@ namespace System.Globalization {
//
// 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) {
+ 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;
}
@@ -1007,43 +1168,53 @@ namespace System.Globalization {
bool positive = false;
bool match = false;
- if (inv) {
- if (raw.FullHMMatch(raw.PositiveInvariant)) {
+ if (inv)
+ {
+ if (raw.FullHMMatch(raw.PositiveInvariant))
+ {
match = true;
- positive = true;
+ positive = true;
}
- if (!match && raw.FullHMMatch(raw.NegativeInvariant)) {
+ if (!match && raw.FullHMMatch(raw.NegativeInvariant))
+ {
match = true;
positive = false;
}
}
- if (loc) {
- if (!match && raw.FullHMMatch(raw.PositiveLocalized)) {
+ if (loc)
+ {
+ if (!match && raw.FullHMMatch(raw.PositiveLocalized))
+ {
match = true;
- positive = true;
+ positive = true;
}
- if (!match && raw.FullHMMatch(raw.NegativeLocalized)) {
+ 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)) {
+ 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) {
+ if (!positive)
+ {
ticks = -ticks;
- if (ticks > 0) {
+ 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;
@@ -1055,8 +1226,10 @@ namespace System.Globalization {
//
// 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) {
+ 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;
}
@@ -1067,43 +1240,53 @@ namespace System.Globalization {
bool positive = false;
bool match = false;
- if (inv) {
- if (raw.FullDMatch(raw.PositiveInvariant)) {
+ if (inv)
+ {
+ if (raw.FullDMatch(raw.PositiveInvariant))
+ {
match = true;
- positive = true;
+ positive = true;
}
- if (!match && raw.FullDMatch(raw.NegativeInvariant)) {
+ if (!match && raw.FullDMatch(raw.NegativeInvariant))
+ {
match = true;
positive = false;
}
}
- if (loc) {
- if (!match && raw.FullDMatch(raw.PositiveLocalized)) {
+ if (loc)
+ {
+ if (!match && raw.FullDMatch(raw.PositiveLocalized))
+ {
match = true;
- positive = true;
+ positive = true;
}
- if (!match && raw.FullDMatch(raw.NegativeLocalized)) {
+ 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)) {
+ if (match)
+ {
+ if (!TryTimeToTicks(positive, raw.numbers[0], zero, zero, zero, zero, out ticks))
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
return false;
}
- if (!positive) {
+ if (!positive)
+ {
ticks = -ticks;
- if (ticks > 0) {
+ 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;
@@ -1116,40 +1299,49 @@ namespace System.Globalization {
//
// 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) {
+ 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) {
+ if (format == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
return false;
}
- if (format.Length == 0) {
+ if (format.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
return false;
}
- if (format.Length == 1) {
+ if (format.Length == 1)
+ {
TimeSpanStandardStyles style = TimeSpanStandardStyles.None;
- if (format[0] == 'c' || format[0] == 't' || format[0] == 'T') {
+ 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') {
+ else if (format[0] == 'g')
+ {
style = TimeSpanStandardStyles.Localized;
}
- else if (format[0] == 'G') {
+ else if (format[0] == 'G')
+ {
style = TimeSpanStandardStyles.Localized | TimeSpanStandardStyles.RequireFull;
}
- else {
+ else
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
return false;
}
return TryParseTimeSpan(input, style, formatProvider, ref result);
}
-
+
return TryParseByFormat(input, format, styles, ref result);
}
@@ -1158,7 +1350,8 @@ namespace System.Globalization {
//
// 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) {
+ 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");
@@ -1179,13 +1372,16 @@ namespace System.Globalization {
TimeSpanTokenizer tokenizer = new TimeSpanTokenizer();
tokenizer.Init(input, -1);
- while (i < format.Length) {
+ while (i < format.Length)
+ {
char ch = format[i];
int nextFormatChar;
- switch (ch) {
+ switch (ch)
+ {
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > 2 || seenHH || !ParseExactDigits(ref tokenizer, tokenLen, out hh)) {
+ if (tokenLen > 2 || seenHH || !ParseExactDigits(ref tokenizer, tokenLen, out hh))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
return false;
}
@@ -1193,7 +1389,8 @@ namespace System.Globalization {
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > 2 || seenMM || !ParseExactDigits(ref tokenizer, tokenLen, out mm)) {
+ if (tokenLen > 2 || seenMM || !ParseExactDigits(ref tokenizer, tokenLen, out mm))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
return false;
}
@@ -1201,7 +1398,8 @@ namespace System.Globalization {
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > 2 || seenSS || !ParseExactDigits(ref tokenizer, tokenLen, out ss)) {
+ if (tokenLen > 2 || seenSS || !ParseExactDigits(ref tokenizer, tokenLen, out ss))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
return false;
}
@@ -1209,7 +1407,8 @@ namespace System.Globalization {
break;
case 'f':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF || !ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff)) {
+ if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF || !ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
return false;
}
@@ -1217,7 +1416,8 @@ namespace System.Globalization {
break;
case 'F':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF) {
+ if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
return false;
}
@@ -1227,7 +1427,8 @@ namespace System.Globalization {
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)) {
+ 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;
}
@@ -1236,11 +1437,13 @@ namespace System.Globalization {
case '\'':
case '\"':
StringBuilder enquotedString = new StringBuilder();
- if (!DateTimeParse.TryParseQuoteString(format, i, enquotedString, out tokenLen)) {
+ if (!DateTimeParse.TryParseQuoteString(format, i, enquotedString, out tokenLen))
+ {
result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadQuote", ch);
return false;
}
- if (!ParseExactLiteral(ref tokenizer, enquotedString)) {
+ if (!ParseExactLiteral(ref tokenizer, enquotedString))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
return false;
}
@@ -1252,11 +1455,13 @@ namespace System.Globalization {
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)'%') {
+ if (nextFormatChar >= 0 && nextFormatChar != (int)'%')
+ {
tokenLen = 1; // skip the '%' and process the format character
break;
}
- else {
+ else
+ {
// This means that '%' is at the end of the format string or
// "%%" appears in the format string.
result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
@@ -1267,10 +1472,12 @@ namespace System.Globalization {
// For example, "\d" will insert the character 'd' into the string.
//
nextFormatChar = DateTimeFormat.ParseNextChar(format, i);
- if (nextFormatChar >= 0 && tokenizer.NextChar == (char)nextFormatChar) {
+ if (nextFormatChar >= 0 && tokenizer.NextChar == (char)nextFormatChar)
+ {
tokenLen = 2;
- }
- else {
+ }
+ 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;
@@ -1284,12 +1491,13 @@ namespace System.Globalization {
}
- if (!tokenizer.EOL) {
+ 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),
@@ -1297,33 +1505,38 @@ namespace System.Globalization {
new TimeSpanToken(mm),
new TimeSpanToken(ss),
new TimeSpanToken(leadingZeroes, ff),
- out ticks)) {
+ out ticks))
+ {
if (!positive) ticks = -ticks;
result.parsedTimeSpan._ticks = ticks;
return true;
}
- else {
+ else
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
return false;
-
}
}
- private static Boolean ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, out int result) {
+ 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) {
+ 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) {
+ while (tokenLength < maxDigitLength)
+ {
char ch = tokenizer.NextChar;
- if (ch < '0' || ch > '9') {
- tokenizer.BackOne();
+ if (ch < '0' || ch > '9')
+ {
+ tokenizer.BackOne();
break;
}
result = result * 10 + (ch - '0');
@@ -1332,8 +1545,10 @@ namespace System.Globalization {
}
return (tokenLength >= minDigitLength);
}
- private static Boolean ParseExactLiteral(ref TimeSpanTokenizer tokenizer, StringBuilder enquotedString) {
- for (int i = 0; i < enquotedString.Length; i++) {
+ private static Boolean ParseExactLiteral(ref TimeSpanTokenizer tokenizer, StringBuilder enquotedString)
+ {
+ for (int i = 0; i < enquotedString.Length; i++)
+ {
if (enquotedString[i] != tokenizer.NextChar)
return false;
}
@@ -1348,35 +1563,42 @@ namespace System.Globalization {
// 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) {
+ private static Boolean TryParseTimeSpanConstant(String input, ref TimeSpanResult result)
+ {
return (new StringParser().TryParse(input, ref result));
}
- private struct StringParser {
+ private struct StringParser
+ {
private String str;
private char ch;
private int pos;
private int len;
- internal void NextChar() {
+ internal void NextChar()
+ {
if (pos < len) pos++;
- ch = pos < len? str[pos]: (char) 0;
+ ch = pos < len ? str[pos] : (char)0;
}
- internal char NextNonDigit() {
+ internal char NextNonDigit()
+ {
int i = pos;
- while (i < len) {
+ while (i < len)
+ {
char ch = str[i];
if (ch < '0' || ch > '9') return ch;
i++;
}
- return (char) 0;
+ return (char)0;
}
-
- internal bool TryParse(String input, ref TimeSpanResult result) {
+
+ internal bool TryParse(String input, ref TimeSpanResult result)
+ {
result.parsedTimeSpan._ticks = 0;
- if (input == null) {
+ if (input == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
return false;
}
@@ -1386,109 +1608,136 @@ namespace System.Globalization {
NextChar();
SkipBlanks();
bool negative = false;
- if (ch == '-') {
+ if (ch == '-')
+ {
negative = true;
NextChar();
}
long time;
- if (NextNonDigit() == ':') {
- if (!ParseTime(out time, ref result)) {
+ if (NextNonDigit() == ':')
+ {
+ if (!ParseTime(out time, ref result))
+ {
return false;
};
}
- else {
+ else
+ {
int days;
- if (!ParseInt((int)(0x7FFFFFFFFFFFFFFFL / TimeSpan.TicksPerDay), out days, ref result)) {
+ if (!ParseInt((int)(0x7FFFFFFFFFFFFFFFL / TimeSpan.TicksPerDay), out days, ref result))
+ {
return false;
}
time = days * TimeSpan.TicksPerDay;
- if (ch == '.') {
+ if (ch == '.')
+ {
NextChar();
long remainingTime;
- if (!ParseTime(out remainingTime, ref result)) {
+ if (!ParseTime(out remainingTime, ref result))
+ {
return false;
};
time += remainingTime;
}
}
- if (negative) {
+ if (negative)
+ {
time = -time;
// Allow -0 as well
- if (time > 0) {
+ if (time > 0)
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
+ return false;
}
}
- else {
- if (time < 0) {
+ else
+ {
+ if (time < 0)
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
+ return false;
}
}
SkipBlanks();
- if (pos < len) {
+ if (pos < len)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
+ return false;
}
result.parsedTimeSpan._ticks = time;
return true;
}
- internal bool ParseInt(int max, out int i, ref TimeSpanResult result) {
+ 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) {
+ 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) {
+ if (i < 0)
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
return false;
}
NextChar();
}
- if (p == pos) {
+ if (p == pos)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
- if (i > max) {
+ if (i > max)
+ {
result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
return false;
}
return true;
}
- internal bool ParseTime(out long time, ref TimeSpanResult result) {
+ internal bool ParseTime(out long time, ref TimeSpanResult result)
+ {
time = 0;
int unit;
- if (!ParseInt(23, out unit, ref result)) {
+ if (!ParseInt(23, out unit, ref result))
+ {
return false;
}
time = unit * TimeSpan.TicksPerHour;
- if (ch != ':') {
+ if (ch != ':')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
+ return false;
}
- NextChar();
- if (!ParseInt(59, out unit, ref result)) {
+ NextChar();
+ if (!ParseInt(59, out unit, ref result))
+ {
return false;
- }
+ }
time += unit * TimeSpan.TicksPerMinute;
- if (ch == ':') {
+ if (ch == ':')
+ {
NextChar();
// allow seconds with the leading zero
- if (ch != '.') {
- if (!ParseInt(59, out unit, ref result)) {
+ if (ch != '.')
+ {
+ if (!ParseInt(59, out unit, ref result))
+ {
return false;
- }
+ }
time += unit * TimeSpan.TicksPerSecond;
}
- if (ch == '.') {
+ if (ch == '.')
+ {
NextChar();
int f = (int)TimeSpan.TicksPerSecond;
- while (f > 1 && ch >= '0' && ch <= '9') {
+ while (f > 1 && ch >= '0' && ch <= '9')
+ {
f /= 10;
time += (ch - '0') * f;
NextChar();
@@ -1498,10 +1747,11 @@ namespace System.Globalization {
return true;
}
- internal void SkipBlanks() {
+ internal void SkipBlanks()
+ {
while (ch == ' ' || ch == '\t') NextChar();
}
- }
+ }
#endregion
#region TryParseExactMultipleTimeSpan
@@ -1510,22 +1760,27 @@ namespace System.Globalization {
//
// 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) {
+ 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) {
+ if (formats == null)
+ {
result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
return false;
}
- if (input.Length == 0) {
+ if (input.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
return false;
}
- if (formats.Length == 0) {
+ if (formats.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
return false;
}
@@ -1534,8 +1789,10 @@ namespace System.Globalization {
// 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) {
+ for (int i = 0; i < formats.Length; i++)
+ {
+ if (formats[i] == null || formats[i].Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
return false;
}
@@ -1544,7 +1801,8 @@ namespace System.Globalization {
TimeSpanResult innerResult = new TimeSpanResult();
innerResult.Init(TimeSpanThrowStyle.None);
- if(TryParseExactTimeSpan(input, formats[i], formatProvider, styles, ref innerResult)) {
+ if (TryParseExactTimeSpan(input, formats[i], formatProvider, styles, ref innerResult))
+ {
result.parsedTimeSpan = innerResult.parsedTimeSpan;
return true;
}
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanStyles.cs b/src/mscorlib/src/System/Globalization/TimeSpanStyles.cs
deleted file mode 100644
index 7ba5327324..0000000000
--- a/src/mscorlib/src/System/Globalization/TimeSpanStyles.cs
+++ /dev/null
@@ -1,12 +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.
-
-namespace System.Globalization {
-
- [Flags]
- public enum TimeSpanStyles {
- None = 0x00000000,
- AssumeNegative = 0x00000001,
- }
-}
diff --git a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs b/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
deleted file mode 100644
index 06e7c7d75a..0000000000
--- a/src/mscorlib/src/System/Globalization/UmAlQuraCalendar.cs
+++ /dev/null
@@ -1,850 +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.
-
-namespace System.Globalization {
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-
- ////////////////////////////////////////////////////////////////////////////
- //
- // Notes about UmAlQuraCalendar
- //
- ////////////////////////////////////////////////////////////////////////////
- /*
- ** Calendar support range:
- ** Calendar Minimum Maximum
- ** ========== ========== ==========
- ** Gregorian 1900/04/30 2077/11/17
- ** UmAlQura 1318/01/01 1500/12/30
- */
-
- [Serializable]
- public class UmAlQuraCalendar : Calendar {
-
- internal const int MinCalendarYear = 1318;
- internal const int MaxCalendarYear = 1500;
-
- internal struct DateMapping
- {
- internal DateMapping(int MonthsLengthFlags, int GYear, int GMonth, int GDay)
- {
- HijriMonthsLengthFlags = MonthsLengthFlags;
- GregorianDate = new DateTime(GYear, GMonth, GDay);
- }
- internal int HijriMonthsLengthFlags;
- internal DateTime GregorianDate;
- }
-
- static readonly DateMapping [] HijriYearInfo = InitDateMapping();
-
- static DateMapping[] InitDateMapping()
- {
- short[] rawData = new short[] {
-//These data is taken from Tables/Excel/UmAlQura.xls please make sure that the two places are in sync
-/* DaysPerM GY GM GD D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12
-1318*/0x02EA, 1900, 4, 30,/* 0 1 0 1 0 1 1 1 0 1 0 0 4/30/1900
-1319*/0x06E9, 1901, 4, 19,/* 1 0 0 1 0 1 1 1 0 1 1 0 4/19/1901
-1320*/0x0ED2, 1902, 4, 9,/* 0 1 0 0 1 0 1 1 0 1 1 1 4/9/1902
-1321*/0x0EA4, 1903, 3, 30,/* 0 0 1 0 0 1 0 1 0 1 1 1 3/30/1903
-1322*/0x0D4A, 1904, 3, 18,/* 0 1 0 1 0 0 1 0 1 0 1 1 3/18/1904
-1323*/0x0A96, 1905, 3, 7,/* 0 1 1 0 1 0 0 1 0 1 0 1 3/7/1905
-1324*/0x0536, 1906, 2, 24,/* 0 1 1 0 1 1 0 0 1 0 1 0 2/24/1906
-1325*/0x0AB5, 1907, 2, 13,/* 1 0 1 0 1 1 0 1 0 1 0 1 2/13/1907
-1326*/0x0DAA, 1908, 2, 3,/* 0 1 0 1 0 1 0 1 1 0 1 1 2/3/1908
-1327*/0x0BA4, 1909, 1, 23,/* 0 0 1 0 0 1 0 1 1 1 0 1 1/23/1909
-1328*/0x0B49, 1910, 1, 12,/* 1 0 0 1 0 0 1 0 1 1 0 1 1/12/1910
-1329*/0x0A93, 1911, 1, 1,/* 1 1 0 0 1 0 0 1 0 1 0 1 1/1/1911
-1330*/0x052B, 1911, 12, 21,/* 1 1 0 1 0 1 0 0 1 0 1 0 12/21/1911
-1331*/0x0A57, 1912, 12, 9,/* 1 1 1 0 1 0 1 0 0 1 0 1 12/9/1912
-1332*/0x04B6, 1913, 11, 29,/* 0 1 1 0 1 1 0 1 0 0 1 0 11/29/1913
-1333*/0x0AB5, 1914, 11, 18,/* 1 0 1 0 1 1 0 1 0 1 0 1 11/18/1914
-1334*/0x05AA, 1915, 11, 8,/* 0 1 0 1 0 1 0 1 1 0 1 0 11/8/1915
-1335*/0x0D55, 1916, 10, 27,/* 1 0 1 0 1 0 1 0 1 0 1 1 10/27/1916
-1336*/0x0D2A, 1917, 10, 17,/* 0 1 0 1 0 1 0 0 1 0 1 1 10/17/1917
-1337*/0x0A56, 1918, 10, 6,/* 0 1 1 0 1 0 1 0 0 1 0 1 10/6/1918
-1338*/0x04AE, 1919, 9, 25,/* 0 1 1 1 0 1 0 1 0 0 1 0 9/25/1919
-1339*/0x095D, 1920, 9, 13,/* 1 0 1 1 1 0 1 0 1 0 0 1 9/13/1920
-1340*/0x02EC, 1921, 9, 3,/* 0 0 1 1 0 1 1 1 0 1 0 0 9/3/1921
-1341*/0x06D5, 1922, 8, 23,/* 1 0 1 0 1 0 1 1 0 1 1 0 8/23/1922
-1342*/0x06AA, 1923, 8, 13,/* 0 1 0 1 0 1 0 1 0 1 1 0 8/13/1923
-1343*/0x0555, 1924, 8, 1,/* 1 0 1 0 1 0 1 0 1 0 1 0 8/1/1924
-1344*/0x04AB, 1925, 7, 21,/* 1 1 0 1 0 1 0 1 0 0 1 0 7/21/1925
-1345*/0x095B, 1926, 7, 10,/* 1 1 0 1 1 0 1 0 1 0 0 1 7/10/1926
-1346*/0x02BA, 1927, 6, 30,/* 0 1 0 1 1 1 0 1 0 1 0 0 6/30/1927
-1347*/0x0575, 1928, 6, 18,/* 1 0 1 0 1 1 1 0 1 0 1 0 6/18/1928
-1348*/0x0BB2, 1929, 6, 8,/* 0 1 0 0 1 1 0 1 1 1 0 1 6/8/1929
-1349*/0x0764, 1930, 5, 29,/* 0 0 1 0 0 1 1 0 1 1 1 0 5/29/1930
-1350*/0x0749, 1931, 5, 18,/* 1 0 0 1 0 0 1 0 1 1 1 0 5/18/1931
-1351*/0x0655, 1932, 5, 6,/* 1 0 1 0 1 0 1 0 0 1 1 0 5/6/1932
-1352*/0x02AB, 1933, 4, 25,/* 1 1 0 1 0 1 0 1 0 1 0 0 4/25/1933
-1353*/0x055B, 1934, 4, 14,/* 1 1 0 1 1 0 1 0 1 0 1 0 4/14/1934
-1354*/0x0ADA, 1935, 4, 4,/* 0 1 0 1 1 0 1 1 0 1 0 1 4/4/1935
-1355*/0x06D4, 1936, 3, 24,/* 0 0 1 0 1 0 1 1 0 1 1 0 3/24/1936
-1356*/0x0EC9, 1937, 3, 13,/* 1 0 0 1 0 0 1 1 0 1 1 1 3/13/1937
-1357*/0x0D92, 1938, 3, 3,/* 0 1 0 0 1 0 0 1 1 0 1 1 3/3/1938
-1358*/0x0D25, 1939, 2, 20,/* 1 0 1 0 0 1 0 0 1 0 1 1 2/20/1939
-1359*/0x0A4D, 1940, 2, 9,/* 1 0 1 1 0 0 1 0 0 1 0 1 2/9/1940
-1360*/0x02AD, 1941, 1, 28,/* 1 0 1 1 0 1 0 1 0 1 0 0 1/28/1941
-1361*/0x056D, 1942, 1, 17,/* 1 0 1 1 0 1 1 0 1 0 1 0 1/17/1942
-1362*/0x0B6A, 1943, 1, 7,/* 0 1 0 1 0 1 1 0 1 1 0 1 1/7/1943
-1363*/0x0B52, 1943, 12, 28,/* 0 1 0 0 1 0 1 0 1 1 0 1 12/28/1943
-1364*/0x0AA5, 1944, 12, 16,/* 1 0 1 0 0 1 0 1 0 1 0 1 12/16/1944
-1365*/0x0A4B, 1945, 12, 5,/* 1 1 0 1 0 0 1 0 0 1 0 1 12/5/1945
-1366*/0x0497, 1946, 11, 24,/* 1 1 1 0 1 0 0 1 0 0 1 0 11/24/1946
-1367*/0x0937, 1947, 11, 13,/* 1 1 1 0 1 1 0 0 1 0 0 1 11/13/1947
-1368*/0x02B6, 1948, 11, 2,/* 0 1 1 0 1 1 0 1 0 1 0 0 11/2/1948
-1369*/0x0575, 1949, 10, 22,/* 1 0 1 0 1 1 1 0 1 0 1 0 10/22/1949
-1370*/0x0D6A, 1950, 10, 12,/* 0 1 0 1 0 1 1 0 1 0 1 1 10/12/1950
-1371*/0x0D52, 1951, 10, 2,/* 0 1 0 0 1 0 1 0 1 0 1 1 10/2/1951
-1372*/0x0A96, 1952, 9, 20,/* 0 1 1 0 1 0 0 1 0 1 0 1 9/20/1952
-1373*/0x092D, 1953, 9, 9,/* 1 0 1 1 0 1 0 0 1 0 0 1 9/9/1953
-1374*/0x025D, 1954, 8, 29,/* 1 0 1 1 1 0 1 0 0 1 0 0 8/29/1954
-1375*/0x04DD, 1955, 8, 18,/* 1 0 1 1 1 0 1 1 0 0 1 0 8/18/1955
-1376*/0x0ADA, 1956, 8, 7,/* 0 1 0 1 1 0 1 1 0 1 0 1 8/7/1956
-1377*/0x05D4, 1957, 7, 28,/* 0 0 1 0 1 0 1 1 1 0 1 0 7/28/1957
-1378*/0x0DA9, 1958, 7, 17,/* 1 0 0 1 0 1 0 1 1 0 1 1 7/17/1958
-1379*/0x0D52, 1959, 7, 7,/* 0 1 0 0 1 0 1 0 1 0 1 1 7/7/1959
-1380*/0x0AAA, 1960, 6, 25,/* 0 1 0 1 0 1 0 1 0 1 0 1 6/25/1960
-1381*/0x04D6, 1961, 6, 14,/* 0 1 1 0 1 0 1 1 0 0 1 0 6/14/1961
-1382*/0x09B6, 1962, 6, 3,/* 0 1 1 0 1 1 0 1 1 0 0 1 6/3/1962
-1383*/0x0374, 1963, 5, 24,/* 0 0 1 0 1 1 1 0 1 1 0 0 5/24/1963
-1384*/0x0769, 1964, 5, 12,/* 1 0 0 1 0 1 1 0 1 1 1 0 5/12/1964
-1385*/0x0752, 1965, 5, 2,/* 0 1 0 0 1 0 1 0 1 1 1 0 5/2/1965
-1386*/0x06A5, 1966, 4, 21,/* 1 0 1 0 0 1 0 1 0 1 1 0 4/21/1966
-1387*/0x054B, 1967, 4, 10,/* 1 1 0 1 0 0 1 0 1 0 1 0 4/10/1967
-1388*/0x0AAB, 1968, 3, 29,/* 1 1 0 1 0 1 0 1 0 1 0 1 3/29/1968
-1389*/0x055A, 1969, 3, 19,/* 0 1 0 1 1 0 1 0 1 0 1 0 3/19/1969
-1390*/0x0AD5, 1970, 3, 8,/* 1 0 1 0 1 0 1 1 0 1 0 1 3/8/1970
-1391*/0x0DD2, 1971, 2, 26,/* 0 1 0 0 1 0 1 1 1 0 1 1 2/26/1971
-1392*/0x0DA4, 1972, 2, 16,/* 0 0 1 0 0 1 0 1 1 0 1 1 2/16/1972
-1393*/0x0D49, 1973, 2, 4,/* 1 0 0 1 0 0 1 0 1 0 1 1 2/4/1973
-1394*/0x0A95, 1974, 1, 24,/* 1 0 1 0 1 0 0 1 0 1 0 1 1/24/1974
-1395*/0x052D, 1975, 1, 13,/* 1 0 1 1 0 1 0 0 1 0 1 0 1/13/1975
-1396*/0x0A5D, 1976, 1, 2,/* 1 0 1 1 1 0 1 0 0 1 0 1 1/2/1976
-1397*/0x055A, 1976, 12, 22,/* 0 1 0 1 1 0 1 0 1 0 1 0 12/22/1976
-1398*/0x0AD5, 1977, 12, 11,/* 1 0 1 0 1 0 1 1 0 1 0 1 12/11/1977
-1399*/0x06AA, 1978, 12, 1,/* 0 1 0 1 0 1 0 1 0 1 1 0 12/1/1978
-1400*/0x0695, 1979, 11, 20,/* 1 0 1 0 1 0 0 1 0 1 1 0 11/20/1979
-1401*/0x052B, 1980, 11, 8,/* 1 1 0 1 0 1 0 0 1 0 1 0 11/8/1980
-1402*/0x0A57, 1981, 10, 28,/* 1 1 1 0 1 0 1 0 0 1 0 1 10/28/1981
-1403*/0x04AE, 1982, 10, 18,/* 0 1 1 1 0 1 0 1 0 0 1 0 10/18/1982
-1404*/0x0976, 1983, 10, 7,/* 0 1 1 0 1 1 1 0 1 0 0 1 10/7/1983
-1405*/0x056C, 1984, 9, 26,/* 0 0 1 1 0 1 1 0 1 0 1 0 9/26/1984
-1406*/0x0B55, 1985, 9, 15,/* 1 0 1 0 1 0 1 0 1 1 0 1 9/15/1985
-1407*/0x0AAA, 1986, 9, 5,/* 0 1 0 1 0 1 0 1 0 1 0 1 9/5/1986
-1408*/0x0A55, 1987, 8, 25,/* 1 0 1 0 1 0 1 0 0 1 0 1 8/25/1987
-1409*/0x04AD, 1988, 8, 13,/* 1 0 1 1 0 1 0 1 0 0 1 0 8/13/1988
-1410*/0x095D, 1989, 8, 2,/* 1 0 1 1 1 0 1 0 1 0 0 1 8/2/1989
-1411*/0x02DA, 1990, 7, 23,/* 0 1 0 1 1 0 1 1 0 1 0 0 7/23/1990
-1412*/0x05D9, 1991, 7, 12,/* 1 0 0 1 1 0 1 1 1 0 1 0 7/12/1991
-1413*/0x0DB2, 1992, 7, 1,/* 0 1 0 0 1 1 0 1 1 0 1 1 7/1/1992
-1414*/0x0BA4, 1993, 6, 21,/* 0 0 1 0 0 1 0 1 1 1 0 1 6/21/1993
-1415*/0x0B4A, 1994, 6, 10,/* 0 1 0 1 0 0 1 0 1 1 0 1 6/10/1994
-1416*/0x0A55, 1995, 5, 30,/* 1 0 1 0 1 0 1 0 0 1 0 1 5/30/1995
-1417*/0x02B5, 1996, 5, 18,/* 1 0 1 0 1 1 0 1 0 1 0 0 5/18/1996
-1418*/0x0575, 1997, 5, 7,/* 1 0 1 0 1 1 1 0 1 0 1 0 5/7/1997
-1419*/0x0B6A, 1998, 4, 27,/* 0 1 0 1 0 1 1 0 1 1 0 1 4/27/1998
-1420*/0x0BD2, 1999, 4, 17,/* 0 1 0 0 1 0 1 1 1 1 0 1 4/17/1999
-1421*/0x0BC4, 2000, 4, 6,/* 0 0 1 0 0 0 1 1 1 1 0 1 4/6/2000
-1422*/0x0B89, 2001, 3, 26,/* 1 0 0 1 0 0 0 1 1 1 0 1 3/26/2001
-1423*/0x0A95, 2002, 3, 15,/* 1 0 1 0 1 0 0 1 0 1 0 1 3/15/2002
-1424*/0x052D, 2003, 3, 4,/* 1 0 1 1 0 1 0 0 1 0 1 0 3/4/2003
-1425*/0x05AD, 2004, 2, 21,/* 1 0 1 1 0 1 0 1 1 0 1 0 2/21/2004
-1426*/0x0B6A, 2005, 2, 10,/* 0 1 0 1 0 1 1 0 1 1 0 1 2/10/2005
-1427*/0x06D4, 2006, 1, 31,/* 0 0 1 0 1 0 1 1 0 1 1 0 1/31/2006
-1428*/0x0DC9, 2007, 1, 20,/* 1 0 0 1 0 0 1 1 1 0 1 1 1/20/2007
-1429*/0x0D92, 2008, 1, 10,/* 0 1 0 0 1 0 0 1 1 0 1 1 1/10/2008
-1430*/0x0AA6, 2008, 12, 29,/* 0 1 1 0 0 1 0 1 0 1 0 1 12/29/2008
-1431*/0x0956, 2009, 12, 18,/* 0 1 1 0 1 0 1 0 1 0 0 1 12/18/2009
-1432*/0x02AE, 2010, 12, 7,/* 0 1 1 1 0 1 0 1 0 1 0 0 12/7/2010
-1433*/0x056D, 2011, 11, 26,/* 1 0 1 1 0 1 1 0 1 0 1 0 11/26/2011
-1434*/0x036A, 2012, 11, 15,/* 0 1 0 1 0 1 1 0 1 1 0 0 11/15/2012
-1435*/0x0B55, 2013, 11, 4,/* 1 0 1 0 1 0 1 0 1 1 0 1 11/4/2013
-1436*/0x0AAA, 2014, 10, 25,/* 0 1 0 1 0 1 0 1 0 1 0 1 10/25/2014
-1437*/0x094D, 2015, 10, 14,/* 1 0 1 1 0 0 1 0 1 0 0 1 10/14/2015
-1438*/0x049D, 2016, 10, 2,/* 1 0 1 1 1 0 0 1 0 0 1 0 10/2/2016
-1439*/0x095D, 2017, 9, 21,/* 1 0 1 1 1 0 1 0 1 0 0 1 9/21/2017
-1440*/0x02BA, 2018, 9, 11,/* 0 1 0 1 1 1 0 1 0 1 0 0 9/11/2018
-1441*/0x05B5, 2019, 8, 31,/* 1 0 1 0 1 1 0 1 1 0 1 0 8/31/2019
-1442*/0x05AA, 2020, 8, 20,/* 0 1 0 1 0 1 0 1 1 0 1 0 8/20/2020
-1443*/0x0D55, 2021, 8, 9,/* 1 0 1 0 1 0 1 0 1 0 1 1 8/9/2021
-1444*/0x0A9A, 2022, 7, 30,/* 0 1 0 1 1 0 0 1 0 1 0 1 7/30/2022
-1445*/0x092E, 2023, 7, 19,/* 0 1 1 1 0 1 0 0 1 0 0 1 7/19/2023
-1446*/0x026E, 2024, 7, 7,/* 0 1 1 1 0 1 1 0 0 1 0 0 7/7/2024
-1447*/0x055D, 2025, 6, 26,/* 1 0 1 1 1 0 1 0 1 0 1 0 6/26/2025
-1448*/0x0ADA, 2026, 6, 16,/* 0 1 0 1 1 0 1 1 0 1 0 1 6/16/2026
-1449*/0x06D4, 2027, 6, 6,/* 0 0 1 0 1 0 1 1 0 1 1 0 6/6/2027
-1450*/0x06A5, 2028, 5, 25,/* 1 0 1 0 0 1 0 1 0 1 1 0 5/25/2028
-1451*/0x054B, 2029, 5, 14,/* 1 1 0 1 0 0 1 0 1 0 1 0 5/14/2029
-1452*/0x0A97, 2030, 5, 3,/* 1 1 1 0 1 0 0 1 0 1 0 1 5/3/2030
-1453*/0x054E, 2031, 4, 23,/* 0 1 1 1 0 0 1 0 1 0 1 0 4/23/2031
-1454*/0x0AAE, 2032, 4, 11,/* 0 1 1 1 0 1 0 1 0 1 0 1 4/11/2032
-1455*/0x05AC, 2033, 4, 1,/* 0 0 1 1 0 1 0 1 1 0 1 0 4/1/2033
-1456*/0x0BA9, 2034, 3, 21,/* 1 0 0 1 0 1 0 1 1 1 0 1 3/21/2034
-1457*/0x0D92, 2035, 3, 11,/* 0 1 0 0 1 0 0 1 1 0 1 1 3/11/2035
-1458*/0x0B25, 2036, 2, 28,/* 1 0 1 0 0 1 0 0 1 1 0 1 2/28/2036
-1459*/0x064B, 2037, 2, 16,/* 1 1 0 1 0 0 1 0 0 1 1 0 2/16/2037
-1460*/0x0CAB, 2038, 2, 5,/* 1 1 0 1 0 1 0 1 0 0 1 1 2/5/2038
-1461*/0x055A, 2039, 1, 26,/* 0 1 0 1 1 0 1 0 1 0 1 0 1/26/2039
-1462*/0x0B55, 2040, 1, 15,/* 1 0 1 0 1 0 1 0 1 1 0 1 1/15/2040
-1463*/0x06D2, 2041, 1, 4,/* 0 1 0 0 1 0 1 1 0 1 1 0 1/4/2041
-1464*/0x0EA5, 2041, 12, 24,/* 1 0 1 0 0 1 0 1 0 1 1 1 12/24/2041
-1465*/0x0E4A, 2042, 12, 14,/* 0 1 0 1 0 0 1 0 0 1 1 1 12/14/2042
-1466*/0x0A95, 2043, 12, 3,/* 1 0 1 0 1 0 0 1 0 1 0 1 12/3/2043
-1467*/0x052D, 2044, 11, 21,/* 1 0 1 1 0 1 0 0 1 0 1 0 11/21/2044
-1468*/0x0AAD, 2045, 11, 10,/* 1 0 1 1 0 1 0 1 0 1 0 1 11/10/2045
-1469*/0x036C, 2046, 10, 31,/* 0 0 1 1 0 1 1 0 1 1 0 0 10/31/2046
-1470*/0x0759, 2047, 10, 20,/* 1 0 0 1 1 0 1 0 1 1 1 0 10/20/2047
-1471*/0x06D2, 2048, 10, 9,/* 0 1 0 0 1 0 1 1 0 1 1 0 10/9/2048
-1472*/0x0695, 2049, 9, 28,/* 1 0 1 0 1 0 0 1 0 1 1 0 9/28/2049
-1473*/0x052D, 2050, 9, 17,/* 1 0 1 1 0 1 0 0 1 0 1 0 9/17/2050
-1474*/0x0A5B, 2051, 9, 6,/* 1 1 0 1 1 0 1 0 0 1 0 1 9/6/2051
-1475*/0x04BA, 2052, 8, 26,/* 0 1 0 1 1 1 0 1 0 0 1 0 8/26/2052
-1476*/0x09BA, 2053, 8, 15,/* 0 1 0 1 1 1 0 1 1 0 0 1 8/15/2053
-1477*/0x03B4, 2054, 8, 5,/* 0 0 1 0 1 1 0 1 1 1 0 0 8/5/2054
-1478*/0x0B69, 2055, 7, 25,/* 1 0 0 1 0 1 1 0 1 1 0 1 7/25/2055
-1479*/0x0B52, 2056, 7, 14,/* 0 1 0 0 1 0 1 0 1 1 0 1 7/14/2056
-1480*/0x0AA6, 2057, 7, 3,/* 0 1 1 0 0 1 0 1 0 1 0 1 7/3/2057
-1481*/0x04B6, 2058, 6, 22,/* 0 1 1 0 1 1 0 1 0 0 1 0 6/22/2058
-1482*/0x096D, 2059, 6, 11,/* 1 0 1 1 0 1 1 0 1 0 0 1 6/11/2059
-1483*/0x02EC, 2060, 5, 31,/* 0 0 1 1 0 1 1 1 0 1 0 0 5/31/2060
-1484*/0x06D9, 2061, 5, 20,/* 1 0 0 1 1 0 1 1 0 1 1 0 5/20/2061
-1485*/0x0EB2, 2062, 5, 10,/* 0 1 0 0 1 1 0 1 0 1 1 1 5/10/2062
-1486*/0x0D54, 2063, 4, 30,/* 0 0 1 0 1 0 1 0 1 0 1 1 4/30/2063
-1487*/0x0D2A, 2064, 4, 18,/* 0 1 0 1 0 1 0 0 1 0 1 1 4/18/2064
-1488*/0x0A56, 2065, 4, 7,/* 0 1 1 0 1 0 1 0 0 1 0 1 4/7/2065
-1489*/0x04AE, 2066, 3, 27,/* 0 1 1 1 0 1 0 1 0 0 1 0 3/27/2066
-1490*/0x096D, 2067, 3, 16,/* 1 0 1 1 0 1 1 0 1 0 0 1 3/16/2067
-1491*/0x0D6A, 2068, 3, 5,/* 0 1 0 1 0 1 1 0 1 0 1 1 3/5/2068
-1492*/0x0B54, 2069, 2, 23,/* 0 0 1 0 1 0 1 0 1 1 0 1 2/23/2069
-1493*/0x0B29, 2070, 2, 12,/* 1 0 0 1 0 1 0 0 1 1 0 1 2/12/2070
-1494*/0x0A93, 2071, 2, 1,/* 1 1 0 0 1 0 0 1 0 1 0 1 2/1/2071
-1495*/0x052B, 2072, 1, 21,/* 1 1 0 1 0 1 0 0 1 0 1 0 1/21/2072
-1496*/0x0A57, 2073, 1, 9,/* 1 1 1 0 1 0 1 0 0 1 0 1 1/9/2073
-1497*/0x0536, 2073, 12, 30,/* 0 1 1 0 1 1 0 0 1 0 1 0 12/30/2073
-1498*/0x0AB5, 2074, 12, 19,/* 1 0 1 0 1 1 0 1 0 1 0 1 12/19/2074
-1499*/0x06AA, 2075, 12, 9,/* 0 1 0 1 0 1 0 1 0 1 1 0 12/9/2075
-1500*/0x0E93, 2076, 11, 27,/* 1 1 0 0 1 0 0 1 0 1 1 1 11/27/2076
-1501*/ 0, 2077, 11, 17,/* 0 0 0 0 0 0 0 0 0 0 0 0 11/17/2077
-
-*/ };
-
- // Direct inline initialization of DateMapping array would produce a lot of code bloat.
-
- // We take advantage of C# compiler compiles inline initialization of primitive type array into very compact code.
- // So we start with raw data stored in primitive type array, and initialize the DateMapping out of it
-
- DateMapping[] mapping = new DateMapping[rawData.Length / 4];
- for (int i = 0; i < mapping.Length; i++)
- mapping[i] = new DateMapping(rawData[i * 4], rawData[i * 4 + 1], rawData[i * 4 + 2], rawData[i * 4 + 3]);
- return mapping;
- }
-
- public const int UmAlQuraEra = 1;
-
- internal const int DateCycle = 30;
- internal const int DatePartYear = 0;
- internal const int DatePartDayOfYear = 1;
- internal const int DatePartMonth = 2;
- internal const int DatePartDay = 3;
-
- //internal static Calendar m_defaultInstance;
-
-
- // This is the minimal Gregorian date that we support in the UmAlQuraCalendar.
- internal static DateTime minDate = new DateTime(1900, 4, 30);
- internal static DateTime maxDate = new DateTime((new DateTime(2077, 11, 16, 23, 59, 59, 999)).Ticks + 9999);
-
- /*=================================GetDefaultInstance==========================
- **Action: Internal method to provide a default intance of UmAlQuraCalendar. Used by NLS+ implementation
- ** and other calendars.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- /*
- internal static Calendar GetDefaultInstance() {
- if (m_defaultInstance == null) {
- m_defaultInstance = new UmAlQuraCalendar();
- }
- return (m_defaultInstance);
- }
- */
-
-
-
- public override DateTime MinSupportedDateTime
- {
- get
- {
- return (minDate);
- }
- }
-
-
- public override DateTime MaxSupportedDateTime
- {
- get
- {
- return (maxDate);
- }
- }
-
-
- // Return the type of the UmAlQura calendar.
- //
-
-
- public override CalendarAlgorithmType AlgorithmType {
- get {
- return CalendarAlgorithmType.LunarCalendar;
- }
- }
-
- // Construct an instance of UmAlQura calendar.
-
- public UmAlQuraCalendar() {
- }
-
- internal override int BaseCalendarID {
- get {
- return (CAL_HIJRI);
- }
- }
-
- internal override int ID {
- get {
- return (CAL_UMALQURA);
- }
- }
-
- protected override int DaysInYearBeforeMinSupportedYear
- {
- get
- {
- // HijriCalendar has same number of days as UmAlQuraCalendar for any given year
- // HijriCalendar says year 1317 has 355 days.
- return 355;
- }
- }
-
- /*==========================ConvertHijriToGregorian==========================
- ** Purpose: convert Hdate(year,month,day) to Gdate(year,month,day)
- ** Arguments:
- ** Input: Hijrah date: year:HijriYear, month:HijriMonth, day:HijriDay
- ** Output: Gregorian date: year:yg, month:mg, day:dg
- =========================ConvertHijriToGregorian============================*/
- static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, ref int yg, ref int mg, ref int dg)
- {
- Debug.Assert( (HijriYear >= MinCalendarYear) && (HijriYear <= MaxCalendarYear), "Hijri year is out of range.");
- Debug.Assert( HijriMonth >= 1, "Hijri month is out of range.");
- Debug.Assert( HijriDay >= 1, "Hijri day is out of range.");
- int index, b, nDays = HijriDay-1;
- DateTime dt;
-
-
- index = HijriYear - MinCalendarYear;
- dt = HijriYearInfo[index].GregorianDate;
-
-
- b = HijriYearInfo[index].HijriMonthsLengthFlags;
-
- for(int m = 1; m < HijriMonth; m++)
- {
- nDays += 29 + (b & 0x1);
- b = b >> 1;
- }
-
- dt = dt.AddDays(nDays);
- yg = dt.Year;
- mg = dt.Month;
- dg = dt.Day;
- }
-
- /*=================================GetAbsoluteDateUmAlQura==========================
- **Action: Gets the Absolute date for the given UmAlQura date. The absolute date means
- ** the number of days from January 1st, 1 A.D.
- **Returns:
- **Arguments:
- **Exceptions:
- ============================================================================*/
- static long GetAbsoluteDateUmAlQura(int year, int month, int day) {
- //Caller should check the validaty of year, month and day.
-
- int yg=0,mg=0,dg=0;
- ConvertHijriToGregorian(year, month, day, ref yg, ref mg, ref dg);
- return GregorianCalendar.GetAbsoluteDate(yg,mg,dg);
- }
-
- static internal void CheckTicksRange(long ticks) {
- if (ticks < minDate.Ticks || ticks > maxDate.Ticks) {
- throw new ArgumentOutOfRangeException(
- "time",
- String.Format(
- CultureInfo.InvariantCulture,
- Environment.GetResourceString("ArgumentOutOfRange_CalendarRange"),
- minDate,
- maxDate));
- }
- }
-
- static internal void CheckEraRange(int era) {
- if (era != CurrentEra && era != UmAlQuraEra) {
- throw new ArgumentOutOfRangeException(nameof(era), Environment.GetResourceString("ArgumentOutOfRange_InvalidEraValue"));
- }
- }
-
- static internal void CheckYearRange(int year, int era) {
- CheckEraRange(era);
- if (year < MinCalendarYear || year > MaxCalendarYear) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MinCalendarYear,
- MaxCalendarYear));
- }
- }
-
- static internal void CheckYearMonthRange(int year, int month, int era) {
- CheckYearRange(year, era);
- if (month < 1 || month > 12) {
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_Month"));
- }
- }
-
- /*========================ConvertGregorianToHijri============================
- ** Purpose: convert DateTime to Hdate(year,month,day)
- ** Arguments:
- ** Input: DateTime
- ** Output: Hijrah date: year:HijriYear, month:HijriMonth, day:HijriDay
- ============================================================================*/
- static void ConvertGregorianToHijri(DateTime time, ref int HijriYear, ref int HijriMonth, ref int HijriDay)
- {
-
- int index, b, DaysPerThisMonth;
- double nDays;
- TimeSpan ts;
- int yh1=0, mh1=0, dh1=0;
-
- Debug.Assert((time.Ticks >= minDate.Ticks) && (time.Ticks <= maxDate.Ticks), "Gregorian date is out of range.");
-
- // Find the index where we should start our search by quessing the Hijri year that we will be in HijriYearInfo.
- // A Hijri year is 354 or 355 days. Use 355 days so that we will search from a lower index.
-
- index = (int)((time.Ticks - minDate.Ticks) / Calendar.TicksPerDay) / 355;
- do
- {
- } while (time.CompareTo(HijriYearInfo[++index].GregorianDate)>0); //while greater
-
- if (time.CompareTo(HijriYearInfo[index].GregorianDate) != 0)
- {
- index--;
- }
-
- ts = time.Subtract(HijriYearInfo[index].GregorianDate);
- yh1 = index + MinCalendarYear;
-
- mh1 = 1;
- dh1 = 1;
- nDays = ts.TotalDays;
- b = HijriYearInfo[index].HijriMonthsLengthFlags;
- DaysPerThisMonth = 29 + (b&1);
-
- while (nDays >= DaysPerThisMonth)
- {
- nDays -= DaysPerThisMonth;
- b = b >> 1;
- DaysPerThisMonth = 29 + (b&1);
- mh1++;
- }
- dh1 += (int)nDays;
-
- HijriDay = dh1;
- HijriMonth = mh1;
- HijriYear = yh1;
- }
-
- /*=================================GetDatePart==========================
- **Action: Returns a given date part of this <i>DateTime</i>. This method is used
- ** to compute the year, day-of-year, month, or day part.
- **Returns:
- **Arguments:
- **Exceptions: ArgumentException if part is incorrect.
- **Notes:
- ** First, we get the absolute date (the number of days from January 1st, 1 A.C) for the given ticks.
- ** Use the formula (((AbsoluteDate - 226894) * 33) / (33 * 365 + 8)) + 1, we can a rough value for the UmAlQura year.
- ** In order to get the exact UmAlQura year, we compare the exact absolute date for UmAlQuraYear and (UmAlQuraYear + 1).
- ** From here, we can get the correct UmAlQura year.
- ============================================================================*/
-
- internal virtual int GetDatePart(DateTime time, int part) {
- int UmAlQuraYear=0; // UmAlQura year
- int UmAlQuraMonth=0; // UmAlQura month
- int UmAlQuraDay=0; // UmAlQura day
- long ticks = time.Ticks;
- CheckTicksRange(ticks);
-
- ConvertGregorianToHijri(time, ref UmAlQuraYear, ref UmAlQuraMonth, ref UmAlQuraDay);
-
- if (part == DatePartYear)
- return (UmAlQuraYear);
-
- if (part == DatePartMonth)
- return (UmAlQuraMonth);
-
- if (part == DatePartDay)
- return (UmAlQuraDay);
-
- if (part == DatePartDayOfYear)
- return (int)(GetAbsoluteDateUmAlQura(UmAlQuraYear, UmAlQuraMonth, UmAlQuraDay) - GetAbsoluteDateUmAlQura(UmAlQuraYear, 1, 1) + 1);
-
- // Incorrect part value.
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DateTimeParsing"));
- }
-
- // Returns the DateTime resulting from adding the given number of
- // months to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year and month parts of the specified DateTime by
- // value months, and, if required, adjusting the day part of the
- // resulting date downwards to the last day of the resulting month in the
- // resulting year. The time-of-day part of the result is the same as the
- // time-of-day part of the specified DateTime.
- //
- // In more precise terms, considering the specified DateTime to be of the
- // form y / m / d + t, where y is the
- // year, m is the month, d is the day, and t is the
- // time-of-day, the result is y1 / m1 / d1 + t,
- // where y1 and m1 are computed by adding value months
- // to y and m, and d1 is the largest value less than
- // or equal to d that denotes a valid day in month m1 of year
- // y1.
- //
-
-
- public override DateTime AddMonths(DateTime time, int months) {
- if (months < -120000 || months > 120000) {
- throw new ArgumentOutOfRangeException(
- nameof(months),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- -120000,
- 120000));
- }
- Contract.EndContractBlock();
- // Get the date in UmAlQura calendar.
- int y = GetDatePart(time, DatePartYear);
- int m = GetDatePart(time, DatePartMonth);
- int d = GetDatePart(time, DatePartDay);
- int i = m - 1 + months;
-
- if (i >= 0) {
- m = i % 12 + 1;
- y = y + i / 12;
- } else {
- m = 12 + (i + 1) % 12;
- y = y + (i - 11) / 12;
- }
-
- if (d>29)
- {
- int days = GetDaysInMonth(y, m);
- if (d > days) {
- d = days;
- }
- }
- CheckYearRange(y, UmAlQuraEra);
- DateTime dt = new DateTime(GetAbsoluteDateUmAlQura(y, m, d) * TicksPerDay + time.Ticks % TicksPerDay);
- Calendar.CheckAddResult(dt.Ticks, MinSupportedDateTime, MaxSupportedDateTime);
- return (dt);
- }
-
- // Returns the DateTime resulting from adding the given number of
- // years to the specified DateTime. The result is computed by incrementing
- // (or decrementing) the year part of the specified DateTime by value
- // years. If the month and day of the specified DateTime is 2/29, and if the
- // resulting year is not a leap year, the month and day of the resulting
- // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
- // parts of the result are the same as those of the specified DateTime.
- //
-
-
- public override DateTime AddYears(DateTime time, int years) {
- return (AddMonths(time, years * 12));
- }
-
- // Returns the day-of-month part of the specified DateTime. The returned
- // value is an integer between 1 and 31.
- //
-
-
- public override int GetDayOfMonth(DateTime time) {
- return (GetDatePart(time, DatePartDay));
- }
-
- // Returns the day-of-week part of the specified DateTime. The returned value
- // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
- // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
- // Thursday, 5 indicates Friday, and 6 indicates Saturday.
- //
-
-
- public override DayOfWeek GetDayOfWeek(DateTime time) {
- return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7));
- }
-
- // Returns the day-of-year part of the specified DateTime. The returned value
- // is an integer between 1 and 354 or 355.
- //
-
-
- public override int GetDayOfYear(DateTime time) {
- return (GetDatePart(time, DatePartDayOfYear));
- }
-
- /*
- internal bool CouldBeLeapYear(int year)
- {
- return ((((year * 11) + 14) % 30) < 11);
- }
- */
-
- // Returns the number of days in the month given by the year and
- // month arguments.
- //
-
-
- public override int GetDaysInMonth(int year, int month, int era) {
- CheckYearMonthRange(year, month, era);
-
- if ((HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags & (1<<month-1))==0)
- return 29;
- else
- return 30;
- }
-
- static internal int RealGetDaysInYear(int year)
- {
- int days = 0, b;
-
- Debug.Assert( (year >= MinCalendarYear) && (year <= MaxCalendarYear), "Hijri year is out of range.");
-
- b = HijriYearInfo[year-MinCalendarYear].HijriMonthsLengthFlags;
-
- for(int m = 1; m <= 12; m++)
- {
- days += 29 + (b & 0x1);
- b = b >> 1;
- }
- Debug.Assert((days == 354)||(days == 355), "Hijri year has to be 354 or 355 days.");
- return days;
- }
-
- // Returns the number of days in the year given by the year argument for the current era.
- //
-
-
- public override int GetDaysInYear(int year, int era)
- {
- CheckYearRange(year, era);
- return (RealGetDaysInYear(year));
- }
-
- // Returns the era for the specified DateTime value.
-
-
- public override int GetEra(DateTime time) {
- CheckTicksRange(time.Ticks);
- return (UmAlQuraEra);
- }
-
-
-
- public override int[] Eras {
- get {
- return (new int[] {UmAlQuraEra});
- }
- }
-
- // Returns the month part of the specified DateTime. The returned value is an
- // integer between 1 and 12.
- //
-
-
- public override int GetMonth(DateTime time) {
- return (GetDatePart(time, DatePartMonth));
- }
-
- // Returns the number of months in the specified year and era.
-
-
- public override int GetMonthsInYear(int year, int era) {
- CheckYearRange(year, era);
- return (12);
- }
-
- // Returns the year part of the specified DateTime. The returned value is an
- // integer between MinCalendarYear and MaxCalendarYear.
- //
-
-
- public override int GetYear(DateTime time) {
- return (GetDatePart(time, DatePartYear));
- }
-
- // Checks whether a given day in the specified era is a leap day. This method returns true if
- // the date is a leap day, or false if not.
- //
-
-
- public override bool IsLeapDay(int year, int month, int day, int era) {
- if (day>=1 && day <=29)
- {
- CheckYearMonthRange(year, month, era);
- return (false);
- }
-
- // The year/month/era value checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
- if (day < 1 || day > daysInMonth) {
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Day"),
- daysInMonth,
- month));
- }
- return (false);
- }
-
- // Returns the leap month in a calendar year of the specified era. This method returns 0
- // if this calendar does not have leap month, or this year is not a leap year.
- //
-
-
- public override int GetLeapMonth(int year, int era)
- {
- CheckYearRange(year, era);
- return (0);
- }
-
- // Checks whether a given month in the specified era is a leap month. This method returns true if
- // month is a leap month, or false if not.
- //
-
-
- public override bool IsLeapMonth(int year, int month, int era) {
- CheckYearMonthRange(year, month, era);
- return (false);
- }
-
- // Checks whether a given year in the specified era is a leap year. This method returns true if
- // year is a leap year, or false if not.
- //
-
-
- public override bool IsLeapYear(int year, int era)
- {
- CheckYearRange(year, era);
- if (RealGetDaysInYear(year) == 355)
- return true;
- else
- return false;
- }
-
- // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid.
- //
-
-
- public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) {
- if (day >= 1 && day <= 29)
- {
- CheckYearMonthRange(year, month, era);
- goto DayInRang;
- }
-
- // The year/month/era value checking is done in GetDaysInMonth().
- int daysInMonth = GetDaysInMonth(year, month, era);
-
- if (day < 1 || day > daysInMonth) {
- BCLDebug.Log("year = " + year + ", month = " + month + ", day = " + day);
- throw new ArgumentOutOfRangeException(
- nameof(day),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Day"),
- daysInMonth,
- month));
- }
-DayInRang:
- long lDate = GetAbsoluteDateUmAlQura(year, month, day);
-
- if (lDate >= 0) {
- return (new DateTime(lDate * GregorianCalendar.TicksPerDay + TimeToTicks(hour, minute, second, millisecond)));
- } else {
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_BadYearMonthDay"));
- }
- }
-
- private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 1451;
-
-
-
- public override int TwoDigitYearMax {
- get {
- if (twoDigitYearMax == -1) {
- twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX);
- }
- return (twoDigitYearMax);
- }
-
- set {
- if (value != 99 && (value < MinCalendarYear || value > MaxCalendarYear)) {
- throw new ArgumentOutOfRangeException(
- nameof(value),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MinCalendarYear,
- MaxCalendarYear));
- }
- Contract.EndContractBlock();
- VerifyWritable();
- // We allow year 99 to be set so that one can make ToFourDigitYearMax a no-op by setting TwoDigitYearMax to 99.
- twoDigitYearMax = value;
- }
- }
-
-
-
- public override int ToFourDigitYear(int year) {
- if (year < 0) {
- throw new ArgumentOutOfRangeException(nameof(year),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- if (year < 100) {
- return (base.ToFourDigitYear(year));
- }
-
- if ((year < MinCalendarYear) || (year > MaxCalendarYear)) {
- throw new ArgumentOutOfRangeException(
- nameof(year),
- String.Format(
- CultureInfo.CurrentCulture,
- Environment.GetResourceString("ArgumentOutOfRange_Range"),
- MinCalendarYear,
- MaxCalendarYear));
- }
- return (year);
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Globalization/UnicodeCategory.cs b/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
deleted file mode 100644
index c9898f135b..0000000000
--- a/src/mscorlib/src/System/Globalization/UnicodeCategory.cs
+++ /dev/null
@@ -1,78 +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:
-**
-**
-============================================================*/
-namespace System.Globalization {
-
- [Serializable]
- public enum UnicodeCategory {
-
- UppercaseLetter = 0,
-
- LowercaseLetter = 1,
-
- TitlecaseLetter = 2,
-
- ModifierLetter = 3,
-
- OtherLetter = 4,
-
- NonSpacingMark = 5,
-
- SpacingCombiningMark = 6,
-
- EnclosingMark = 7,
-
- DecimalDigitNumber = 8,
-
- LetterNumber = 9,
-
- OtherNumber = 10,
-
- SpaceSeparator = 11,
-
- LineSeparator = 12,
-
- ParagraphSeparator = 13,
-
- Control = 14,
-
- Format = 15,
-
- Surrogate = 16,
-
- PrivateUse = 17,
-
- ConnectorPunctuation = 18,
-
- DashPunctuation = 19,
-
- OpenPunctuation = 20,
-
- ClosePunctuation = 21,
-
- InitialQuotePunctuation = 22,
-
- FinalQuotePunctuation = 23,
-
- OtherPunctuation = 24,
-
- MathSymbol = 25,
-
- CurrencySymbol = 26,
-
- ModifierSymbol = 27,
-
- OtherSymbol = 28,
-
- OtherNotAssigned = 29,
- }
-}
diff --git a/src/mscorlib/src/System/Guid.cs b/src/mscorlib/src/System/Guid.cs
index 1116faf027..f64211d5d0 100644
--- a/src/mscorlib/src/System/Guid.cs
+++ b/src/mscorlib/src/System/Guid.cs
@@ -2,17 +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.
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Text;
- using Microsoft.Win32;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Globalization;
+using System.Text;
+using Microsoft.Win32;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
@@ -24,17 +25,17 @@ namespace System {
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
- private int _a;
- private short _b;
- private short _c;
- private byte _d;
- private byte _e;
- private byte _f;
- private byte _g;
- private byte _h;
- private byte _i;
- private byte _j;
- private byte _k;
+ private int _a;
+ private short _b;
+ private short _c;
+ private byte _d;
+ private byte _e;
+ private byte _f;
+ private byte _g;
+ private byte _h;
+ private byte _i;
+ private byte _j;
+ private byte _k;
@@ -46,10 +47,10 @@ namespace System {
//
public Guid(byte[] b)
{
- if (b==null)
+ if (b == null)
throw new ArgumentNullException(nameof(b));
if (b.Length != 16)
- throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "16"), nameof(b));
+ 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];
@@ -66,7 +67,7 @@ namespace System {
}
[CLSCompliant(false)]
- public Guid (uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
+ public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k)
{
_a = (int)a;
_b = (short)b;
@@ -86,16 +87,16 @@ namespace System {
//
public Guid(int a, short b, short c, byte[] d)
{
- if (d==null)
+ if (d == null)
throw new ArgumentNullException(nameof(d));
// Check that array is not too big
- if(d.Length != 8)
- throw new ArgumentException(Environment.GetResourceString("Arg_GuidArrayCtor", "8"), nameof(d));
+ if (d.Length != 8)
+ throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), nameof(d));
Contract.EndContractBlock();
- _a = a;
- _b = b;
- _c = c;
+ _a = a;
+ _b = b;
+ _c = c;
_d = d[0];
_e = d[1];
_f = d[2];
@@ -125,41 +126,45 @@ namespace System {
}
[Flags]
- private enum GuidStyles {
- None = 0x00000000,
- AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
- AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
- AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
- AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
- RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
- RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
- RequireDashes = 0x00000040, //Require the guid to contain dash group separators
- RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
-
- HexFormat = RequireBraces | RequireHexPrefix, /* X */
- NumberFormat = None, /* N */
- DigitFormat = RequireDashes, /* D */
- BraceFormat = RequireBraces | RequireDashes, /* B */
- ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
-
- Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
+ private enum GuidStyles
+ {
+ None = 0x00000000,
+ AllowParenthesis = 0x00000001, //Allow the guid to be enclosed in parens
+ AllowBraces = 0x00000002, //Allow the guid to be enclosed in braces
+ AllowDashes = 0x00000004, //Allow the guid to contain dash group separators
+ AllowHexPrefix = 0x00000008, //Allow the guid to contain {0xdd,0xdd}
+ RequireParenthesis = 0x00000010, //Require the guid to be enclosed in parens
+ RequireBraces = 0x00000020, //Require the guid to be enclosed in braces
+ RequireDashes = 0x00000040, //Require the guid to contain dash group separators
+ RequireHexPrefix = 0x00000080, //Require the guid to contain {0xdd,0xdd}
+
+ HexFormat = RequireBraces | RequireHexPrefix, /* X */
+ NumberFormat = None, /* N */
+ DigitFormat = RequireDashes, /* D */
+ BraceFormat = RequireBraces | RequireDashes, /* B */
+ ParenthesisFormat = RequireParenthesis | RequireDashes, /* P */
+
+ Any = AllowParenthesis | AllowBraces | AllowDashes | AllowHexPrefix,
}
- private enum GuidParseThrowStyle {
- None = 0,
- All = 1,
- AllButOverflow = 2
+ private enum GuidParseThrowStyle
+ {
+ None = 0,
+ All = 1,
+ AllButOverflow = 2
}
- private enum ParseFailureKind {
- None = 0,
- ArgumentNull = 1,
- Format = 2,
- FormatWithParameter = 3,
- NativeException = 4,
+ private enum ParseFailureKind
+ {
+ None = 0,
+ ArgumentNull = 1,
+ Format = 2,
+ FormatWithParameter = 3,
+ NativeException = 4,
FormatWithInnerException = 5
}
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
- private struct GuidResult {
+ private struct GuidResult
+ {
internal Guid parsedGuid;
internal GuidParseThrowStyle throwStyle;
@@ -169,53 +174,61 @@ namespace System {
internal string m_failureArgumentName;
internal Exception m_innerException;
- internal void Init(GuidParseThrowStyle canThrow) {
+ internal void Init(GuidParseThrowStyle canThrow)
+ {
parsedGuid = Guid.Empty;
- throwStyle = canThrow;
+ throwStyle = canThrow;
}
- internal void SetFailure(Exception nativeException) {
+ internal void SetFailure(Exception nativeException)
+ {
m_failure = ParseFailureKind.NativeException;
m_innerException = nativeException;
}
- internal void SetFailure(ParseFailureKind failure, string failureMessageID) {
+ internal void SetFailure(ParseFailureKind failure, string failureMessageID)
+ {
SetFailure(failure, failureMessageID, null, null, null);
}
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) {
+ 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) {
+ 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) {
+ if (throwStyle != GuidParseThrowStyle.None)
+ {
throw GetGuidParseException();
}
}
- internal Exception GetGuidParseException() {
- switch (m_failure) {
- case ParseFailureKind.ArgumentNull:
- return new ArgumentNullException(m_failureArgumentName, Environment.GetResourceString(m_failureMessageID));
+ internal Exception GetGuidParseException()
+ {
+ switch (m_failure)
+ {
+ case ParseFailureKind.ArgumentNull:
+ return new ArgumentNullException(m_failureArgumentName, SR.GetResourceString(m_failureMessageID));
- case ParseFailureKind.FormatWithInnerException:
- return new FormatException(Environment.GetResourceString(m_failureMessageID), m_innerException);
+ case ParseFailureKind.FormatWithInnerException:
+ return new FormatException(SR.GetResourceString(m_failureMessageID), m_innerException);
- case ParseFailureKind.FormatWithParameter:
- return new FormatException(Environment.GetResourceString(m_failureMessageID, m_failureMessageFormatArgument));
+ case ParseFailureKind.FormatWithParameter:
+ return new FormatException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
- case ParseFailureKind.Format:
- return new FormatException(Environment.GetResourceString(m_failureMessageID));
+ case ParseFailureKind.Format:
+ return new FormatException(SR.GetResourceString(m_failureMessageID));
- case ParseFailureKind.NativeException:
- return m_innerException;
+ case ParseFailureKind.NativeException:
+ return m_innerException;
- default:
- Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
- return new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"));
+ default:
+ Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
+ return new FormatException(SR.Format_GuidUnrecognized);
}
}
}
@@ -230,7 +243,8 @@ namespace System {
//
public Guid(String g)
{
- if (g==null) {
+ if (g == null)
+ {
throw new ArgumentNullException(nameof(g));
}
Contract.EndContractBlock();
@@ -238,10 +252,12 @@ namespace System {
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
- if (TryParseGuid(g, GuidStyles.Any, ref result)) {
+ if (TryParseGuid(g, GuidStyles.Any, ref result))
+ {
this = result.parsedGuid;
}
- else {
+ else
+ {
throw result.GetGuidParseException();
}
}
@@ -249,17 +265,20 @@ namespace System {
public static Guid Parse(String input)
{
- if (input == null) {
+ if (input == null)
+ {
throw new ArgumentNullException(nameof(input));
}
Contract.EndContractBlock();
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
- if (TryParseGuid(input, GuidStyles.Any, ref result)) {
+ if (TryParseGuid(input, GuidStyles.Any, ref result))
+ {
return result.parsedGuid;
}
- else {
+ else
+ {
throw result.GetGuidParseException();
}
}
@@ -268,11 +287,13 @@ namespace System {
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
- if (TryParseGuid(input, GuidStyles.Any, ref parseResult)) {
+ if (TryParseGuid(input, GuidStyles.Any, ref parseResult))
+ {
result = parseResult.parsedGuid;
return true;
}
- else {
+ else
+ {
result = Guid.Empty;
return false;
}
@@ -286,45 +307,55 @@ namespace System {
if (format == null)
throw new ArgumentNullException(nameof(format));
- if( format.Length != 1) {
+ if (format.Length != 1)
+ {
// all acceptable format strings are of length 1
- throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidStyles style;
char formatCh = format[0];
- if (formatCh == 'D' || formatCh == 'd') {
+ if (formatCh == 'D' || formatCh == 'd')
+ {
style = GuidStyles.DigitFormat;
- }
- else if (formatCh == 'N' || formatCh == 'n') {
+ }
+ else if (formatCh == 'N' || formatCh == 'n')
+ {
style = GuidStyles.NumberFormat;
}
- else if (formatCh == 'B' || formatCh == 'b') {
+ else if (formatCh == 'B' || formatCh == 'b')
+ {
style = GuidStyles.BraceFormat;
}
- else if (formatCh == 'P' || formatCh == 'p') {
+ else if (formatCh == 'P' || formatCh == 'p')
+ {
style = GuidStyles.ParenthesisFormat;
}
- else if (formatCh == 'X' || formatCh == 'x') {
+ else if (formatCh == 'X' || formatCh == 'x')
+ {
style = GuidStyles.HexFormat;
}
- else {
- throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
+ else
+ {
+ throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.AllButOverflow);
- if (TryParseGuid(input, style, ref result)) {
+ if (TryParseGuid(input, style, ref result))
+ {
return result.parsedGuid;
}
- else {
+ else
+ {
throw result.GetGuidParseException();
}
}
public static bool TryParseExact(String input, String format, out Guid result)
{
- if (format == null || format.Length != 1) {
+ if (format == null || format.Length != 1)
+ {
result = Guid.Empty;
return false;
}
@@ -332,22 +363,28 @@ namespace System {
GuidStyles style;
char formatCh = format[0];
- if (formatCh == 'D' || formatCh == 'd') {
+ if (formatCh == 'D' || formatCh == 'd')
+ {
style = GuidStyles.DigitFormat;
- }
- else if (formatCh == 'N' || formatCh == 'n') {
+ }
+ else if (formatCh == 'N' || formatCh == 'n')
+ {
style = GuidStyles.NumberFormat;
}
- else if (formatCh == 'B' || formatCh == 'b') {
+ else if (formatCh == 'B' || formatCh == 'b')
+ {
style = GuidStyles.BraceFormat;
}
- else if (formatCh == 'P' || formatCh == 'p') {
+ else if (formatCh == 'P' || formatCh == 'p')
+ {
style = GuidStyles.ParenthesisFormat;
}
- else if (formatCh == 'X' || formatCh == 'x') {
+ else if (formatCh == 'X' || formatCh == 'x')
+ {
style = GuidStyles.HexFormat;
}
- else {
+ else
+ {
// invalid guid format specification
result = Guid.Empty;
return false;
@@ -355,11 +392,13 @@ namespace System {
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
- if (TryParseGuid(input, style, ref parseResult)) {
+ if (TryParseGuid(input, style, ref parseResult))
+ {
result = parseResult.parsedGuid;
return true;
}
- else {
+ else
+ {
result = Guid.Empty;
return false;
}
@@ -368,13 +407,15 @@ namespace System {
private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result)
{
- if (g == null) {
+ if (g == null)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
String guidString = g.Trim(); //Remove Whitespace
- if (guidString.Length == 0) {
+ if (guidString.Length == 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
@@ -382,15 +423,19 @@ namespace System {
// Check for dashes
bool dashesExistInString = (guidString.IndexOf('-', 0) >= 0);
- if (dashesExistInString) {
- if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0) {
+ if (dashesExistInString)
+ {
+ if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0)
+ {
// dashes are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
- else {
- if ((flags & GuidStyles.RequireDashes) != 0) {
+ else
+ {
+ if ((flags & GuidStyles.RequireDashes) != 0)
+ {
// dashes are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
@@ -400,15 +445,19 @@ namespace System {
// Check for braces
bool bracesExistInString = (guidString.IndexOf('{', 0) >= 0);
- if (bracesExistInString) {
- if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0) {
+ if (bracesExistInString)
+ {
+ if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0)
+ {
// braces are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
- else {
- if ((flags & GuidStyles.RequireBraces) != 0) {
+ else
+ {
+ if ((flags & GuidStyles.RequireBraces) != 0)
+ {
// braces are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
@@ -417,50 +466,61 @@ namespace System {
// Check for parenthesis
bool parenthesisExistInString = (guidString.IndexOf('(', 0) >= 0);
-
- if (parenthesisExistInString) {
- if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0) {
+
+ if (parenthesisExistInString)
+ {
+ if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0)
+ {
// parenthesis are not allowed
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
- else {
- if ((flags & GuidStyles.RequireParenthesis) != 0) {
+ else
+ {
+ if ((flags & GuidStyles.RequireParenthesis) != 0)
+ {
// parenthesis are required
result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
return false;
}
}
- try {
+ try
+ {
// let's get on with the parsing
- if (dashesExistInString) {
+ if (dashesExistInString)
+ {
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
return TryParseGuidWithDashes(guidString, ref result);
}
- else if (bracesExistInString) {
+ else if (bracesExistInString)
+ {
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
return TryParseGuidWithHexPrefix(guidString, ref result);
}
- else {
+ else
+ {
// Check if it's of the form dddddddddddddddddddddddddddddddd
return TryParseGuidWithNoStyle(guidString, ref result);
}
}
- catch(IndexOutOfRangeException ex) {
+ catch (IndexOutOfRangeException ex)
+ {
result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
return false;
}
- catch (ArgumentException ex) {
+ catch (ArgumentException ex)
+ {
result.SetFailure(ParseFailureKind.FormatWithInnerException, "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;
@@ -468,13 +528,15 @@ 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");
return false;
}
// Check for '0x'
- if(!IsHexPrefix(guidString, 1)) {
+ if (!IsHexPrefix(guidString, 1))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}");
return false;
}
@@ -482,7 +544,8 @@ namespace System {
// Find the end of this hex number (since it is not fixed length)
numStart = 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
- if(numLen <= 0) {
+ if (numLen <= 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
@@ -492,14 +555,16 @@ namespace System {
return false;
// Check for '0x'
- if(!IsHexPrefix(guidString, numStart+numLen+1)) {
+ if (!IsHexPrefix(guidString, numStart + numLen + 1))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
- if(numLen <= 0) {
+ if (numLen <= 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
@@ -508,14 +573,16 @@ namespace System {
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)) {
+ if (!IsHexPrefix(guidString, numStart + numLen + 1))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
numStart = numStart + numLen + 3;
numLen = guidString.IndexOf(',', numStart) - numStart;
- if(numLen <= 0) {
+ if (numLen <= 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
}
@@ -523,9 +590,10 @@ namespace System {
// Read in the number
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] != '{') {
+ if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
return false;
}
@@ -534,10 +602,11 @@ namespace System {
numLen++;
byte[] bytes = new byte[8];
- for(int i = 0; i < 8; i++)
+ for (int i = 0; i < 8; i++)
{
// Check for '0x'
- if(!IsHexPrefix(guidString, numStart+numLen+1)) {
+ if (!IsHexPrefix(guidString, numStart + numLen + 1))
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}");
return false;
}
@@ -546,33 +615,37 @@ namespace System {
numStart = numStart + numLen + 3;
// Calculate number length
- if(i < 7) // first 7 cases
+ if (i < 7) // first 7 cases
{
numLen = guidString.IndexOf(',', numStart) - numStart;
- if(numLen <= 0) {
+ if (numLen <= 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
return false;
- }
+ }
}
else // last case ends with '}', not ','
{
numLen = guidString.IndexOf('}', numStart) - numStart;
- if(numLen <= 0) {
+ if (numLen <= 0)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber");
return false;
- }
+ }
}
// Read in the number
int signedNumber;
- if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result)) {
+ if (!StringToInt(guidString.Substring(numStart, numLen), -1, ParseNumbers.IsTight, out signedNumber, ref result))
+ {
return false;
}
uint number = (uint)signedNumber;
// check for overflow
- if(number > 255) {
- result.SetFailure(ParseFailureKind.Format, "Overflow_Byte");
+ if (number > 255)
+ {
+ result.SetFailure(ParseFailureKind.Format, "Overflow_Byte");
return false;
}
bytes[i] = (byte)number;
@@ -588,40 +661,48 @@ namespace System {
result.parsedGuid._k = bytes[7];
// Check for last '}'
- if(numStart+numLen+1 >= guidString.Length || guidString[numStart+numLen+1] != '}') {
+ if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace");
return false;
}
// Check if we have extra characters at the end
- if( numStart+numLen+1 != guidString.Length -1) {
+ if (numStart + numLen + 1 != guidString.Length - 1)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd");
return false;
}
-
+
return true;
}
-
+
// Check if it's of the form dddddddddddddddddddddddddddddddd
- private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result) {
- int startPos=0;
+ private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result)
+ {
+ int startPos = 0;
int temp;
long templ;
int currentPos = 0;
- if(guidString.Length != 32) {
+ if (guidString.Length != 32)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
- for(int i= 0; i< guidString.Length; i++) {
+ for (int i = 0; i < guidString.Length; i++)
+ {
char ch = guidString[i];
- if(ch >= '0' && ch <= '9') {
+ if (ch >= '0' && ch <= '9')
+ {
continue;
}
- else {
+ else
+ {
char upperCaseCh = Char.ToUpper(ch, CultureInfo.InvariantCulture);
- if(upperCaseCh >= 'A' && upperCaseCh <= 'F') {
+ if (upperCaseCh >= 'A' && upperCaseCh <= 'F')
+ {
continue;
}
}
@@ -651,20 +732,21 @@ namespace System {
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
- if (currentPos - startPos!=12) {
+ if (currentPos - startPos != 12)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
- result.parsedGuid._d = (byte)(temp>>8);
+ result.parsedGuid._d = (byte)(temp >> 8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
- result.parsedGuid._f = (byte)(temp>>8);
+ 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._h = (byte)(temp >> 24);
+ result.parsedGuid._i = (byte)(temp >> 16);
+ result.parsedGuid._j = (byte)(temp >> 8);
result.parsedGuid._k = (byte)(temp);
return true;
@@ -672,36 +754,43 @@ namespace System {
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
- private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result) {
- int startPos=0;
+ private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result)
+ {
+ int startPos = 0;
int temp;
long templ;
int currentPos = 0;
// check to see that it's the proper length
- if (guidString[0]=='{') {
- if (guidString.Length!=38 || guidString[37]!='}') {
+ if (guidString[0] == '{')
+ {
+ if (guidString.Length != 38 || guidString[37] != '}')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
- startPos=1;
+ startPos = 1;
}
- else if (guidString[0]=='(') {
- if (guidString.Length!=38 || guidString[37]!=')') {
+ else if (guidString[0] == '(')
+ {
+ if (guidString.Length != 38 || guidString[37] != ')')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
- startPos=1;
+ startPos = 1;
}
- else if(guidString.Length != 36) {
+ else if (guidString.Length != 36)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
- if (guidString[8+startPos] != '-' ||
- guidString[13+startPos] != '-' ||
- guidString[18+startPos] != '-' ||
- guidString[23+startPos] != '-') {
+ if (guidString[8 + startPos] != '-' ||
+ guidString[13 + startPos] != '-' ||
+ guidString[18 + startPos] != '-' ||
+ guidString[23 + startPos] != '-')
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes");
return false;
}
@@ -725,24 +814,25 @@ namespace System {
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
++currentPos; //Increment past the '-';
- startPos=currentPos;
+ startPos = currentPos;
if (!StringToLong(guidString, ref currentPos, ParseNumbers.NoSpace, out templ, ref result))
return false;
- if (currentPos - startPos != 12) {
+ if (currentPos - startPos != 12)
+ {
result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
return false;
}
- result.parsedGuid._d = (byte)(temp>>8);
+ result.parsedGuid._d = (byte)(temp >> 8);
result.parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
- result.parsedGuid._f = (byte)(temp>>8);
+ 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._h = (byte)(temp >> 24);
+ result.parsedGuid._i = (byte)(temp >> 16);
+ result.parsedGuid._j = (byte)(temp >> 8);
result.parsedGuid._k = (byte)(temp);
return true;
@@ -752,10 +842,12 @@ namespace System {
//
// 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 unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult)
+ {
return StringToShort(str, null, 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 unsafe bool StringToShort(String str, 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);
@@ -763,79 +855,103 @@ namespace System {
return retValue;
}
- private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
+ private static unsafe 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) {
+ 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);
}
}
- private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult) {
+ private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
+ {
result = 0;
int currStart = (parsePos == null) ? 0 : (*parsePos);
- try {
+ try
+ {
result = ParseNumbers.StringToInt(str, 16, flags, parsePos);
}
- catch (OverflowException ex) {
- if (parseResult.throwStyle == GuidParseThrowStyle.All) {
+ catch (OverflowException ex)
+ {
+ if (parseResult.throwStyle == GuidParseThrowStyle.All)
+ {
throw;
}
- else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) {
- throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex);
+ else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
+ {
+ throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
- else {
+ else
+ {
parseResult.SetFailure(ex);
return false;
}
}
- catch (Exception ex) {
- if (parseResult.throwStyle == GuidParseThrowStyle.None) {
+ catch (Exception ex)
+ {
+ if (parseResult.throwStyle == GuidParseThrowStyle.None)
+ {
parseResult.SetFailure(ex);
return false;
}
- else {
+ else
+ {
throw;
}
}
//If we didn't parse enough characters, there's clearly an error.
- if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength) {
+ if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength)
+ {
parseResult.SetFailure(ParseFailureKind.Format, "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) {
+ 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, int* parsePos, int flags, out long result, ref GuidResult parseResult)
+ {
result = 0;
- try {
+ try
+ {
result = ParseNumbers.StringToLong(str, 16, flags, parsePos);
}
- catch (OverflowException ex) {
- if (parseResult.throwStyle == GuidParseThrowStyle.All) {
+ catch (OverflowException ex)
+ {
+ if (parseResult.throwStyle == GuidParseThrowStyle.All)
+ {
throw;
}
- else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow) {
- throw new FormatException(Environment.GetResourceString("Format_GuidUnrecognized"), ex);
+ else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
+ {
+ throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
- else {
+ else
+ {
parseResult.SetFailure(ex);
return false;
}
}
- catch (Exception ex) {
- if (parseResult.throwStyle == GuidParseThrowStyle.None) {
+ catch (Exception ex)
+ {
+ if (parseResult.throwStyle == GuidParseThrowStyle.None)
+ {
parseResult.SetFailure(ex);
return false;
}
- else {
+ else
+ {
throw;
}
}
@@ -850,10 +966,10 @@ namespace System {
char curChar;
// Now get each char from str and if it is not whitespace add it to chArr
- for(int i = 0; i < str.Length; i++)
+ for (int i = 0; i < str.Length; i++)
{
curChar = str[i];
- if(!Char.IsWhiteSpace(curChar))
+ if (!Char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
@@ -865,7 +981,7 @@ namespace System {
private static bool IsHexPrefix(String str, int i)
{
- if(str.Length > i+1 && str[i] == '0' && (Char.ToLower(str[i+1], CultureInfo.InvariantCulture) == 'x'))
+ if (str.Length > i + 1 && str[i] == '0' && (Char.ToLower(str[i + 1], CultureInfo.InvariantCulture) == 'x'))
return true;
else
return false;
@@ -879,7 +995,7 @@ namespace System {
g[0] = (byte)(_a);
g[1] = (byte)(_a >> 8);
- g[2] = (byte)(_a >> 16);
+ g[2] = (byte)(_a >> 16);
g[3] = (byte)(_a >> 24);
g[4] = (byte)(_b);
g[5] = (byte)(_b >> 8);
@@ -901,14 +1017,14 @@ namespace System {
// Returns the guid in "registry" format.
public override String ToString()
{
- return ToString("D",null);
+ return ToString("D", null);
}
public unsafe override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
- fixed (int* ptr = &this._a)
- return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];
+ fixed (int* ptr = &_a)
+ return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];
}
// Returns true if and only if the guid represented
@@ -917,16 +1033,16 @@ namespace System {
{
Guid g;
// Check that o is a Guid first
- if(o == null || !(o is Guid))
+ if (o == null || !(o is Guid))
return false;
- else g = (Guid) o;
+ else g = (Guid)o;
// Now compare each of the elements
- if(g._a != _a)
+ if (g._a != _a)
return false;
- if(g._b != _b)
+ if (g._b != _b)
return false;
- if(g._c != _c)
+ if (g._c != _c)
return false;
if (g._d != _d)
return false;
@@ -951,11 +1067,11 @@ namespace System {
public bool Equals(Guid g)
{
// Now compare each of the elements
- if(g._a != _a)
+ if (g._a != _a)
return false;
- if(g._b != _b)
+ if (g._b != _b)
return false;
- if(g._c != _c)
+ if (g._c != _c)
return false;
if (g._d != _d)
return false;
@@ -977,64 +1093,80 @@ namespace System {
return true;
}
- private int GetResult(uint me, uint them) {
- if (me<them) {
+ private int GetResult(uint me, uint them)
+ {
+ if (me < them)
+ {
return -1;
}
return 1;
}
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (!(value is Guid)) {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeGuid"), nameof(value));
+ if (!(value is Guid))
+ {
+ throw new ArgumentException(SR.Arg_MustBeGuid, nameof(value));
}
Guid g = (Guid)value;
- if (g._a!=this._a) {
- return GetResult((uint)this._a, (uint)g._a);
+ if (g._a != _a)
+ {
+ return GetResult((uint)_a, (uint)g._a);
}
- if (g._b!=this._b) {
- return GetResult((uint)this._b, (uint)g._b);
+ if (g._b != _b)
+ {
+ return GetResult((uint)_b, (uint)g._b);
}
- if (g._c!=this._c) {
- return GetResult((uint)this._c, (uint)g._c);
+ if (g._c != _c)
+ {
+ return GetResult((uint)_c, (uint)g._c);
}
- if (g._d!=this._d) {
- return GetResult((uint)this._d, (uint)g._d);
+ if (g._d != _d)
+ {
+ return GetResult((uint)_d, (uint)g._d);
}
- if (g._e!=this._e) {
- return GetResult((uint)this._e, (uint)g._e);
+ if (g._e != _e)
+ {
+ return GetResult((uint)_e, (uint)g._e);
}
- if (g._f!=this._f) {
- return GetResult((uint)this._f, (uint)g._f);
+ if (g._f != _f)
+ {
+ return GetResult((uint)_f, (uint)g._f);
}
- if (g._g!=this._g) {
- return GetResult((uint)this._g, (uint)g._g);
+ if (g._g != _g)
+ {
+ return GetResult((uint)_g, (uint)g._g);
}
- if (g._h!=this._h) {
- return GetResult((uint)this._h, (uint)g._h);
+ if (g._h != _h)
+ {
+ return GetResult((uint)_h, (uint)g._h);
}
- if (g._i!=this._i) {
- return GetResult((uint)this._i, (uint)g._i);
+ if (g._i != _i)
+ {
+ return GetResult((uint)_i, (uint)g._i);
}
- if (g._j!=this._j) {
- return GetResult((uint)this._j, (uint)g._j);
+ if (g._j != _j)
+ {
+ return GetResult((uint)_j, (uint)g._j);
}
- if (g._k!=this._k) {
- return GetResult((uint)this._k, (uint)g._k);
+ if (g._k != _k)
+ {
+ return GetResult((uint)_k, (uint)g._k);
}
return 0;
@@ -1042,48 +1174,59 @@ namespace System {
public int CompareTo(Guid value)
{
- if (value._a!=this._a) {
- return GetResult((uint)this._a, (uint)value._a);
+ if (value._a != _a)
+ {
+ return GetResult((uint)_a, (uint)value._a);
}
- if (value._b!=this._b) {
- return GetResult((uint)this._b, (uint)value._b);
+ if (value._b != _b)
+ {
+ return GetResult((uint)_b, (uint)value._b);
}
- if (value._c!=this._c) {
- return GetResult((uint)this._c, (uint)value._c);
+ if (value._c != _c)
+ {
+ return GetResult((uint)_c, (uint)value._c);
}
- if (value._d!=this._d) {
- return GetResult((uint)this._d, (uint)value._d);
+ if (value._d != _d)
+ {
+ return GetResult((uint)_d, (uint)value._d);
}
- if (value._e!=this._e) {
- return GetResult((uint)this._e, (uint)value._e);
+ if (value._e != _e)
+ {
+ return GetResult((uint)_e, (uint)value._e);
}
- if (value._f!=this._f) {
- return GetResult((uint)this._f, (uint)value._f);
+ if (value._f != _f)
+ {
+ return GetResult((uint)_f, (uint)value._f);
}
- if (value._g!=this._g) {
- return GetResult((uint)this._g, (uint)value._g);
+ if (value._g != _g)
+ {
+ return GetResult((uint)_g, (uint)value._g);
}
- if (value._h!=this._h) {
- return GetResult((uint)this._h, (uint)value._h);
+ if (value._h != _h)
+ {
+ return GetResult((uint)_h, (uint)value._h);
}
- if (value._i!=this._i) {
- return GetResult((uint)this._i, (uint)value._i);
+ if (value._i != _i)
+ {
+ return GetResult((uint)_i, (uint)value._i);
}
- if (value._j!=this._j) {
- return GetResult((uint)this._j, (uint)value._j);
+ if (value._j != _j)
+ {
+ return GetResult((uint)_j, (uint)value._j);
}
- if (value._k!=this._k) {
- return GetResult((uint)this._k, (uint)value._k);
+ if (value._k != _k)
+ {
+ return GetResult((uint)_k, (uint)value._k);
}
return 0;
@@ -1092,27 +1235,27 @@ namespace System {
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
- if(a._a != b._a)
+ if (a._a != b._a)
return false;
- if(a._b != b._b)
+ if (a._b != b._b)
return false;
- if(a._c != b._c)
+ if (a._c != b._c)
return false;
- if(a._d != b._d)
+ if (a._d != b._d)
return false;
- if(a._e != b._e)
+ if (a._e != b._e)
return false;
- if(a._f != b._f)
+ if (a._f != b._f)
return false;
- if(a._g != b._g)
+ if (a._g != b._g)
return false;
- if(a._h != b._h)
+ if (a._h != b._h)
return false;
- if(a._i != b._i)
+ if (a._i != b._i)
return false;
- if(a._j != b._j)
+ if (a._j != b._j)
return false;
- if(a._k != b._k)
+ if (a._k != b._k)
return false;
return true;
@@ -1125,7 +1268,8 @@ namespace System {
// 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() {
+ 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.
@@ -1136,37 +1280,45 @@ namespace System {
return guid;
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
return ToString(format, null);
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
private static char HexToChar(int a)
{
a = a & 0xf;
- return (char) ((a > 9) ? a - 10 + 0x61 : a + 0x30);
+ return (char)((a > 9) ? a - 10 + 0x61 : a + 0x30);
}
- unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b)
+ unsafe private static int HexsToChars(char* guidChars, int a, int b)
{
- return HexsToChars(guidChars, offset, a, b, false);
+ guidChars[0] = HexToChar(a >> 4);
+ guidChars[1] = HexToChar(a);
+
+ guidChars[2] = HexToChar(b >> 4);
+ guidChars[3] = HexToChar(b);
+
+ return 4;
}
- unsafe private static int HexsToChars(char* guidChars, int offset, int a, int b, bool hex)
+ unsafe private static int HexsToCharsHexOutput(char* guidChars, int a, int b)
{
- if (hex) {
- guidChars[offset++] = '0';
- guidChars[offset++] = 'x';
- }
- guidChars[offset++] = HexToChar(a>>4);
- guidChars[offset++] = HexToChar(a);
- if (hex) {
- guidChars[offset++] = ',';
- guidChars[offset++] = '0';
- guidChars[offset++] = 'x';
- }
- guidChars[offset++] = HexToChar(b>>4);
- guidChars[offset++] = HexToChar(b);
- return offset;
+ guidChars[0] = '0';
+ guidChars[1] = 'x';
+
+ guidChars[2] = HexToChar(a >> 4);
+ guidChars[3] = HexToChar(a);
+
+ guidChars[4] = ',';
+ guidChars[5] = '0';
+ guidChars[6] = 'x';
+
+ guidChars[7] = HexToChar(b >> 4);
+ guidChars[8] = HexToChar(b);
+
+ return 9;
}
// IFormattable interface
@@ -1181,41 +1333,53 @@ namespace System {
bool dash = true;
bool hex = false;
- if( format.Length != 1) {
+ if (format.Length != 1)
+ {
// all acceptable format strings are of length 1
- throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
+ throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
-
+
char formatCh = format[0];
- if (formatCh == 'D' || formatCh == 'd') {
+ if (formatCh == 'D' || formatCh == 'd')
+ {
guidString = string.FastAllocateString(36);
- }
- else if (formatCh == 'N' || formatCh == 'n') {
+ }
+ else if (formatCh == 'N' || formatCh == 'n')
+ {
guidString = string.FastAllocateString(32);
dash = false;
}
- else if (formatCh == 'B' || formatCh == 'b') {
+ else if (formatCh == 'B' || formatCh == 'b')
+ {
guidString = string.FastAllocateString(38);
- unsafe {
- fixed (char* guidChars = guidString) {
+ unsafe
+ {
+ fixed (char* guidChars = guidString)
+ {
guidChars[offset++] = '{';
guidChars[37] = '}';
}
}
}
- else if (formatCh == 'P' || formatCh == 'p') {
+ else if (formatCh == 'P' || formatCh == 'p')
+ {
guidString = string.FastAllocateString(38);
- unsafe {
- fixed (char* guidChars = guidString) {
+ unsafe
+ {
+ fixed (char* guidChars = guidString)
+ {
guidChars[offset++] = '(';
guidChars[37] = ')';
}
}
}
- else if (formatCh == 'X' || formatCh == 'x') {
+ else if (formatCh == 'X' || formatCh == 'x')
+ {
guidString = string.FastAllocateString(68);
- unsafe {
- fixed (char* guidChars = guidString) {
+ unsafe
+ {
+ fixed (char* guidChars = guidString)
+ {
guidChars[offset++] = '{';
guidChars[67] = '}';
}
@@ -1223,51 +1387,56 @@ namespace System {
dash = false;
hex = true;
}
- else {
- throw new FormatException(Environment.GetResourceString("Format_InvalidGuidFormatSpecification"));
+ else
+ {
+ throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
}
- unsafe {
- fixed (char* guidChars = guidString) {
- if (hex) {
+ unsafe
+ {
+ fixed (char* guidChars = guidString)
+ {
+ 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);
+ 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);
+ offset += HexsToChars(guidChars + offset, _b >> 8, _b);
guidChars[offset++] = ',';
guidChars[offset++] = '0';
guidChars[offset++] = 'x';
- offset = HexsToChars(guidChars, offset, _c >> 8, _c);
+ offset += HexsToChars(guidChars + offset, _c >> 8, _c);
guidChars[offset++] = ',';
guidChars[offset++] = '{';
- offset = HexsToChars(guidChars, offset, _d, _e, true);
+ offset += HexsToCharsHexOutput(guidChars + offset, _d, _e);
guidChars[offset++] = ',';
- offset = HexsToChars(guidChars, offset, _f, _g, true);
+ offset += HexsToCharsHexOutput(guidChars + offset, _f, _g);
guidChars[offset++] = ',';
- offset = HexsToChars(guidChars, offset, _h, _i, true);
+ offset += HexsToCharsHexOutput(guidChars + offset, _h, _i);
guidChars[offset++] = ',';
- offset = HexsToChars(guidChars, offset, _j, _k, true);
+ offset += HexsToCharsHexOutput(guidChars + offset, _j, _k);
guidChars[offset++] = '}';
}
- else {
+ else
+ {
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
- offset = HexsToChars(guidChars, offset, _a >> 24, _a >> 16);
- offset = HexsToChars(guidChars, offset, _a >> 8, _a);
+ 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);
+ offset += HexsToChars(guidChars + offset, _b >> 8, _b);
if (dash) guidChars[offset++] = '-';
- offset = HexsToChars(guidChars, offset, _c >> 8, _c);
+ offset += HexsToChars(guidChars + offset, _c >> 8, _c);
if (dash) guidChars[offset++] = '-';
- offset = HexsToChars(guidChars, offset, _d, _e);
+ 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);
+ offset += HexsToChars(guidChars + offset, _f, _g);
+ offset += HexsToChars(guidChars + offset, _h, _i);
+ offset += HexsToChars(guidChars + offset, _j, _k);
}
}
}
diff --git a/src/mscorlib/src/System/HResults.cs b/src/mscorlib/src/System/HResults.cs
new file mode 100644
index 0000000000..fa0e24f00b
--- /dev/null
+++ b/src/mscorlib/src/System/HResults.cs
@@ -0,0 +1,236 @@
+// 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_LOADING_REFERENCE_ASSEMBLY = unchecked((int)0x80131058);
+ 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/IAppDomainPauseManager.cs b/src/mscorlib/src/System/IAppDomainPauseManager.cs
index cd3a9033de..8696e48664 100644
--- a/src/mscorlib/src/System/IAppDomainPauseManager.cs
+++ b/src/mscorlib/src/System/IAppDomainPauseManager.cs
@@ -11,15 +11,15 @@
**
=============================================================================*/
+using System;
+using System.Threading;
+using System.Security;
+using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
+using System.Runtime.CompilerServices;
+
namespace System
{
- using System;
- using System.Threading;
- using System.Security;
- using System.Diagnostics.Contracts;
- using System.Runtime.Versioning;
- using System.Runtime.CompilerServices;
-
internal class AppDomainPauseManager
{
public AppDomainPauseManager()
@@ -30,9 +30,9 @@ namespace System
static AppDomainPauseManager()
{
}
-
- static readonly AppDomainPauseManager instance = new AppDomainPauseManager();
-
+
+ private static readonly AppDomainPauseManager instance = new AppDomainPauseManager();
+
private static volatile bool isPaused;
internal static bool IsPaused
@@ -42,7 +42,7 @@ namespace System
internal static ManualResetEvent ResumeEvent
{
- get;
+ get;
set;
}
}
diff --git a/src/mscorlib/src/System/IAsyncResult.cs b/src/mscorlib/src/System/IAsyncResult.cs
deleted file mode 100644
index 0abeaca525..0000000000
--- a/src/mscorlib/src/System/IAsyncResult.cs
+++ /dev/null
@@ -1,30 +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.
-
-/*============================================================
-**
-** Interface: IAsyncResult
-**
-** Purpose: Interface to encapsulate the results of an async
-** operation
-**
-===========================================================*/
-
-using System;
-using System.Threading;
-
-namespace System
-{
- public interface IAsyncResult
- {
- bool IsCompleted { get; }
-
- WaitHandle AsyncWaitHandle { get; }
-
-
- Object AsyncState { get; }
-
- bool CompletedSynchronously { get; }
- }
-}
diff --git a/src/mscorlib/src/System/ICloneable.cs b/src/mscorlib/src/System/ICloneable.cs
deleted file mode 100644
index 49657c2765..0000000000
--- a/src/mscorlib/src/System/ICloneable.cs
+++ /dev/null
@@ -1,28 +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.
-
-/*============================================================
-**
-**
-** This interface is implemented by classes that support cloning.
-**
-===========================================================*/
-namespace System {
-
- using System;
- // Defines an interface indicating that an object may be cloned. Only objects
- // that implement ICloneable may be cloned. The interface defines a single
- // method which is called to create a clone of the object. Object defines a method
- // MemberwiseClone to support default clone operations.
- //
- public interface ICloneable
- {
- // Interface does not need to be marked with the serializable attribute
- // Make a new object which is a copy of the object instanced. This object may be either
- // deep copy or a shallow copy depending on the implementation of clone. The default
- // Object support for clone does a shallow copy.
- //
- Object Clone();
- }
-}
diff --git a/src/mscorlib/src/System/IComparable.cs b/src/mscorlib/src/System/IComparable.cs
deleted file mode 100644
index 72aeeb027c..0000000000
--- a/src/mscorlib/src/System/IComparable.cs
+++ /dev/null
@@ -1,37 +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.
-
-namespace System
-{
- // The IComparable interface is implemented by classes that support an
- // ordering of instances of the class. The ordering represented by
- // IComparable can be used to sort arrays and collections of objects
- // that implement the interface.
- //
- public interface IComparable
- {
- // Interface does not need to be marked with the serializable attribute
- // Compares this object to another object, returning an integer that
- // indicates the relationship. An implementation of this method must return
- // a value less than zero if this is less than object, zero
- // if this is equal to object, or a value greater than zero
- // if this is greater than object.
- //
- int CompareTo(Object obj);
- }
-
- // Generic version of IComparable.
-
- public interface IComparable<in T>
- {
- // Interface does not need to be marked with the serializable attribute
- // Compares this object to another object, returning an integer that
- // indicates the relationship. An implementation of this method must return
- // a value less than zero if this is less than object, zero
- // if this is equal to object, or a value greater than zero
- // if this is greater than object.
- //
- int CompareTo(T other);
- }
-}
diff --git a/src/mscorlib/src/System/IConvertible.cs b/src/mscorlib/src/System/IConvertible.cs
deleted file mode 100644
index 87351127f2..0000000000
--- a/src/mscorlib/src/System/IConvertible.cs
+++ /dev/null
@@ -1,63 +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.
-
-namespace System
-{
- // The IConvertible interface represents an object that contains a value. This
- // interface is implemented by the following types in the System namespace:
- // Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64,
- // Single, Double, Decimal, DateTime, and String. The interface may
- // be implemented by other types that are to be considered values. For example,
- // a library of nullable database types could implement IConvertible.
- //
- // Note: The interface was originally proposed as IValue.
- //
- // The implementations of IConvertible provided by the System.XXX value classes
- // simply forward to the appropriate Value.ToXXX(YYY) methods (a description of
- // the Value class follows below). In cases where a Value.ToXXX(YYY) method
- // does not exist (because the particular conversion is not supported), the
- // IConvertible implementation should simply throw an InvalidCastException.
-
- [CLSCompliant(false)]
- public interface IConvertible
- {
- // Returns the type code of this object. An implementation of this method
- // must not return TypeCode.Empty (which represents a null reference) or
- // TypeCode.Object (which represents an object that doesn't implement the
- // IConvertible interface). An implementation of this method should return
- // TypeCode.DBNull if the value of this object is a database null. For
- // example, a nullable integer type should return TypeCode.DBNull if the
- // value of the object is the database null. Otherwise, an implementation
- // of this method should return the TypeCode that best describes the
- // internal representation of the object.
-
- TypeCode GetTypeCode();
-
- // The ToXXX methods convert the value of the underlying object to the
- // given type. If a particular conversion is not supported, the
- // implementation must throw an InvalidCastException. If the value of the
- // underlying object is not within the range of the target type, the
- // implementation must throw an OverflowException. The
- // IFormatProvider will be used to get a NumberFormatInfo or similar
- // appropriate service object, and may safely be null.
-
- bool ToBoolean(IFormatProvider provider);
- char ToChar(IFormatProvider provider);
- sbyte ToSByte(IFormatProvider provider);
- byte ToByte(IFormatProvider provider);
- short ToInt16(IFormatProvider provider);
- ushort ToUInt16(IFormatProvider provider);
- int ToInt32(IFormatProvider provider);
- uint ToUInt32(IFormatProvider provider);
- long ToInt64(IFormatProvider provider);
- ulong ToUInt64(IFormatProvider provider);
- float ToSingle(IFormatProvider provider);
- double ToDouble(IFormatProvider provider);
- Decimal ToDecimal(IFormatProvider provider);
- DateTime ToDateTime(IFormatProvider provider);
- String ToString(IFormatProvider provider);
- Object ToType(Type conversionType, IFormatProvider provider);
- }
-}
-
diff --git a/src/mscorlib/src/System/ICustomFormatter.cs b/src/mscorlib/src/System/ICustomFormatter.cs
deleted file mode 100644
index 47340f3093..0000000000
--- a/src/mscorlib/src/System/ICustomFormatter.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.
-
-/*============================================================
-**
-** Interface: ICustomFormatter
-**
-**
-** Purpose: Marks a class as providing special formatting
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System
-{
- public interface ICustomFormatter
- {
- // Interface does not need to be marked with the serializable attribute
- String Format(String format, Object arg, IFormatProvider formatProvider);
- }
-}
diff --git a/src/mscorlib/src/System/IDisposable.cs b/src/mscorlib/src/System/IDisposable.cs
deleted file mode 100644
index 24f0740edc..0000000000
--- a/src/mscorlib/src/System/IDisposable.cs
+++ /dev/null
@@ -1,60 +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.
-
-/*============================================================
-**
-** Interface: IDisposable
-**
-**
-** Purpose: Interface for assisting with deterministic finalization.
-**
-**
-===========================================================*/
-
-namespace System
-{
- // IDisposable is an attempt at helping to solve problems with deterministic
- // finalization. The GC of course doesn't leave any way to deterministically
- // know when a finalizer will run. This forces classes that hold onto OS
- // resources or some sort of important state (such as a FileStream or a
- // network connection) to provide a Close or Dispose method so users can
- // run clean up code deterministically. We have formalized this into an
- // interface with one method. Classes may privately implement IDisposable and
- // provide a Close method instead, if that name is by far the expected name
- // for objects in that domain (ie, you don't Dispose of a FileStream, you Close
- // it).
- //
- // This interface could be theoretically used as a marker by a compiler to
- // ensure a disposable object has been cleaned up along all code paths if it's
- // been allocated in that method, though in practice any compiler that
- // draconian may tick off any number of people. Perhaps an external tool (like
- // like Purify or BoundsChecker) could do this. Instead, C# has added a using
- // clause, which will generate a try/finally statement where the resource
- // passed into the using clause will always have it's Dispose method called.
- // Syntax is using(FileStream fs = ...) { .. };
- //
- // Dispose should meet the following conditions:
- // 1) Be safely callable multiple times
- // 2) Release any resources associated with the instance
- // 3) Call the base class's Dispose method, if necessary
- // 4) Suppress finalization of this class to help the GC by reducing the
- // number of objects on the finalization queue.
- // 5) Dispose shouldn't generally throw exceptions, except for very serious
- // errors that are particularly unexpected. (ie, OutOfMemoryException)
- // Ideally, nothing should go wrong with your object by calling Dispose.
- //
- // If possible, a class should define a finalizer that calls Dispose.
- // However, in many situations, this is impractical. For instance, take the
- // classic example of a Stream and a StreamWriter (which has an internal
- // buffer of data to write to the Stream). If both objects are collected
- // before Close or Dispose has been called on either, then the GC may run the
- // finalizer for the Stream first, before the StreamWriter. At that point, any
- // data buffered by the StreamWriter cannot be written to the Stream. In this
- // case, it doesn't make much sense to provide a finalizer on the StreamWriter
- // since you cannot solve this problem correctly.
- public interface IDisposable
- {
- void Dispose();
- }
-}
diff --git a/src/mscorlib/src/System/IEquatable.cs b/src/mscorlib/src/System/IEquatable.cs
deleted file mode 100644
index 1264fdd57a..0000000000
--- a/src/mscorlib/src/System/IEquatable.cs
+++ /dev/null
@@ -1,14 +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;
-
-namespace System
-{
- public interface IEquatable<T>
- {
- bool Equals(T other);
- }
-}
-
diff --git a/src/mscorlib/src/System/IFormatProvider.cs b/src/mscorlib/src/System/IFormatProvider.cs
deleted file mode 100644
index 0c17354af3..0000000000
--- a/src/mscorlib/src/System/IFormatProvider.cs
+++ /dev/null
@@ -1,23 +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: Notes a class which knows how to return formatting information
-**
-**
-============================================================*/
-
-using System;
-
-namespace System
-{
- public interface IFormatProvider
- {
- // Interface does not need to be marked with the serializable attribute
- Object GetFormat(Type formatType);
- }
-}
diff --git a/src/mscorlib/src/System/IFormattable.cs b/src/mscorlib/src/System/IFormattable.cs
deleted file mode 100644
index 28a7d70571..0000000000
--- a/src/mscorlib/src/System/IFormattable.cs
+++ /dev/null
@@ -1,15 +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.Diagnostics.Contracts;
-
-namespace System
-{
- public interface IFormattable
- {
- [Pure]
- String ToString(String format, IFormatProvider formatProvider);
- }
-}
diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs
index d973860472..54358d601d 100644
--- a/src/mscorlib/src/System/IO/BinaryReader.cs
+++ b/src/mscorlib/src/System/IO/BinaryReader.cs
@@ -13,54 +13,60 @@
**
**
============================================================*/
-namespace System.IO {
- using System;
- using System.Runtime;
- using System.Text;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Security;
+using System;
+using System.Runtime;
+using System.Text;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Security;
+namespace System.IO
+{
public class BinaryReader : IDisposable
{
private const int MaxCharBytesSize = 128;
- private Stream m_stream;
- private byte[] m_buffer;
- private Decoder m_decoder;
- private byte[] m_charBytes;
- private char[] m_singleChar;
- private char[] m_charBuffer;
- private int m_maxCharsSize; // From MaxCharBytesSize & Encoding
+ private Stream m_stream;
+ private byte[] m_buffer;
+ private Decoder m_decoder;
+ private byte[] m_charBytes;
+ private char[] m_singleChar;
+ private char[] m_charBuffer;
+ private int m_maxCharsSize; // From MaxCharBytesSize & Encoding
// Performance optimization for Read() w/ Unicode. Speeds us up by ~40%
- private bool m_2BytesPerChar;
- private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
- private bool m_leaveOpen;
+ private bool m_2BytesPerChar;
+ private bool m_isMemoryStream; // "do we sit on MemoryStream?" for Read/ReadInt32 perf
+ private bool m_leaveOpen;
- public BinaryReader(Stream input) : this(input, Encoding.UTF8, false) {
+ public BinaryReader(Stream input) : this(input, Encoding.UTF8, false)
+ {
}
- public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false) {
+ public BinaryReader(Stream input, Encoding encoding) : this(input, encoding, false)
+ {
}
- public BinaryReader(Stream input, Encoding encoding, bool leaveOpen) {
- if (input==null) {
+ public BinaryReader(Stream input, Encoding encoding, bool leaveOpen)
+ {
+ if (input == null)
+ {
throw new ArgumentNullException(nameof(input));
}
- if (encoding==null) {
+ if (encoding == null)
+ {
throw new ArgumentNullException(nameof(encoding));
}
if (!input.CanRead)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
+ throw new ArgumentException(SR.Argument_StreamNotReadable);
Contract.EndContractBlock();
m_stream = input;
m_decoder = encoding.GetDecoder();
m_maxCharsSize = encoding.GetMaxCharCount(MaxCharBytesSize);
int minBufferSize = encoding.GetMaxByteCount(1); // max bytes per one char
- if (minBufferSize < 16)
+ if (minBufferSize < 16)
minBufferSize = 16;
m_buffer = new byte[minBufferSize];
// m_charBuffer and m_charBytes will be left null.
@@ -73,21 +79,26 @@ namespace System.IO {
m_isMemoryStream = (m_stream.GetType() == typeof(MemoryStream));
m_leaveOpen = leaveOpen;
- Debug.Assert(m_decoder!=null, "[BinaryReader.ctor]m_decoder!=null");
+ Debug.Assert(m_decoder != null, "[BinaryReader.ctor]m_decoder!=null");
}
- public virtual Stream BaseStream {
- get {
+ public virtual Stream BaseStream
+ {
+ get
+ {
return m_stream;
}
}
- public virtual void Close() {
+ public virtual void Close()
+ {
Dispose(true);
}
- protected virtual void Dispose(bool disposing) {
- if (disposing) {
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ {
Stream copyOfStream = m_stream;
m_stream = null;
if (copyOfStream != null && !m_leaveOpen)
@@ -106,10 +117,11 @@ namespace System.IO {
Dispose(true);
}
- public virtual int PeekChar() {
+ public virtual int PeekChar()
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
if (!m_stream.CanSeek)
return -1;
@@ -118,59 +130,70 @@ namespace System.IO {
m_stream.Position = origPos;
return ch;
}
-
- public virtual int Read() {
+
+ public virtual int Read()
+ {
Contract.Ensures(Contract.Result<int>() >= -1);
- if (m_stream==null) {
+ if (m_stream == null)
+ {
__Error.FileNotOpen();
}
return InternalReadOneChar();
}
- public virtual bool ReadBoolean(){
+ public virtual bool ReadBoolean()
+ {
FillBuffer(1);
- return (m_buffer[0]!=0);
+ return (m_buffer[0] != 0);
}
- public virtual byte ReadByte() {
+ public virtual byte ReadByte()
+ {
// Inlined to avoid some method call overhead with FillBuffer.
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
int b = m_stream.ReadByte();
if (b == -1)
__Error.EndOfFile();
- return (byte) b;
+ return (byte)b;
}
[CLSCompliant(false)]
- public virtual sbyte ReadSByte() {
+ public virtual sbyte ReadSByte()
+ {
FillBuffer(1);
return (sbyte)(m_buffer[0]);
}
- public virtual char ReadChar() {
+ public virtual char ReadChar()
+ {
int value = Read();
- if (value==-1) {
+ if (value == -1)
+ {
__Error.EndOfFile();
}
return (char)value;
}
- public virtual short ReadInt16() {
+ public virtual short ReadInt16()
+ {
FillBuffer(2);
return (short)(m_buffer[0] | m_buffer[1] << 8);
}
[CLSCompliant(false)]
- public virtual ushort ReadUInt16(){
+ public virtual ushort ReadUInt16()
+ {
FillBuffer(2);
return (ushort)(m_buffer[0] | m_buffer[1] << 8);
}
- public virtual int ReadInt32() {
- if (m_isMemoryStream) {
- if (m_stream==null) __Error.FileNotOpen();
+ public virtual int ReadInt32()
+ {
+ if (m_isMemoryStream)
+ {
+ if (m_stream == null) __Error.FileNotOpen();
// read directly from MemoryStream buffer
MemoryStream mStream = m_stream as MemoryStream;
Debug.Assert(mStream != null, "m_stream as MemoryStream != null");
@@ -185,22 +208,25 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public virtual uint ReadUInt32() {
+ public virtual uint ReadUInt32()
+ {
FillBuffer(4);
return (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
}
- public virtual long ReadInt64() {
+ public virtual long ReadInt64()
+ {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
uint hi = (uint)(m_buffer[4] | m_buffer[5] << 8 |
m_buffer[6] << 16 | m_buffer[7] << 24);
- return (long) ((ulong)hi) << 32 | lo;
+ return (long)((ulong)hi) << 32 | lo;
}
[CLSCompliant(false)]
- public virtual ulong ReadUInt64() {
+ public virtual ulong ReadUInt64()
+ {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
@@ -209,13 +235,15 @@ namespace System.IO {
return ((ulong)hi) << 32 | lo;
}
- public virtual unsafe float ReadSingle() {
+ public virtual unsafe float ReadSingle()
+ {
FillBuffer(4);
uint tmpBuffer = (uint)(m_buffer[0] | m_buffer[1] << 8 | m_buffer[2] << 16 | m_buffer[3] << 24);
return *((float*)&tmpBuffer);
}
- public virtual unsafe double ReadDouble() {
+ public virtual unsafe double ReadDouble()
+ {
FillBuffer(8);
uint lo = (uint)(m_buffer[0] | m_buffer[1] << 8 |
m_buffer[2] << 16 | m_buffer[3] << 24);
@@ -226,18 +254,22 @@ namespace System.IO {
return *((double*)&tmpBuffer);
}
- public virtual decimal ReadDecimal() {
+ public virtual decimal ReadDecimal()
+ {
FillBuffer(16);
- try {
+ try
+ {
return Decimal.ToDecimal(m_buffer);
}
- catch (ArgumentException e) {
+ catch (ArgumentException e)
+ {
// ReadDecimal cannot leak out ArgumentException
- throw new IOException(Environment.GetResourceString("Arg_DecBitCtor"), e);
+ throw new IOException(SR.Arg_DecBitCtor, e);
}
}
- public virtual String ReadString() {
+ public virtual String ReadString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
if (m_stream == null)
@@ -251,29 +283,34 @@ namespace System.IO {
// Length of the string in bytes, not chars
stringLength = Read7BitEncodedInt();
- if (stringLength<0) {
- throw new IOException(Environment.GetResourceString("IO.IO_InvalidStringLen_Len", stringLength));
+ if (stringLength < 0)
+ {
+ throw new IOException(SR.Format(SR.IO_InvalidStringLen_Len, stringLength));
}
- if (stringLength==0) {
+ if (stringLength == 0)
+ {
return String.Empty;
}
- if (m_charBytes==null) {
- m_charBytes = new byte[MaxCharBytesSize];
+ if (m_charBytes == null)
+ {
+ m_charBytes = new byte[MaxCharBytesSize];
}
-
- if (m_charBuffer == null) {
+
+ if (m_charBuffer == null)
+ {
m_charBuffer = new char[m_maxCharsSize];
}
-
- StringBuilder sb = null;
+
+ StringBuilder sb = null;
do
{
- readLength = ((stringLength - currPos)>MaxCharBytesSize)?MaxCharBytesSize:(stringLength - currPos);
+ readLength = ((stringLength - currPos) > MaxCharBytesSize) ? MaxCharBytesSize : (stringLength - currPos);
n = m_stream.Read(m_charBytes, 0, readLength);
- if (n==0) {
+ if (n == 0)
+ {
__Error.EndOfFile();
}
@@ -285,38 +322,43 @@ namespace System.IO {
if (sb == null)
sb = StringBuilderCache.Acquire(stringLength); // Actual string length in chars may be smaller.
sb.Append(m_charBuffer, 0, charsRead);
- currPos +=n;
-
- } while (currPos<stringLength);
+ currPos += n;
+ } while (currPos < stringLength);
return StringBuilderCache.GetStringAndRelease(sb);
}
- public virtual int Read(char[] buffer, int index, int count) {
- if (buffer==null) {
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public virtual int Read(char[] buffer, int index, int count)
+ {
+ if (buffer == null)
+ {
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
- if (index < 0) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (index < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (buffer.Length - index < count) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ if (buffer.Length - index < count)
+ {
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
- if (m_stream==null)
+ if (m_stream == null)
__Error.FileNotOpen();
// SafeCritical: index and count have already been verified to be a valid range for the buffer
return InternalReadChars(buffer, index, count);
}
- private int InternalReadChars(char[] buffer, int index, int count) {
+ private int InternalReadChars(char[] buffer, int index, int count)
+ {
Contract.Requires(buffer != null);
Contract.Requires(index >= 0 && count >= 0);
Debug.Assert(m_stream != null);
@@ -324,11 +366,13 @@ namespace System.IO {
int numBytes = 0;
int charsRemaining = count;
- if (m_charBytes==null) {
+ if (m_charBytes == null)
+ {
m_charBytes = new byte[MaxCharBytesSize];
}
- while (charsRemaining > 0) {
+ while (charsRemaining > 0)
+ {
int charsRead = 0;
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
@@ -337,7 +381,8 @@ namespace System.IO {
// special case for DecoderNLS subclasses when there is a hanging byte from the previous loop
DecoderNLS decoder = m_decoder as DecoderNLS;
- if (decoder != null && decoder.HasState && numBytes > 1) {
+ if (decoder != null && decoder.HasState && numBytes > 1)
+ {
numBytes -= 1;
}
@@ -360,10 +405,11 @@ namespace System.IO {
else
{
numBytes = m_stream.Read(m_charBytes, 0, numBytes);
- byteBuffer = m_charBytes;
+ byteBuffer = m_charBytes;
}
- if (numBytes == 0) {
+ if (numBytes == 0)
+ {
return (count - charsRemaining);
}
@@ -390,7 +436,7 @@ namespace System.IO {
}
charsRemaining -= charsRead;
- index+=charsRead;
+ index += charsRead;
}
// this should never fail
@@ -401,7 +447,8 @@ namespace System.IO {
return (count - charsRemaining);
}
- private int InternalReadOneChar() {
+ private int InternalReadOneChar()
+ {
// I know having a separate InternalReadOneChar method seems a little
// redundant, but this makes a scenario like the security parser code
// 20% faster, in addition to the optimizations for UnicodeEncoding I
@@ -409,18 +456,21 @@ namespace System.IO {
int charsRead = 0;
int numBytes = 0;
long posSav = posSav = 0;
-
+
if (m_stream.CanSeek)
posSav = m_stream.Position;
- if (m_charBytes==null) {
+ if (m_charBytes == null)
+ {
m_charBytes = new byte[MaxCharBytesSize];
}
- if (m_singleChar==null) {
+ if (m_singleChar == null)
+ {
m_singleChar = new char[1];
}
- while (charsRead == 0) {
+ while (charsRead == 0)
+ {
// We really want to know what the minimum number of bytes per char
// is for our encoding. Otherwise for UnicodeEncoding we'd have to
// do ~1+log(n) reads to read n characters.
@@ -428,25 +478,27 @@ namespace System.IO {
numBytes = m_2BytesPerChar ? 2 : 1;
int r = m_stream.ReadByte();
- m_charBytes[0] = (byte) r;
+ m_charBytes[0] = (byte)r;
if (r == -1)
numBytes = 0;
- if (numBytes == 2) {
+ if (numBytes == 2)
+ {
r = m_stream.ReadByte();
- m_charBytes[1] = (byte) r;
+ m_charBytes[1] = (byte)r;
if (r == -1)
numBytes = 1;
}
- if (numBytes==0) {
+ if (numBytes == 0)
+ {
// Console.WriteLine("Found no bytes. We're outta here.");
return -1;
}
Debug.Assert(numBytes == 1 || numBytes == 2, "BinaryReader::InternalReadOneChar assumes it's reading one or 2 bytes only.");
- try {
-
+ try
+ {
charsRead = m_decoder.GetChars(m_charBytes, 0, numBytes, m_singleChar, 0);
}
catch
@@ -468,65 +520,74 @@ namespace System.IO {
return m_singleChar[0];
}
- public virtual char[] ReadChars(int count) {
- if (count<0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public virtual char[] ReadChars(int count)
+ {
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.Ensures(Contract.Result<char[]>() != null);
Contract.Ensures(Contract.Result<char[]>().Length <= count);
Contract.EndContractBlock();
- if (m_stream == null) {
+ if (m_stream == null)
+ {
__Error.FileNotOpen();
}
- if (count == 0) {
- return EmptyArray<Char>.Value;
+ if (count == 0)
+ {
+ return Array.Empty<Char>();
}
// 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);
- if (n!=count) {
+ if (n != count)
+ {
char[] copy = new char[n];
- Buffer.InternalBlockCopy(chars, 0, copy, 0, 2*n); // sizeof(char)
+ Buffer.InternalBlockCopy(chars, 0, copy, 0, 2 * n); // sizeof(char)
chars = copy;
}
return chars;
}
- public virtual int Read(byte[] buffer, int index, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public virtual int Read(byte[] buffer, int index, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= count);
Contract.EndContractBlock();
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
return m_stream.Read(buffer, index, count);
}
- public virtual byte[] ReadBytes(int count) {
- if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public virtual byte[] ReadBytes(int count)
+ {
+ if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length <= Contract.OldValue(count));
Contract.EndContractBlock();
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
- if (count == 0) {
- return EmptyArray<Byte>.Value;
+ if (count == 0)
+ {
+ return Array.Empty<Byte>();
}
byte[] result = new byte[count];
int numRead = 0;
- do {
+ do
+ {
int n = m_stream.Read(result, numRead, count);
if (n == 0)
break;
@@ -534,7 +595,8 @@ namespace System.IO {
count -= n;
} while (count > 0);
- if (numRead != result.Length) {
+ if (numRead != result.Length)
+ {
// Trim array. This should happen on EOF & possibly net streams.
byte[] copy = new byte[numRead];
Buffer.InternalBlockCopy(result, 0, copy, 0, numRead);
@@ -544,46 +606,53 @@ namespace System.IO {
return result;
}
- protected virtual void FillBuffer(int numBytes) {
- if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length)) {
- throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer"));
+ protected virtual void FillBuffer(int numBytes)
+ {
+ if (m_buffer != null && (numBytes < 0 || numBytes > m_buffer.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_BinaryReaderFillBuffer);
}
- int bytesRead=0;
+ int bytesRead = 0;
int n = 0;
- if (m_stream==null) __Error.FileNotOpen();
+ if (m_stream == null) __Error.FileNotOpen();
// Need to find a good threshold for calling ReadByte() repeatedly
// vs. calling Read(byte[], int, int) for both buffered & unbuffered
// streams.
- if (numBytes==1) {
+ if (numBytes == 1)
+ {
n = m_stream.ReadByte();
- if (n==-1)
+ if (n == -1)
__Error.EndOfFile();
m_buffer[0] = (byte)n;
return;
}
- do {
- n = m_stream.Read(m_buffer, bytesRead, numBytes-bytesRead);
- if (n==0) {
+ do
+ {
+ n = m_stream.Read(m_buffer, bytesRead, numBytes - bytesRead);
+ if (n == 0)
+ {
__Error.EndOfFile();
}
- bytesRead+=n;
- } while (bytesRead<numBytes);
+ bytesRead += n;
+ } while (bytesRead < numBytes);
}
- internal protected int Read7BitEncodedInt() {
+ internal protected int Read7BitEncodedInt()
+ {
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
- do {
+ do
+ {
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
- throw new FormatException(Environment.GetResourceString("Format_Bad7BitInt32"));
+ throw new FormatException(SR.Format_Bad7BitInt32);
// ReadByte handles end of stream cases for us.
b = ReadByte();
diff --git a/src/mscorlib/src/System/IO/BinaryWriter.cs b/src/mscorlib/src/System/IO/BinaryWriter.cs
index b6c562534c..3d9839f46e 100644
--- a/src/mscorlib/src/System/IO/BinaryWriter.cs
+++ b/src/mscorlib/src/System/IO/BinaryWriter.cs
@@ -13,6 +13,7 @@
**
**
===========================================================*/
+
using System;
using System.Runtime;
using System.Runtime.Serialization;
@@ -20,7 +21,8 @@ using System.Text;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
// This abstract base class represents a writer that can write
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
@@ -29,7 +31,7 @@ namespace System.IO {
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
-
+
protected Stream OutStream;
private byte[] _buffer; // temp space for writing primitives to.
private Encoding _encoding;
@@ -42,7 +44,7 @@ namespace System.IO {
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// Size should be around the max number of chars/string * Encoding's max bytes/char
- private const int LargeByteBufferSize = 256;
+ private const int LargeByteBufferSize = 256;
// Protected default constructor that sets the output stream
// to a null stream (a bit bucket).
@@ -53,7 +55,7 @@ namespace System.IO {
_encoding = EncodingCache.UTF8NoBOM;
_encoder = _encoding.GetEncoder();
}
-
+
public BinaryWriter(Stream output) : this(output, EncodingCache.UTF8NoBOM, false)
{
}
@@ -64,21 +66,21 @@ namespace System.IO {
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
- if (output==null)
+ if (output == null)
throw new ArgumentNullException(nameof(output));
- if (encoding==null)
+ if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (!output.CanWrite)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
+ throw new ArgumentException(SR.Argument_StreamNotWritable);
Contract.EndContractBlock();
-
+
OutStream = output;
_buffer = new byte[16];
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_leaveOpen = leaveOpen;
}
-
+
// Closes this writer and releases any system resources associated with the
// writer. Following a call to Close, any operations on the writer
// may raise exceptions.
@@ -89,7 +91,8 @@ namespace System.IO {
protected virtual void Dispose(bool disposing)
{
- if (disposing) {
+ if (disposing)
+ {
if (_leaveOpen)
OutStream.Flush();
else
@@ -101,54 +104,57 @@ namespace System.IO {
{
Dispose(true);
}
-
+
/*
* Returns the stream associate with the writer. It flushes all pending
* writes before returning. All subclasses should override Flush to
* ensure that all buffered data is sent to the stream.
*/
- public virtual Stream BaseStream {
- get {
+ public virtual Stream BaseStream
+ {
+ get
+ {
Flush();
return OutStream;
}
}
-
+
// Clears all buffers for this writer and causes any buffered data to be
// written to the underlying device.
- public virtual void Flush()
+ public virtual void Flush()
{
OutStream.Flush();
}
-
+
public virtual long Seek(int offset, SeekOrigin origin)
{
return OutStream.Seek(offset, origin);
}
-
+
// Writes a boolean to this stream. A single byte is written to the stream
// with the value 0 representing false or the value 1 representing true.
//
- public virtual void Write(bool value) {
- _buffer[0] = (byte) (value ? 1 : 0);
+ public virtual void Write(bool value)
+ {
+ _buffer[0] = (byte)(value ? 1 : 0);
OutStream.Write(_buffer, 0, 1);
}
-
+
// Writes a byte to this stream. The current position of the stream is
// advanced by one.
//
- public virtual void Write(byte value)
+ public virtual void Write(byte value)
{
OutStream.WriteByte(value);
}
-
+
// Writes a signed byte to this stream. The current position of the stream
// is advanced by one.
//
[CLSCompliant(false)]
- public virtual void Write(sbyte value)
+ public virtual void Write(sbyte value)
{
- OutStream.WriteByte((byte) value);
+ OutStream.WriteByte((byte)value);
}
// Writes a byte array to this stream.
@@ -156,46 +162,50 @@ namespace System.IO {
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
- public virtual void Write(byte[] buffer) {
+ public virtual void Write(byte[] buffer)
+ {
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
Contract.EndContractBlock();
OutStream.Write(buffer, 0, buffer.Length);
}
-
+
// Writes a section of a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
- public virtual void Write(byte[] buffer, int index, int count) {
+ public virtual void Write(byte[] buffer, int index, int count)
+ {
OutStream.Write(buffer, index, count);
}
-
-
+
+
// Writes a character to this stream. The current position of the stream is
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
- public unsafe virtual void Write(char ch) {
+ public unsafe virtual void Write(char ch)
+ {
if (Char.IsSurrogate(ch))
- throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
+ throw new ArgumentException(SR.Arg_SurrogatesNotAllowedAsSingleChar);
Contract.EndContractBlock();
Debug.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
- fixed(byte * pBytes = &_buffer[0]) {
+ fixed (byte* pBytes = &_buffer[0])
+ {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, _buffer.Length, flush: true);
}
OutStream.Write(_buffer, 0, numBytes);
}
-
+
// Writes a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
- public virtual void Write(char[] chars)
+ public virtual void Write(char[] chars)
{
if (chars == null)
throw new ArgumentNullException(nameof(chars));
@@ -204,49 +214,49 @@ namespace System.IO {
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(bytes, 0, bytes.Length);
}
-
+
// Writes a section of a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
- public virtual void Write(char[] chars, int index, int count)
+ public virtual void Write(char[] chars, int index, int count)
{
byte[] bytes = _encoding.GetBytes(chars, index, count);
OutStream.Write(bytes, 0, bytes.Length);
}
-
-
+
+
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
public unsafe virtual void Write(double value)
{
- ulong TmpValue = *(ulong *)&value;
- _buffer[0] = (byte) TmpValue;
- _buffer[1] = (byte) (TmpValue >> 8);
- _buffer[2] = (byte) (TmpValue >> 16);
- _buffer[3] = (byte) (TmpValue >> 24);
- _buffer[4] = (byte) (TmpValue >> 32);
- _buffer[5] = (byte) (TmpValue >> 40);
- _buffer[6] = (byte) (TmpValue >> 48);
- _buffer[7] = (byte) (TmpValue >> 56);
+ ulong TmpValue = *(ulong*)&value;
+ _buffer[0] = (byte)TmpValue;
+ _buffer[1] = (byte)(TmpValue >> 8);
+ _buffer[2] = (byte)(TmpValue >> 16);
+ _buffer[3] = (byte)(TmpValue >> 24);
+ _buffer[4] = (byte)(TmpValue >> 32);
+ _buffer[5] = (byte)(TmpValue >> 40);
+ _buffer[6] = (byte)(TmpValue >> 48);
+ _buffer[7] = (byte)(TmpValue >> 56);
OutStream.Write(_buffer, 0, 8);
}
public virtual void Write(decimal value)
{
- Decimal.GetBytes(value,_buffer);
+ Decimal.GetBytes(value, _buffer);
OutStream.Write(_buffer, 0, 16);
}
-
+
// Writes a two-byte signed integer to this stream. The current position of
// the stream is advanced by two.
//
public virtual void Write(short value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
@@ -256,20 +266,20 @@ namespace System.IO {
[CLSCompliant(false)]
public virtual void Write(ushort value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
OutStream.Write(_buffer, 0, 2);
}
-
+
// Writes a four-byte signed integer to this stream. The current position
// of the stream is advanced by four.
//
public virtual void Write(int value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
@@ -279,26 +289,26 @@ namespace System.IO {
[CLSCompliant(false)]
public virtual void Write(uint value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
OutStream.Write(_buffer, 0, 4);
}
-
+
// Writes an eight-byte signed integer to this stream. The current position
// of the stream is advanced by eight.
//
public virtual void Write(long value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
- _buffer[4] = (byte) (value >> 32);
- _buffer[5] = (byte) (value >> 40);
- _buffer[6] = (byte) (value >> 48);
- _buffer[7] = (byte) (value >> 56);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
+ _buffer[4] = (byte)(value >> 32);
+ _buffer[5] = (byte)(value >> 40);
+ _buffer[6] = (byte)(value >> 48);
+ _buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
@@ -308,46 +318,47 @@ namespace System.IO {
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
- _buffer[0] = (byte) value;
- _buffer[1] = (byte) (value >> 8);
- _buffer[2] = (byte) (value >> 16);
- _buffer[3] = (byte) (value >> 24);
- _buffer[4] = (byte) (value >> 32);
- _buffer[5] = (byte) (value >> 40);
- _buffer[6] = (byte) (value >> 48);
- _buffer[7] = (byte) (value >> 56);
+ _buffer[0] = (byte)value;
+ _buffer[1] = (byte)(value >> 8);
+ _buffer[2] = (byte)(value >> 16);
+ _buffer[3] = (byte)(value >> 24);
+ _buffer[4] = (byte)(value >> 32);
+ _buffer[5] = (byte)(value >> 40);
+ _buffer[6] = (byte)(value >> 48);
+ _buffer[7] = (byte)(value >> 56);
OutStream.Write(_buffer, 0, 8);
}
-
+
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
public unsafe virtual void Write(float value)
{
- uint TmpValue = *(uint *)&value;
- _buffer[0] = (byte) TmpValue;
- _buffer[1] = (byte) (TmpValue >> 8);
- _buffer[2] = (byte) (TmpValue >> 16);
- _buffer[3] = (byte) (TmpValue >> 24);
+ uint TmpValue = *(uint*)&value;
+ _buffer[0] = (byte)TmpValue;
+ _buffer[1] = (byte)(TmpValue >> 8);
+ _buffer[2] = (byte)(TmpValue >> 16);
+ _buffer[3] = (byte)(TmpValue >> 24);
OutStream.Write(_buffer, 0, 4);
}
-
-
+
+
// Writes a length-prefixed string to this stream in the BinaryWriter's
// current Encoding. This method first writes the length of the string as
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
- public unsafe virtual void Write(String value)
+ public unsafe virtual void Write(String value)
{
- if (value==null)
+ if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
- if (_largeByteBuffer == null) {
+ if (_largeByteBuffer == null)
+ {
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = _largeByteBuffer.Length / _encoding.GetMaxByteCount(1);
}
@@ -358,7 +369,8 @@ namespace System.IO {
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
- else {
+ else
+ {
// Aggressively try to not allocate memory in this loop for
// runtime performance reasons. Use an Encoder to write out
// the string correctly (handling surrogates crossing buffer
@@ -368,7 +380,8 @@ namespace System.IO {
#if _DEBUG
int totalBytes = 0;
#endif
- while (numLeft > 0) {
+ while (numLeft > 0)
+ {
// Figure out how many chars to process this round.
int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
int byteLen;
@@ -389,7 +402,7 @@ namespace System.IO {
}
#if _DEBUG
totalBytes += byteLen;
- Debug.Assert (totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
+ Debug.Assert(totalBytes <= len && byteLen <= _largeByteBuffer.Length, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
@@ -400,13 +413,15 @@ namespace System.IO {
#endif
}
}
-
- protected void Write7BitEncodedInt(int value) {
+
+ protected void Write7BitEncodedInt(int value)
+ {
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
- uint v = (uint) value; // support negative numbers
- while (v >= 0x80) {
- Write((byte) (v | 0x80));
+ uint v = (uint)value; // support negative numbers
+ while (v >= 0x80)
+ {
+ Write((byte)(v | 0x80));
v >>= 7;
}
Write((byte)v);
diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs
index 88a669a971..6417207d38 100644
--- a/src/mscorlib/src/System/IO/Directory.cs
+++ b/src/mscorlib/src/System/IO/Directory.cs
@@ -25,8 +25,8 @@ using System.Diagnostics.Contracts;
namespace System.IO
{
- internal static class Directory {
-
+ internal static class Directory
+ {
// Private class that holds search data that is passed around
// in the heap based stack recursion
internal sealed class SearchData
@@ -55,7 +55,7 @@ namespace System.IO
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
- throw new ArgumentOutOfRangeException(nameof(searchOption), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
@@ -85,8 +85,9 @@ namespace System.IO
}
#endif // PLATFORM_UNIX
- internal static String InternalGetDirectoryRoot(String path) {
- if (path == null) return null;
+ internal static String InternalGetDirectoryRoot(String path)
+ {
+ if (path == null) return null;
return path.Substring(0, PathInternal.GetRootLength(path));
}
@@ -116,10 +117,10 @@ namespace System.IO
buffer.Length = (int)result;
-#if !PLATFORM_UNIX
+#if PLATFORM_WINDOWS
if (buffer.Contains('~'))
return Path.GetFullPath(buffer.ToString());
-#endif
+#endif // PLATFORM_WINDOWS
return buffer.ToString();
}
@@ -131,16 +132,17 @@ namespace System.IO
public static void SetCurrentDirectory(String path)
{
- if (path==null)
+ if (path == null)
throw new ArgumentNullException(nameof(path));
- if (path.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_PathEmpty"));
+ if (path.Length == 0)
+ throw new ArgumentException(SR.Argument_PathEmpty);
if (path.Length >= Path.MaxPath)
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
+ throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = Path.GetFullPath(path);
-
- if (!Win32Native.SetCurrentDirectory(fulldestDirName)) {
+
+ if (!Win32Native.SetCurrentDirectory(fulldestDirName))
+ {
// If path doesn't exist, this sets last error to 2 (File
// not Found). LEGACY: This may potentially have worked correctly
// on Win9x, maybe.
diff --git a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs b/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
deleted file mode 100644
index 21211a61e7..0000000000
--- a/src/mscorlib/src/System/IO/DirectoryNotFoundException.cs
+++ /dev/null
@@ -1,45 +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 accessing a path that doesn't exist.
-**
-**
-===========================================================*/
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO {
- /*
- * Thrown when trying to access a directory that doesn't exist on disk.
- * From COM Interop, this exception is thrown for 2 HRESULTS:
- * the Win32 errorcode-as-HRESULT ERROR_PATH_NOT_FOUND (0x80070003)
- * and STG_E_PATHNOTFOUND (0x80030003).
- */
- [Serializable]
- public class DirectoryNotFoundException : IOException {
- public DirectoryNotFoundException()
- : base(Environment.GetResourceString("Arg_DirectoryNotFoundException")) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
-
- public DirectoryNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
-
- public DirectoryNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
- }
-
- protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/DriveNotFoundException.cs b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
index f0245a8b28..27b6f9015d 100644
--- a/src/mscorlib/src/System/IO/DriveNotFoundException.cs
+++ b/src/mscorlib/src/System/IO/DriveNotFoundException.cs
@@ -10,25 +10,30 @@
//
//
//============================================================
+
using System;
using System.Runtime.Serialization;
-namespace System.IO {
-
+namespace System.IO
+{
//Thrown when trying to access a drive that is not availabe.
[Serializable]
- internal class DriveNotFoundException : IOException {
- public DriveNotFoundException()
- : base(Environment.GetResourceString("Arg_DriveNotFoundException")) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
+ internal class DriveNotFoundException : IOException
+ {
+ public DriveNotFoundException()
+ : base(SR.Arg_DriveNotFoundException)
+ {
+ HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
}
-
- public DriveNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
+
+ public DriveNotFoundException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
}
-
- protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
+
+ protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/IO/EndOfStreamException.cs b/src/mscorlib/src/System/IO/EndOfStreamException.cs
deleted file mode 100644
index 558c792a9e..0000000000
--- a/src/mscorlib/src/System/IO/EndOfStreamException.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: Exception to be thrown when reading past end-of-file.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO {
- [Serializable]
- public class EndOfStreamException : IOException
- {
- public EndOfStreamException()
- : base(Environment.GetResourceString("Arg_EndOfStreamException")) {
- SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
- }
-
- public EndOfStreamException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
- }
-
- public EndOfStreamException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
- }
-
- protected EndOfStreamException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs
index 7cc3f431a9..4aba1488ec 100644
--- a/src/mscorlib/src/System/IO/File.cs
+++ b/src/mscorlib/src/System/IO/File.cs
@@ -74,27 +74,30 @@ namespace System.IO
return false;
}
- internal static bool InternalExists(String path) {
+ internal static bool InternalExists(String path)
+ {
Win32Native.WIN32_FILE_ATTRIBUTE_DATA data = new Win32Native.WIN32_FILE_ATTRIBUTE_DATA();
int dataInitialised = FillAttributeInfo(path, ref data, false, true);
- return (dataInitialised == 0) && (data.fileAttributes != -1)
- && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
+ return (dataInitialised == 0) && (data.fileAttributes != -1)
+ && ((data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0);
}
public static byte[] ReadAllBytes(String path)
{
byte[] bytes;
- using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
- FileStream.DefaultBufferSize, FileOptions.None)) {
+ using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,
+ FileStream.DefaultBufferSize, FileOptions.None))
+ {
// Do a blocking read
int index = 0;
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
- throw new IOException(Environment.GetResourceString("IO.IO_FileTooLong2GB"));
- int count = (int) fileLength;
+ throw new IOException(SR.IO_FileTooLong2GB);
+ int count = (int)fileLength;
bytes = new byte[count];
- while(count > 0) {
+ while (count > 0)
+ {
int n = fs.Read(bytes, index, count);
if (n == 0)
__Error.EndOfFile();
@@ -111,7 +114,7 @@ namespace System.IO
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
+ throw new ArgumentException(SR.Argument_EmptyPath);
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
@@ -133,7 +136,7 @@ namespace System.IO
return lines.ToArray();
}
#endif // PLATFORM_UNIX
-
+
// Returns 0 on success, otherwise a Win32 error code. Note that
// classes should use -1 as the uninitialized state for dataInitialized.
internal static int FillAttributeInfo(String path, ref Win32Native.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound)
@@ -142,29 +145,33 @@ namespace System.IO
if (tryagain) // someone has a handle to the file open, or other error
{
Win32Native.WIN32_FIND_DATA findData;
- findData = new Win32Native.WIN32_FIND_DATA ();
-
+ findData = new Win32Native.WIN32_FIND_DATA();
+
// Remove trialing slash since this can cause grief to FindFirstFile. You will get an invalid argument error
- String tempPath = path.TrimEnd(new char [] {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar});
+ String tempPath = path.TrimEnd(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
// For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
+ try
+ {
bool error = false;
- SafeFindHandle handle = Win32Native.FindFirstFile(tempPath,findData);
- try {
- if (handle.IsInvalid) {
+ SafeFindHandle handle = Win32Native.FindFirstFile(tempPath, findData);
+ try
+ {
+ if (handle.IsInvalid)
+ {
error = true;
dataInitialised = Marshal.GetLastWin32Error();
-
+
if (dataInitialised == Win32Native.ERROR_FILE_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_PATH_NOT_FOUND ||
dataInitialised == Win32Native.ERROR_NOT_READY) // floppy device not ready
{
- if (!returnErrorOnNotFound) {
+ if (!returnErrorOnNotFound)
+ {
// Return default value for backward compatibility
dataInitialised = 0;
data.fileAttributes = -1;
@@ -173,21 +180,26 @@ namespace System.IO
return dataInitialised;
}
}
- finally {
+ finally
+ {
// Close the Win32 handle
- try {
+ try
+ {
handle.Close();
}
- catch {
+ catch
+ {
// if we're already returning an error, don't throw another one.
- if (!error) {
+ if (!error)
+ {
Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
__Error.WinIOError();
}
}
}
}
- finally {
+ finally
+ {
Win32Native.SetErrorMode(oldMode);
}
@@ -195,31 +207,36 @@ namespace System.IO
data.PopulateFrom(findData);
}
else
- {
- // For floppy drives, normally the OS will pop up a dialog saying
+ {
+ // For floppy drives, normally the OS will pop up a dialog saying
// there is no disk in drive A:, please insert one. We don't want that.
// SetErrorMode will let us disable this, but we should set the error
// mode back, since this may have wide-ranging effects.
bool success = false;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
- try {
+ try
+ {
success = Win32Native.GetFileAttributesEx(path, GetFileExInfoStandard, ref data);
}
- finally {
+ finally
+ {
Win32Native.SetErrorMode(oldMode);
}
- if (!success) {
+ if (!success)
+ {
dataInitialised = Marshal.GetLastWin32Error();
if (dataInitialised != Win32Native.ERROR_FILE_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_PATH_NOT_FOUND &&
dataInitialised != Win32Native.ERROR_NOT_READY) // floppy device not ready
{
- // In case someone latched onto the file. Take the perf hit only for failure
+ // In case someone latched onto the file. Take the perf hit only for failure
return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound);
}
- else {
- if (!returnErrorOnNotFound) {
+ else
+ {
+ if (!returnErrorOnNotFound)
+ {
// Return default value for backward compbatibility
dataInitialised = 0;
data.fileAttributes = -1;
diff --git a/src/mscorlib/src/System/IO/FileAccess.cs b/src/mscorlib/src/System/IO/FileAccess.cs
deleted file mode 100644
index 707b58f78b..0000000000
--- a/src/mscorlib/src/System/IO/FileAccess.cs
+++ /dev/null
@@ -1,41 +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.
-
-/*============================================================
-**
-** Enum: FileAccess
-**
-**
-**
-**
-** Purpose: Enum describing whether you want read and/or write
-** permission to a file.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Contains constants for specifying the access you want for a file.
- // You can have Read, Write or ReadWrite access.
- //
-[Serializable]
-[Flags]
- public enum FileAccess
- {
- // Specifies read access to the file. Data can be read from the file and
- // the file pointer can be moved. Combine with WRITE for read-write access.
- Read = 1,
-
- // Specifies write access to the file. Data can be written to the file and
- // the file pointer can be moved. Combine with READ for read-write access.
- Write = 2,
-
- // Specifies read and write access to the file. Data can be written to the
- // file and the file pointer can be moved. Data can also be read from the
- // file.
- ReadWrite = 3,
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
new file mode 100644
index 0000000000..f6415670e3
--- /dev/null
+++ b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
@@ -0,0 +1,43 @@
+// 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.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Security;
+
+namespace System.IO
+{
+ public partial class FileLoadException
+ {
+ // Do not delete: this is invoked from native code.
+ private FileLoadException(string fileName, string fusionLog, int hResult)
+ : base(null)
+ {
+ HResult = hResult;
+ FileName = fileName;
+ FusionLog = fusionLog;
+ _message = FormatFileLoadExceptionMessage(FileName, HResult);
+ }
+
+ internal static string FormatFileLoadExceptionMessage(string fileName, int hResult)
+ {
+ string format = null;
+ GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
+
+ string message = null;
+ GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
+
+ return string.Format(CultureInfo.CurrentCulture, format, fileName, message);
+ }
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
+ }
+}
diff --git a/src/mscorlib/src/System/IO/FileLoadException.cs b/src/mscorlib/src/System/IO/FileLoadException.cs
deleted file mode 100644
index 980d2514aa..0000000000
--- a/src/mscorlib/src/System/IO/FileLoadException.cs
+++ /dev/null
@@ -1,175 +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 failure to load a file that was successfully found.
-**
-**
-===========================================================*/
-
-using System;
-using System.Globalization;
-using System.Runtime.Serialization;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using System.Security;
-using System.Runtime.Versioning;
-using SecurityException = System.Security.SecurityException;
-
-namespace System.IO {
-
- [Serializable]
- public class FileLoadException : IOException {
-
- private String _fileName; // the name of the file we could not load.
- private String _fusionLog; // fusion log (when applicable)
-
- public FileLoadException()
- : base(Environment.GetResourceString("IO.FileLoad")) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- }
-
- public FileLoadException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- }
-
- public FileLoadException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- }
-
- public FileLoadException(String message, String fileName) : base(message)
- {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- _fileName = fileName;
- }
-
- public FileLoadException(String message, String fileName, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_FILELOAD);
- _fileName = fileName;
- }
-
- public override String Message
- {
- get {
- SetMessageField();
- return _message;
- }
- }
-
- private void SetMessageField()
- {
- if (_message == null)
- _message = FormatFileLoadExceptionMessage(_fileName, HResult);
- }
-
- public String FileName {
- get { return _fileName; }
- }
-
- public override String ToString()
- {
- String s = GetType().FullName + ": " + Message;
-
- if (_fileName != null && _fileName.Length != 0)
- s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
- if (InnerException != null)
- s = s + " ---> " + InnerException.ToString();
-
- if (StackTrace != null)
- s += Environment.NewLine + StackTrace;
-
- try
- {
- if(FusionLog!=null)
- {
- if (s==null)
- s=" ";
- s+=Environment.NewLine;
- s+=Environment.NewLine;
- s+=FusionLog;
- }
- }
- catch(SecurityException)
- {
-
- }
-
- return s;
- }
-
- protected FileLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
- // Base class constructor will check info != null.
-
- _fileName = info.GetString("FileLoad_FileName");
-
- try
- {
- _fusionLog = info.GetString("FileLoad_FusionLog");
- }
- catch
- {
- _fusionLog = null;
- }
- }
-
- private FileLoadException(String fileName, String fusionLog,int hResult)
- : base(null)
- {
- SetErrorCode(hResult);
- _fileName = fileName;
- _fusionLog=fusionLog;
- SetMessageField();
- }
-
- public String FusionLog {
- get { return _fusionLog; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- // Serialize data for our base classes. base will verify info != null.
- base.GetObjectData(info, context);
-
- // Serialize data for this class
- info.AddValue("FileLoad_FileName", _fileName, typeof(String));
-
- try
- {
- info.AddValue("FileLoad_FusionLog", FusionLog, typeof(String));
- }
- catch (SecurityException)
- {
- }
- }
-
- internal static String FormatFileLoadExceptionMessage(String fileName,
- int hResult)
- {
- string format = null;
- GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
-
- string message = null;
- GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
-
- return String.Format(CultureInfo.CurrentCulture, format, fileName, message);
- }
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileMode.cs b/src/mscorlib/src/System/IO/FileMode.cs
deleted file mode 100644
index 3972cf0533..0000000000
--- a/src/mscorlib/src/System/IO/FileMode.cs
+++ /dev/null
@@ -1,53 +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.
-
-/*============================================================
-**
-** Enum: FileMode
-**
-**
-**
-**
-** Purpose: Enum describing whether to create a new file or
-** open an existing one.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Contains constants for specifying how the OS should open a file.
- // These will control whether you overwrite a file, open an existing
- // file, or some combination thereof.
- //
- // To append to a file, use Append (which maps to OpenOrCreate then we seek
- // to the end of the file). To truncate a file or create it if it doesn't
- // exist, use Create.
- //
- [Serializable]
- public enum FileMode
- {
- // Creates a new file. An exception is raised if the file already exists.
- CreateNew = 1,
-
- // Creates a new file. If the file already exists, it is overwritten.
- Create = 2,
-
- // Opens an existing file. An exception is raised if the file does not exist.
- Open = 3,
-
- // Opens the file if it exists. Otherwise, creates a new file.
- OpenOrCreate = 4,
-
- // Opens an existing file. Once opened, the file is truncated so that its
- // size is zero bytes. The calling process must open the file with at least
- // WRITE access. An exception is raised if the file does not exist.
- Truncate = 5,
-
- // Opens the file if it exists and seeks to the end. Otherwise,
- // creates a new file.
- Append = 6,
- }
-}
diff --git a/src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs
new file mode 100644
index 0000000000..99645f0f2d
--- /dev/null
+++ b/src/mscorlib/src/System/IO/FileNotFoundException.CoreCLR.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.IO
+{
+ public partial class FileNotFoundException
+ {
+ // Do not delete: this is invoked from native code.
+ private FileNotFoundException(string fileName, string fusionLog, int hResult)
+ : base(null)
+ {
+ HResult = hResult;
+ FileName = fileName;
+ FusionLog = fusionLog;
+ SetMessageField();
+ }
+ }
+}
+
diff --git a/src/mscorlib/src/System/IO/FileNotFoundException.cs b/src/mscorlib/src/System/IO/FileNotFoundException.cs
deleted file mode 100644
index ad6b5386ba..0000000000
--- a/src/mscorlib/src/System/IO/FileNotFoundException.cs
+++ /dev/null
@@ -1,157 +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 accessing a file that doesn't exist.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-using SecurityException = System.Security.SecurityException;
-using System.Globalization;
-
-namespace System.IO {
- // Thrown when trying to access a file that doesn't exist on disk.
- [Serializable]
- public class FileNotFoundException : IOException {
-
- private String _fileName; // The name of the file that isn't found.
- private String _fusionLog; // fusion log (when applicable)
-
- public FileNotFoundException()
- : base(Environment.GetResourceString("IO.FileNotFound")) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- }
-
- public FileNotFoundException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- }
-
- public FileNotFoundException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- }
-
- public FileNotFoundException(String message, String fileName) : base(message)
- {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- _fileName = fileName;
- }
-
- public FileNotFoundException(String message, String fileName, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_FILENOTFOUND);
- _fileName = fileName;
- }
-
- public override String Message
- {
- get {
- SetMessageField();
- return _message;
- }
- }
-
- private void SetMessageField()
- {
- if (_message == null) {
- if ((_fileName == null) &&
- (HResult == System.__HResults.COR_E_EXCEPTION))
- _message = Environment.GetResourceString("IO.FileNotFound");
-
- else if( _fileName != null)
- _message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, HResult);
- }
- }
-
- public String FileName {
- get { return _fileName; }
- }
-
- public override String ToString()
- {
- String s = GetType().FullName + ": " + Message;
-
- if (_fileName != null && _fileName.Length != 0)
- s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
-
- if (InnerException != null)
- s = s + " ---> " + InnerException.ToString();
-
- if (StackTrace != null)
- s += Environment.NewLine + StackTrace;
-
- try
- {
- if(FusionLog!=null)
- {
- if (s==null)
- s=" ";
- s+=Environment.NewLine;
- s+=Environment.NewLine;
- s+=FusionLog;
- }
- }
- catch(SecurityException)
- {
-
- }
- return s;
-
- }
-
- protected FileNotFoundException(SerializationInfo info, StreamingContext context) : base (info, context) {
- // Base class constructor will check info != null.
-
- _fileName = info.GetString("FileNotFound_FileName");
- try
- {
- _fusionLog = info.GetString("FileNotFound_FusionLog");
- }
- catch
- {
- _fusionLog = null;
- }
- }
-
- private FileNotFoundException(String fileName, String fusionLog,int hResult)
- : base(null)
- {
- SetErrorCode(hResult);
- _fileName = fileName;
- _fusionLog=fusionLog;
- SetMessageField();
- }
-
- public String FusionLog {
- get { return _fusionLog; }
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- // Serialize data for our base classes. base will verify info != null.
- base.GetObjectData(info, context);
-
- // Serialize data for this class
- info.AddValue("FileNotFound_FileName", _fileName, typeof(String));
-
- try
- {
- info.AddValue("FileNotFound_FusionLog", FusionLog, typeof(String));
- }
- catch (SecurityException)
- {
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/IO/FileOptions.cs b/src/mscorlib/src/System/IO/FileOptions.cs
deleted file mode 100644
index 02bc99eea4..0000000000
--- a/src/mscorlib/src/System/IO/FileOptions.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.
-
-/*============================================================
-**
-** Enum: FileOptions
-**
-**
-**
-**
-** Purpose: Additional options to how to create a FileStream.
-** Exposes the more obscure CreateFile functionality.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace System.IO {
- // Maps to FILE_FLAG_DELETE_ON_CLOSE and similar values from winbase.h.
- // We didn't expose a number of these values because we didn't believe
- // a number of them made sense in managed code, at least not yet.
- [Serializable]
- [Flags]
- public enum FileOptions
- {
- // NOTE: any change to FileOptions enum needs to be
- // matched in the FileStream ctor for error validation
- None = 0,
- WriteThrough = unchecked((int)0x80000000),
- Asynchronous = unchecked((int)0x40000000), // FILE_FLAG_OVERLAPPED
- // NoBuffering = 0x20000000,
- RandomAccess = 0x10000000,
- DeleteOnClose = 0x04000000,
- SequentialScan = 0x08000000,
- // AllowPosix = 0x01000000, // FILE_FLAG_POSIX_SEMANTICS
- // BackupOrRestore,
- // DisallowReparsePoint = 0x00200000, // FILE_FLAG_OPEN_REPARSE_POINT
- // NoRemoteRecall = 0x00100000, // FILE_FLAG_OPEN_NO_RECALL
- // FirstPipeInstance = 0x00080000, // FILE_FLAG_FIRST_PIPE_INSTANCE
- Encrypted = 0x00004000, // FILE_ATTRIBUTE_ENCRYPTED
- }
-}
-
diff --git a/src/mscorlib/src/System/IO/FileShare.cs b/src/mscorlib/src/System/IO/FileShare.cs
deleted file mode 100644
index 8a7d1f05e9..0000000000
--- a/src/mscorlib/src/System/IO/FileShare.cs
+++ /dev/null
@@ -1,59 +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.
-
-/*============================================================
-**
-** Enum: FileShare
-**
-**
-**
-**
-** Purpose: Enum describing how to share files with other
-** processes - ie, whether two processes can simultaneously
-** read from the same file.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Contains constants for controlling file sharing options while
- // opening files. You can specify what access other processes trying
- // to open the same file concurrently can have.
- //
- // Note these values currently match the values for FILE_SHARE_READ,
- // FILE_SHARE_WRITE, and FILE_SHARE_DELETE in winnt.h
- //
-[Serializable]
-[Flags]
- public enum FileShare
- {
- // No sharing. Any request to open the file (by this process or another
- // process) will fail until the file is closed.
- None = 0,
-
- // Allows subsequent opening of the file for reading. If this flag is not
- // specified, any request to open the file for reading (by this process or
- // another process) will fail until the file is closed.
- Read = 1,
-
- // Allows subsequent opening of the file for writing. If this flag is not
- // specified, any request to open the file for writing (by this process or
- // another process) will fail until the file is closed.
- Write = 2,
-
- // Allows subsequent opening of the file for writing or reading. If this flag
- // is not specified, any request to open the file for writing or reading (by
- // this process or another process) will fail until the file is closed.
- ReadWrite = 3,
-
- // Open the file, but allow someone else to delete the file.
- Delete = 4,
-
- // Whether the file handle should be inheritable by child processes.
- // Note this is not directly supported like this by Win32.
- Inheritable = 0x10,
- }
-}
diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs
index ab612811b0..2628f7b652 100644
--- a/src/mscorlib/src/System/IO/IOException.cs
+++ b/src/mscorlib/src/System/IO/IOException.cs
@@ -16,8 +16,8 @@
using System;
using System.Runtime.Serialization;
-namespace System.IO {
-
+namespace System.IO
+{
[Serializable]
public class IOException : SystemException
{
@@ -32,36 +32,42 @@ namespace System.IO {
[NonSerialized]
private String _maybeFullPath; // For debuggers on partial trust code
- public IOException()
- : base(Environment.GetResourceString("Arg_IOException")) {
- SetErrorCode(__HResults.COR_E_IO);
+ public IOException()
+ : base(SR.Arg_IOException)
+ {
+ HResult = __HResults.COR_E_IO;
}
-
- public IOException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_IO);
+
+ public IOException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_IO;
}
- public IOException(String message, int hresult)
- : base(message) {
- SetErrorCode(hresult);
+ 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) {
- SetErrorCode(hresult);
+ internal IOException(String message, int hresult, String maybeFullPath)
+ : base(message)
+ {
+ HResult = hresult;
_maybeFullPath = maybeFullPath;
}
-
- public IOException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_IO);
+
+ public IOException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_IO;
}
- protected IOException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected IOException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs
index 05aac909b5..3d5668d774 100644
--- a/src/mscorlib/src/System/IO/MemoryStream.cs
+++ b/src/mscorlib/src/System/IO/MemoryStream.cs
@@ -24,7 +24,8 @@ using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
-namespace System.IO {
+namespace System.IO
+{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
@@ -54,17 +55,20 @@ namespace System.IO {
private const int MemStreamMaxLength = Int32.MaxValue;
- public MemoryStream()
- : this(0) {
+ public MemoryStream()
+ : this(0)
+ {
}
-
- public MemoryStream(int capacity) {
- if (capacity < 0) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
+
+ public MemoryStream(int capacity)
+ {
+ if (capacity < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
}
Contract.EndContractBlock();
- _buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value;
+ _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
@@ -72,13 +76,15 @@ namespace System.IO {
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
-
- public MemoryStream(byte[] buffer)
- : this(buffer, true) {
+
+ public MemoryStream(byte[] buffer)
+ : this(buffer, true)
+ {
}
-
- public MemoryStream(byte[] buffer, bool writable) {
- if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public MemoryStream(byte[] buffer, bool writable)
+ {
+ if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
@@ -87,26 +93,29 @@ namespace System.IO {
_origin = 0;
_isOpen = true;
}
-
- public MemoryStream(byte[] buffer, int index, int count)
- : this(buffer, index, count, true, false) {
+
+ public MemoryStream(byte[] buffer, int index, int count)
+ : this(buffer, index, count, true, false)
+ {
}
-
- public MemoryStream(byte[] buffer, int index, int count, bool writable)
- : this(buffer, index, count, writable, false) {
+
+ public MemoryStream(byte[] buffer, int index, int count, bool writable)
+ : this(buffer, index, count, writable, false)
+ {
}
-
- public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
-
+
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
@@ -115,30 +124,36 @@ namespace System.IO {
_expandable = false;
_isOpen = true;
}
-
- public override bool CanRead {
+
+ public override bool CanRead
+ {
[Pure]
get { return _isOpen; }
}
-
- public override bool CanSeek {
+
+ public override bool CanSeek
+ {
[Pure]
get { return _isOpen; }
}
-
- public override bool CanWrite {
+
+ public override bool CanWrite
+ {
[Pure]
get { return _writable; }
}
- private void EnsureWriteable() {
+ private void EnsureWriteable()
+ {
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
- try {
- if (disposing) {
+ try
+ {
+ if (disposing)
+ {
_isOpen = false;
_writable = false;
_expandable = false;
@@ -146,18 +161,21 @@ namespace System.IO {
_lastReadTask = null;
}
}
- finally {
+ finally
+ {
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
-
+
// returns a bool saying whether we allocated a new array.
- private bool EnsureCapacity(int value) {
+ private bool EnsureCapacity(int value)
+ {
// Check for overflow
if (value < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
- if (value > _capacity) {
+ throw new IOException(SR.IO_StreamTooLong);
+ if (value > _capacity)
+ {
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
@@ -169,53 +187,58 @@ namespace System.IO {
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
-
+
Capacity = newCapacity;
return true;
}
return false;
}
-
- public override void Flush() {
- }
- public override Task FlushAsync(CancellationToken cancellationToken) {
+ public override void Flush()
+ {
+ }
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
- try {
-
+ try
+ {
Flush();
return Task.CompletedTask;
-
- } catch(Exception ex) {
-
+ }
+ catch (Exception ex)
+ {
return Task.FromException(ex);
}
}
- public virtual byte[] GetBuffer() {
+ public virtual byte[] GetBuffer()
+ {
if (!_exposable)
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
+ throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
return _buffer;
}
- public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) {
- if (!_exposable) {
+ public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
+ {
+ if (!_exposable)
+ {
buffer = default(ArraySegment<byte>);
return false;
}
- buffer = new ArraySegment<byte>(_buffer, offset:_origin, count:(_length - _origin));
+ buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
- internal byte[] InternalGetBuffer() {
+ internal byte[] InternalGetBuffer()
+ {
return _buffer;
}
@@ -229,27 +252,30 @@ namespace System.IO {
}
// PERF: True cursor position, we don't need _origin for direct access
- internal int InternalGetPosition() {
+ internal int InternalGetPosition()
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
- internal int InternalReadInt32() {
- if (!_isOpen)
- __Error.StreamIsClosed();
+ internal int InternalReadInt32()
+ {
+ if (!_isOpen)
+ __Error.StreamIsClosed();
- int pos = (_position += 4); // use temp to avoid a race condition
- if (pos > _length)
- {
- _position = _length;
- __Error.EndOfFile();
- }
- return (int)(_buffer[pos-4] | _buffer[pos-3] << 8 | _buffer[pos-2] << 16 | _buffer[pos-1] << 24);
+ int pos = (_position += 4); // use temp to avoid a race condition
+ if (pos > _length)
+ {
+ _position = _length;
+ __Error.EndOfFile();
+ }
+ return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
- internal int InternalEmulateRead(int count) {
+ internal int InternalEmulateRead(int count)
+ {
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
@@ -260,20 +286,23 @@ namespace System.IO {
_position += n;
return n;
}
-
+
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
- public virtual int Capacity {
- get {
+ public virtual int Capacity
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
- set {
+ set
+ {
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
- if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
+ if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
@@ -281,55 +310,64 @@ namespace System.IO {
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
- if (_expandable && value != _capacity) {
- if (value > 0) {
+ if (_expandable && value != _capacity)
+ {
+ if (value > 0)
+ {
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
- else {
+ else
+ {
_buffer = null;
}
_capacity = value;
}
}
- }
+ }
- public override long Length {
- get {
+ public override long Length
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
- public override long Position {
- get {
+ public override long Position
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
- set {
+ set
+ {
if (value < 0)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
_position = _origin + (int)value;
}
}
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
@@ -356,25 +394,25 @@ namespace System.IO {
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
// If cancellation was requested, bail early
- if (cancellationToken.IsCancellationRequested)
+ if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
- Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
+ Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
@@ -389,9 +427,10 @@ namespace System.IO {
}
- public override int ReadByte() {
+ public override int ReadByte()
+ {
if (!_isOpen) __Error.StreamIsClosed();
-
+
if (_position >= _length) return -1;
return _buffer[_position++];
@@ -412,7 +451,7 @@ namespace System.IO {
base.CopyTo(destination, bufferSize);
return;
}
-
+
int originalPosition = _position;
// Seek to the end of the MemoryStream.
@@ -427,8 +466,8 @@ namespace System.IO {
}
}
- public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
-
+ public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
+ {
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
@@ -443,7 +482,7 @@ namespace System.IO {
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
-
+
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
@@ -453,56 +492,62 @@ namespace System.IO {
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
- if (memStrDest == null)
+ if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
-
- try {
+ try
+ {
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
-
- } catch(Exception ex) {
+ }
+ catch (Exception ex)
+ {
return Task.FromException(ex);
}
}
- public override long Seek(long offset, SeekOrigin loc) {
+ public override long Seek(long offset, SeekOrigin loc)
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
- switch(loc) {
- case SeekOrigin.Begin: {
- int tempPosition = unchecked(_origin + (int)offset);
- if (offset < 0 || tempPosition < _origin)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- _position = tempPosition;
- break;
- }
- case SeekOrigin.Current: {
- int tempPosition = unchecked(_position + (int)offset);
- if (unchecked(_position + offset) < _origin || tempPosition < _origin)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- _position = tempPosition;
- break;
- }
- case SeekOrigin.End: {
- int tempPosition = unchecked(_length + (int)offset);
- if ( unchecked(_length + offset) < _origin || tempPosition < _origin )
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- _position = tempPosition;
- break;
- }
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
+ switch (loc)
+ {
+ case SeekOrigin.Begin:
+ {
+ int tempPosition = unchecked(_origin + (int)offset);
+ if (offset < 0 || tempPosition < _origin)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ _position = tempPosition;
+ break;
+ }
+ case SeekOrigin.Current:
+ {
+ int tempPosition = unchecked(_position + (int)offset);
+ if (unchecked(_position + offset) < _origin || tempPosition < _origin)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ _position = tempPosition;
+ break;
+ }
+ case SeekOrigin.End:
+ {
+ int tempPosition = unchecked(_length + (int)offset);
+ if (unchecked(_length + offset) < _origin || tempPosition < _origin)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ _position = tempPosition;
+ break;
+ }
+ default:
+ throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
-
+
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
@@ -513,9 +558,11 @@ namespace System.IO {
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
- public override void SetLength(long value) {
- if (value < 0 || value > Int32.MaxValue) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ public override void SetLength(long value)
+ {
+ if (value < 0 || value > Int32.MaxValue)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
@@ -523,8 +570,9 @@ namespace System.IO {
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
- if (value > (Int32.MaxValue - _origin)) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ if (value > (Int32.MaxValue - _origin))
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
int newLength = _origin + (int)value;
@@ -533,25 +581,26 @@ namespace System.IO {
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
-
}
-
- public virtual byte[] ToArray() {
+
+ public virtual byte[] ToArray()
+ {
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
-
- public override void Write(byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
@@ -560,11 +609,13 @@ namespace System.IO {
int i = _position + count;
// Check for overflow
if (i < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
+ throw new IOException(SR.IO_StreamTooLong);
- if (i > _length) {
+ if (i > _length)
+ {
bool mustZero = _position > _length;
- if (i > _capacity) {
+ if (i > _capacity)
+ {
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
@@ -582,23 +633,22 @@ namespace System.IO {
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
-
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(...)
// If cancellation is already requested, bail early
- if (cancellationToken.IsCancellationRequested)
+ if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
@@ -616,14 +666,17 @@ namespace System.IO {
}
}
- public override void WriteByte(byte value) {
+ public override void WriteByte(byte value)
+ {
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
-
- if (_position >= _length) {
+
+ if (_position >= _length)
+ {
int newLength = _position + 1;
bool mustZero = _position > _length;
- if (newLength >= _capacity) {
+ if (newLength >= _capacity)
+ {
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
@@ -633,13 +686,13 @@ namespace System.IO {
_length = newLength;
}
_buffer[_position++] = value;
-
}
-
+
// Writes this MemoryStream to another stream.
- public virtual void WriteTo(Stream stream) {
- if (stream==null)
- throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
+ public virtual void WriteTo(Stream stream)
+ {
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
diff --git a/src/mscorlib/src/System/IO/PathTooLongException.cs b/src/mscorlib/src/System/IO/PathTooLongException.cs
deleted file mode 100644
index a84fdfbb36..0000000000
--- a/src/mscorlib/src/System/IO/PathTooLongException.cs
+++ /dev/null
@@ -1,43 +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 paths and/or filenames that are
-** too long.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO {
-
- [Serializable]
- public class PathTooLongException : IOException
- {
- public PathTooLongException()
- : base(Environment.GetResourceString("IO.PathTooLong")) {
- SetErrorCode(__HResults.COR_E_PATHTOOLONG);
- }
-
- public PathTooLongException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_PATHTOOLONG);
- }
-
- public PathTooLongException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_PATHTOOLONG);
- }
-
- protected PathTooLongException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
index 2cbd14f734..284cd927dc 100644
--- a/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/PinnedBufferMemoryStream.cs
@@ -13,19 +13,21 @@
**
**
===========================================================*/
+
using System;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
internal sealed unsafe class PinnedBufferMemoryStream : UnmanagedMemoryStream
{
private byte[] _array;
private GCHandle _pinningHandle;
// The new inheritance model requires a Critical default ctor since base (UnmanagedMemoryStream) has one
- private PinnedBufferMemoryStream():base(){}
+ private PinnedBufferMemoryStream() : base() { }
internal PinnedBufferMemoryStream(byte[] array)
{
@@ -33,7 +35,8 @@ namespace System.IO {
int len = array.Length;
// Handle 0 length byte arrays specially.
- if (len == 0) {
+ if (len == 0)
+ {
array = new byte[1];
len = 0;
}
@@ -42,7 +45,7 @@ namespace System.IO {
_pinningHandle = new GCHandle(array, GCHandleType.Pinned);
// Now the byte[] is pinned for the lifetime of this instance.
// But I also need to get a pointer to that block of memory...
- fixed(byte* ptr = &_array[0])
+ fixed (byte* ptr = &_array[0])
Initialize(ptr, len, len, FileAccess.Read);
}
@@ -53,14 +56,16 @@ namespace System.IO {
protected override void Dispose(bool disposing)
{
- if (_isOpen) {
+ if (_isOpen)
+ {
_pinningHandle.Free();
_isOpen = false;
}
#if _DEBUG
// To help track down lifetime issues on checked builds, force
//a full GC here.
- if (disposing) {
+ if (disposing)
+ {
GC.Collect();
GC.WaitForPendingFinalizers();
}
diff --git a/src/mscorlib/src/System/IO/SearchOption.cs b/src/mscorlib/src/System/IO/SearchOption.cs
index e2f761cd54..75909d7499 100644
--- a/src/mscorlib/src/System/IO/SearchOption.cs
+++ b/src/mscorlib/src/System/IO/SearchOption.cs
@@ -18,9 +18,10 @@
using System;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
- public enum SearchOption
+ internal enum SearchOption
{
// Include only the current directory in the search operation
TopDirectoryOnly,
diff --git a/src/mscorlib/src/System/IO/SeekOrigin.cs b/src/mscorlib/src/System/IO/SeekOrigin.cs
deleted file mode 100644
index bff49e610f..0000000000
--- a/src/mscorlib/src/System/IO/SeekOrigin.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.
-
-/*============================================================
-**
-** Enum: SeekOrigin
-**
-**
-**
-**
-** Purpose: Enum describing locations in a stream you could
-** seek relative to.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.IO {
- // Provides seek reference points. To seek to the end of a stream,
- // call stream.Seek(0, SeekOrigin.End).
- [Serializable]
- public enum SeekOrigin
- {
- // These constants match Win32's FILE_BEGIN, FILE_CURRENT, and FILE_END
- Begin = 0,
- Current = 1,
- End = 2,
- }
-}
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index 790f0a09ab..92fe374f19 100644
--- a/src/mscorlib/src/System/IO/Stream.cs
+++ b/src/mscorlib/src/System/IO/Stream.cs
@@ -14,6 +14,7 @@
**
**
===========================================================*/
+
using System;
using System.Buffers;
using System.Threading;
@@ -27,10 +28,11 @@ using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Reflection;
-namespace System.IO {
+namespace System.IO
+{
[Serializable]
- public abstract class Stream : MarshalByRefObject, IDisposable {
-
+ public abstract class Stream : MarshalByRefObject, IDisposable
+ {
public static readonly Stream Null = new NullStream();
//We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
@@ -52,55 +54,68 @@ namespace System.IO {
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
- public abstract bool CanRead {
+ public abstract bool CanRead
+ {
[Pure]
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
- public abstract bool CanSeek {
+ public abstract bool CanSeek
+ {
[Pure]
get;
}
- public virtual bool CanTimeout {
+ public virtual bool CanTimeout
+ {
[Pure]
- get {
+ get
+ {
return false;
}
}
-
- public abstract bool CanWrite {
+
+ public abstract bool CanWrite
+ {
[Pure]
get;
}
- public abstract long Length {
+ public abstract long Length
+ {
get;
}
- public abstract long Position {
+ public abstract long Position
+ {
get;
set;
}
- public virtual int ReadTimeout {
- get {
+ public virtual int ReadTimeout
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
- set {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ set
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
- public virtual int WriteTimeout {
- get {
+ public virtual int WriteTimeout
+ {
+ get
+ {
Contract.Ensures(Contract.Result<int>() >= 0);
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
- set {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TimeoutsNotSupported"));
+ set
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
@@ -127,7 +142,7 @@ namespace System.IO {
// because it would be a breaking change if the stream's override didn't throw before,
// or in a different order. So for simplicity, we just set the bufferSize to 1
// (not 0 since the default implementation throws for 0) and forward to the virtual method.
- bufferSize = 1;
+ bufferSize = 1;
}
else
{
@@ -295,7 +310,7 @@ namespace System.IO {
}
internal IAsyncResult BeginReadInternal(
- byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
+ byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
@@ -341,7 +356,7 @@ namespace System.IO {
{
thisTask._stream.FinishTrackingAsyncOperation();
}
-
+
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
@@ -352,7 +367,7 @@ namespace System.IO {
else
RunReadWriteTask(asyncResult);
-
+
return asyncResult; // return it
}
@@ -367,18 +382,18 @@ namespace System.IO {
if (readTask == null)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (readTask != asyncResult)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
+ throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (!readTask._isRead)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
-
- try
+
+ try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
@@ -437,12 +452,12 @@ namespace System.IO {
}
internal IAsyncResult BeginWriteInternal(
- byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
+ byte[] buffer, int offset, int count, AsyncCallback callback, Object state,
bool serializeAsynchronously, bool apm)
{
Contract.Ensures(Contract.Result<IAsyncResult>() != null);
if (!CanWrite) __Error.WriteNotSupported();
-
+
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
@@ -472,7 +487,7 @@ namespace System.IO {
try
{
// Do the Write
- thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
+ thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
@@ -501,7 +516,7 @@ namespace System.IO {
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null); // Should be Contract.Requires, but CCRewrite is doing a poor job with
- // preconditions in async methods that await.
+ // preconditions in async methods that await.
Debug.Assert(asyncWaiter != null); // Ditto
// If the wait has already completed, run the task.
@@ -509,10 +524,11 @@ namespace System.IO {
{
Debug.Assert(asyncWaiter.IsRanToCompletion, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
- }
+ }
else // Otherwise, wait for our turn, and then run the task.
{
- asyncWaiter.ContinueWith((t, state) => {
+ asyncWaiter.ContinueWith((t, state) =>
+ {
Debug.Assert(t.IsRanToCompletion, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
@@ -536,32 +552,32 @@ namespace System.IO {
private void FinishTrackingAsyncOperation()
{
- _activeReadWriteTask = null;
+ _activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
- if (asyncResult==null)
+ if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != asyncResult)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
+ throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask._isRead)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
- try
+ try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
@@ -590,10 +606,10 @@ namespace System.IO {
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
- internal readonly bool _isRead;
+ internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
- internal byte [] _buffer;
+ internal byte[] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
@@ -608,7 +624,7 @@ namespace System.IO {
public ReadWriteTask(
bool isRead,
bool apm,
- Func<object,int> function, object state,
+ Func<object, int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
@@ -647,23 +663,23 @@ namespace System.IO {
}
private static ContextCallback s_invokeAsyncCallback;
-
+
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
- if (context == null)
+ if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
- else
+ else
{
_context = null;
-
+
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
@@ -704,14 +720,14 @@ namespace System.IO {
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
- this, new ReadWriteParameters { Buffer=buffer, Offset=offset, Count=count },
+ this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default(VoidTaskResult);
});
- }
+ }
public abstract long Seek(long offset, SeekOrigin origin);
@@ -732,7 +748,7 @@ namespace System.IO {
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
- if (r==0)
+ if (r == 0)
return -1;
return oneByteArray[0];
}
@@ -751,20 +767,20 @@ namespace System.IO {
Write(oneByteArray, 0, 1);
}
- public static Stream Synchronized(Stream stream)
+ public static Stream Synchronized(Stream stream)
{
- if (stream==null)
+ if (stream == null)
throw new ArgumentNullException(nameof(stream));
Contract.Ensures(Contract.Result<Stream>() != null);
Contract.EndContractBlock();
if (stream is SyncStream)
return stream;
-
+
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
- protected virtual void ObjectInvariant()
+ protected virtual void ObjectInvariant()
{
}
@@ -778,16 +794,19 @@ namespace System.IO {
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
- SynchronousAsyncResult asyncResult;
- try {
+ SynchronousAsyncResult asyncResult;
+ try
+ {
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
- catch (IOException ex) {
+ catch (IOException ex)
+ {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
-
- if (callback != null) {
+
+ if (callback != null)
+ {
callback(asyncResult);
}
@@ -812,15 +831,18 @@ namespace System.IO {
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
- try {
+ try
+ {
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
- catch (IOException ex) {
+ catch (IOException ex)
+ {
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
- if (callback != null) {
+ if (callback != null)
+ {
callback(asyncResult);
}
@@ -835,45 +857,50 @@ namespace System.IO {
[Serializable]
private sealed class NullStream : Stream
{
- internal NullStream() {}
+ internal NullStream() { }
- public override bool CanRead {
+ public override bool CanRead
+ {
[Pure]
get { return true; }
}
- public override bool CanWrite {
+ public override bool CanWrite
+ {
[Pure]
get { return true; }
}
- public override bool CanSeek {
+ public override bool CanSeek
+ {
[Pure]
get { return true; }
}
- public override long Length {
+ public override long Length
+ {
get { return 0; }
}
- public override long Position {
+ public override long Position
+ {
get { return 0; }
- set {}
+ set { }
}
-
+
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
-
+
// After we validate arguments this is a nop.
}
-
+
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
-
+
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
@@ -935,7 +962,7 @@ namespace System.IO {
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var nullReadTask = s_nullReadTask;
- if (nullReadTask == null)
+ if (nullReadTask == null)
s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
return nullReadTask;
}
@@ -971,11 +998,11 @@ namespace System.IO {
}
}
-
+
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
- internal sealed class SynchronousAsyncResult : IAsyncResult {
-
- private readonly Object _stateObject;
+ internal sealed class SynchronousAsyncResult : IAsyncResult
+ {
+ private readonly Object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
@@ -983,49 +1010,58 @@ namespace System.IO {
private bool _endXxxCalled;
private Int32 _bytesRead;
- internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) {
+ internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject)
+ {
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
- internal SynchronousAsyncResult(Object asyncStateObject) {
+ internal SynchronousAsyncResult(Object asyncStateObject)
+ {
_stateObject = asyncStateObject;
_isWrite = true;
}
- internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) {
+ internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite)
+ {
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
- _isWrite = isWrite;
+ _isWrite = isWrite;
}
- public bool IsCompleted {
+ public bool IsCompleted
+ {
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
- public WaitHandle AsyncWaitHandle {
- get {
- return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
+ public WaitHandle AsyncWaitHandle
+ {
+ get
+ {
+ return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
- public Object AsyncState {
+ public Object AsyncState
+ {
get { return _stateObject; }
}
- public bool CompletedSynchronously {
+ public bool CompletedSynchronously
+ {
get { return true; }
}
- internal void ThrowIfError() {
+ internal void ThrowIfError()
+ {
if (_exceptionInfo != null)
_exceptionInfo.Throw();
- }
-
- internal static Int32 EndRead(IAsyncResult asyncResult) {
+ }
+ internal static Int32 EndRead(IAsyncResult asyncResult)
+ {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || ar._isWrite)
__Error.WrongAsyncResult();
@@ -1039,8 +1075,8 @@ namespace System.IO {
return ar._bytesRead;
}
- internal static void EndWrite(IAsyncResult asyncResult) {
-
+ internal static void EndWrite(IAsyncResult asyncResult)
+ {
SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult;
if (ar == null || !ar._isWrite)
__Error.WrongAsyncResult();
@@ -1069,64 +1105,83 @@ namespace System.IO {
Contract.EndContractBlock();
_stream = stream;
}
-
- public override bool CanRead {
+
+ public override bool CanRead
+ {
[Pure]
get { return _stream.CanRead; }
}
-
- public override bool CanWrite {
+
+ public override bool CanWrite
+ {
[Pure]
get { return _stream.CanWrite; }
}
-
- public override bool CanSeek {
+
+ public override bool CanSeek
+ {
[Pure]
get { return _stream.CanSeek; }
}
-
- public override bool CanTimeout {
+
+ public override bool CanTimeout
+ {
[Pure]
- get {
+ get
+ {
return _stream.CanTimeout;
}
}
- public override long Length {
- get {
- lock(_stream) {
+ public override long Length
+ {
+ get
+ {
+ lock (_stream)
+ {
return _stream.Length;
}
}
}
-
- public override long Position {
- get {
- lock(_stream) {
+
+ public override long Position
+ {
+ get
+ {
+ lock (_stream)
+ {
return _stream.Position;
}
}
- set {
- lock(_stream) {
+ set
+ {
+ lock (_stream)
+ {
_stream.Position = value;
}
}
}
- public override int ReadTimeout {
- get {
+ public override int ReadTimeout
+ {
+ get
+ {
return _stream.ReadTimeout;
}
- set {
+ set
+ {
_stream.ReadTimeout = value;
}
}
- public override int WriteTimeout {
- get {
+ public override int WriteTimeout
+ {
+ get
+ {
return _stream.WriteTimeout;
}
- set {
+ set
+ {
_stream.WriteTimeout = value;
}
}
@@ -1135,48 +1190,54 @@ namespace System.IO {
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
- lock(_stream) {
- try {
+ lock (_stream)
+ {
+ try
+ {
_stream.Close();
}
- finally {
+ finally
+ {
base.Dispose(true);
}
}
}
-
+
protected override void Dispose(bool disposing)
{
- lock(_stream) {
- try {
+ lock (_stream)
+ {
+ try
+ {
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
- finally {
+ finally
+ {
base.Dispose(disposing);
}
}
}
-
+
public override void Flush()
{
- lock(_stream)
+ lock (_stream)
_stream.Flush();
}
-
+
public override int Read([In, Out]byte[] bytes, int offset, int count)
{
- lock(_stream)
+ lock (_stream)
return _stream.Read(bytes, offset, count);
}
-
+
public override int ReadByte()
{
- lock(_stream)
+ lock (_stream)
return _stream.ReadByte();
}
-
+
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
@@ -1194,7 +1255,7 @@ namespace System.IO {
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
-
+
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
@@ -1202,34 +1263,34 @@ namespace System.IO {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.EndContractBlock();
- lock(_stream)
+ lock (_stream)
return _stream.EndRead(asyncResult);
}
-
+
public override long Seek(long offset, SeekOrigin origin)
{
- lock(_stream)
+ lock (_stream)
return _stream.Seek(offset, origin);
}
-
+
public override void SetLength(long length)
{
- lock(_stream)
+ lock (_stream)
_stream.SetLength(length);
}
-
+
public override void Write(byte[] bytes, int offset, int count)
{
- lock(_stream)
+ lock (_stream)
_stream.Write(bytes, offset, count);
}
-
+
public override void WriteByte(byte b)
{
- lock(_stream)
+ lock (_stream)
_stream.WriteByte(b);
}
-
+
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
{
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
@@ -1247,14 +1308,14 @@ namespace System.IO {
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
}
-
+
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
Contract.EndContractBlock();
- lock(_stream)
+ lock (_stream)
_stream.EndWrite(asyncResult);
}
}
diff --git a/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs b/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.cs
deleted file mode 100644
index 8ff0e045ca..0000000000
--- a/src/mscorlib/src/System/IO/StreamHelpers.CopyValidation.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.
-
-namespace System.IO
-{
- /// <summary>Provides methods to help in the implementation of Stream-derived types.</summary>
- internal static partial class StreamHelpers
- {
- /// <summary>Validate the arguments to CopyTo, as would Stream.CopyTo.</summary>
- public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
- {
- if (destination == null)
- {
- throw new ArgumentNullException(nameof(destination));
- }
-
- if (bufferSize <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
- }
-
- bool sourceCanRead = source.CanRead;
- if (!sourceCanRead && !source.CanWrite)
- {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
- }
-
- bool destinationCanWrite = destination.CanWrite;
- if (!destinationCanWrite && !destination.CanRead)
- {
- throw new ObjectDisposedException(nameof(destination), Environment.GetResourceString("ObjectDisposed_StreamClosed"));
- }
-
- if (!sourceCanRead)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
- }
-
- if (!destinationCanWrite)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs
index 6d50347b1a..dfb928c85d 100644
--- a/src/mscorlib/src/System/IO/StreamReader.cs
+++ b/src/mscorlib/src/System/IO/StreamReader.cs
@@ -103,7 +103,7 @@ namespace System.IO
Task t = _asyncReadTask;
if (t != null && !t.IsCompleted)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
+ throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress);
}
// StreamReader by default will ignore illegal UTF8 characters. We don't want to
@@ -149,9 +149,9 @@ namespace System.IO
if (stream == null || encoding == null)
throw new ArgumentNullException((stream == null ? nameof(stream) : nameof(encoding)));
if (!stream.CanRead)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
+ throw new ArgumentException(SR.Argument_StreamNotReadable);
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
Contract.EndContractBlock();
Init(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, leaveOpen);
@@ -181,9 +181,9 @@ namespace System.IO
if (path==null || encoding==null)
throw new ArgumentNullException((path==null ? nameof(path) : nameof(encoding)));
if (path.Length==0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
+ throw new ArgumentException(SR.Argument_EmptyPath);
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
Contract.EndContractBlock();
Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan);
@@ -338,11 +338,11 @@ namespace System.IO
public override int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (stream == null)
@@ -396,11 +396,11 @@ namespace System.IO
public override int ReadBlock([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (stream == null)
@@ -540,7 +540,7 @@ namespace System.IO
return sb.ToString();
}
- internal virtual int ReadBuffer() {
+ internal int ReadBuffer() {
charLen = 0;
charPos = 0;
@@ -777,16 +777,16 @@ namespace System.IO
private async Task<String> ReadLineAsyncInternal()
{
- if (CharPos_Prop == CharLen_Prop && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
+ if (charPos == charLen && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
return null;
StringBuilder sb = null;
do
{
- char[] tmpCharBuffer = CharBuffer_Prop;
- int tmpCharLen = CharLen_Prop;
- int tmpCharPos = CharPos_Prop;
+ char[] tmpCharBuffer = charBuffer;
+ int tmpCharLen = charLen;
+ int tmpCharPos = charPos;
int i = tmpCharPos;
do
@@ -809,13 +809,13 @@ namespace System.IO
s = new String(tmpCharBuffer, tmpCharPos, i - tmpCharPos);
}
- CharPos_Prop = tmpCharPos = i + 1;
+ charPos = tmpCharPos = i + 1;
if (ch == '\r' && (tmpCharPos < tmpCharLen || (await ReadBufferAsync().ConfigureAwait(false)) > 0))
{
- tmpCharPos = CharPos_Prop;
- if (CharBuffer_Prop[tmpCharPos] == '\n')
- CharPos_Prop = ++tmpCharPos;
+ tmpCharPos = charPos;
+ if (charBuffer[tmpCharPos] == '\n')
+ charPos = ++tmpCharPos;
}
return s;
@@ -857,14 +857,14 @@ namespace System.IO
private async Task<String> ReadToEndAsyncInternal()
{
// Call ReadBuffer, then pull data out of charBuffer.
- StringBuilder sb = AcquireSharedStringBuilder(CharLen_Prop - CharPos_Prop);
+ StringBuilder sb = AcquireSharedStringBuilder(charLen - charPos);
do
{
- int tmpCharPos = CharPos_Prop;
- sb.Append(CharBuffer_Prop, tmpCharPos, CharLen_Prop - tmpCharPos);
- CharPos_Prop = CharLen_Prop; // We consumed these characters
+ int tmpCharPos = charPos;
+ sb.Append(charBuffer, tmpCharPos, charLen - tmpCharPos);
+ charPos = charLen; // We consumed these characters
await ReadBufferAsync().ConfigureAwait(false);
- } while (CharLen_Prop > 0);
+ } while (charLen > 0);
return GetStringAndReleaseSharedStringBuilder(sb);
}
@@ -872,11 +872,11 @@ namespace System.IO
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
@@ -899,7 +899,7 @@ namespace System.IO
internal override async Task<int> ReadAsyncInternal(char[] buffer, int index, int count)
{
- if (CharPos_Prop == CharLen_Prop && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
+ if (charPos == charLen && (await ReadBufferAsync().ConfigureAwait(false)) == 0)
return 0;
int charsRead = 0;
@@ -908,24 +908,24 @@ namespace System.IO
// data read in, let's try writing directly to the user's buffer.
bool readToUserBuffer = false;
- Byte[] tmpByteBuffer = ByteBuffer_Prop;
- Stream tmpStream = Stream_Prop;
+ Byte[] tmpByteBuffer = byteBuffer;
+ Stream tmpStream = stream;
while (count > 0)
{
// n is the characters available in _charBuffer
- int n = CharLen_Prop - CharPos_Prop;
+ int n = charLen - charPos;
// charBuffer is empty, let's read from the stream
if (n == 0)
{
- CharLen_Prop = 0;
- CharPos_Prop = 0;
+ charLen = 0;
+ charPos = 0;
- if (!CheckPreamble_Prop)
- ByteLen_Prop = 0;
+ if (!_checkPreamble)
+ byteLen = 0;
- readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
+ readToUserBuffer = count >= _maxCharsPerBuffer;
// We loop here so that we read in enough bytes to yield at least 1 char.
// We break out of the loop if the stream is blocked (EOF is reached).
@@ -933,10 +933,10 @@ namespace System.IO
{
Debug.Assert(n == 0);
- if (CheckPreamble_Prop)
+ if (_checkPreamble)
{
- Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
- int tmpBytePos = BytePos_Prop;
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ int tmpBytePos = bytePos;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
@@ -944,42 +944,42 @@ namespace System.IO
{
// EOF but we might have buffered bytes from previous
// attempts to detect preamble that needs to be decoded now
- if (ByteLen_Prop > 0)
+ if (byteLen > 0)
{
if (readToUserBuffer)
{
- n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
- CharLen_Prop = 0; // StreamReader's buffer is empty.
+ n = decoder.GetChars(tmpByteBuffer, 0, byteLen, buffer, index + charsRead);
+ charLen = 0; // StreamReader's buffer is empty.
}
else
{
- n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
- CharLen_Prop += n; // Number of chars in StreamReader's buffer.
+ n = decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, 0);
+ charLen += n; // Number of chars in StreamReader's buffer.
}
}
// How can part of the preamble yield any chars?
Debug.Assert(n == 0);
- IsBlocked_Prop = true;
+ _isBlocked = true;
break;
}
else
{
- ByteLen_Prop += len;
+ byteLen += len;
}
}
else
{
- Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ Debug.Assert(bytePos == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
- ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
+ byteLen = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
- if (ByteLen_Prop == 0) // EOF
+ if (byteLen == 0) // EOF
{
- IsBlocked_Prop = true;
+ _isBlocked = true;
break;
}
}
@@ -987,7 +987,7 @@ namespace System.IO
// _isBlocked == whether we read fewer bytes than we asked for.
// Note we must check it here because CompressBuffer or
// DetectEncoding will change _byteLen.
- IsBlocked_Prop = (ByteLen_Prop < tmpByteBuffer.Length);
+ _isBlocked = (byteLen < tmpByteBuffer.Length);
// Check for preamble before detect encoding. This is not to override the
// user suppplied Encoding for the one we implicitly detect. The user could
@@ -998,33 +998,33 @@ namespace System.IO
continue;
// On the first call to ReadBuffer, if we're supposed to detect the encoding, do it.
- if (DetectEncoding_Prop && ByteLen_Prop >= 2)
+ if (_detectEncoding && byteLen >= 2)
{
DetectEncoding();
// DetectEncoding changes some buffer state. Recompute this.
- readToUserBuffer = count >= MaxCharsPerBuffer_Prop;
+ readToUserBuffer = count >= _maxCharsPerBuffer;
}
Debug.Assert(n == 0);
- CharPos_Prop = 0;
+ charPos = 0;
if (readToUserBuffer)
{
- n += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, buffer, index + charsRead);
+ n += decoder.GetChars(tmpByteBuffer, 0, byteLen, buffer, index + charsRead);
// Why did the bytes yield no chars?
Debug.Assert(n > 0);
- CharLen_Prop = 0; // StreamReader's buffer is empty.
+ charLen = 0; // StreamReader's buffer is empty.
}
else
{
- n = Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, 0);
+ n = decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, 0);
// Why did the bytes yield no chars?
Debug.Assert(n > 0);
- CharLen_Prop += n; // Number of chars in StreamReader's buffer.
+ charLen += n; // Number of chars in StreamReader's buffer.
}
} while (n == 0);
@@ -1038,8 +1038,8 @@ namespace System.IO
if (!readToUserBuffer)
{
- Buffer.InternalBlockCopy(CharBuffer_Prop, CharPos_Prop * 2, buffer, (index + charsRead) * 2, n * 2);
- CharPos_Prop += n;
+ Buffer.InternalBlockCopy(charBuffer, charPos * 2, buffer, (index + charsRead) * 2, n * 2);
+ charPos += n;
}
charsRead += n;
@@ -1048,7 +1048,7 @@ namespace System.IO
// This function shouldn't block for an indefinite amount of time,
// or reading from a network stream won't work right. If we got
// fewer bytes than we requested, then we want to break right here.
- if (IsBlocked_Prop)
+ if (_isBlocked)
break;
} // while (count > 0)
@@ -1058,11 +1058,11 @@ namespace System.IO
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
@@ -1083,113 +1083,50 @@ namespace System.IO
return task;
}
- #region Private properties for async method performance
- // Access to instance fields of MarshalByRefObject-derived types requires special JIT helpers that check
- // if the instance operated on is remote. This is optimised for fields on this but if a method is Async
- // and is thus lifted to a state machine type, access will be slow.
- // As a workaround, we either cache instance fields in locals or use properties to access such fields.
-
- private Int32 CharLen_Prop {
- get { return charLen; }
- set { charLen = value; }
- }
-
- private Int32 CharPos_Prop {
- get { return charPos; }
- set { charPos = value; }
- }
-
- private Int32 ByteLen_Prop {
- get { return byteLen; }
- set { byteLen = value; }
- }
-
- private Int32 BytePos_Prop {
- get { return bytePos; }
- set { bytePos = value; }
- }
-
- private Byte[] Preamble_Prop {
- get { return _preamble; }
- }
-
- private bool CheckPreamble_Prop {
- get { return _checkPreamble; }
- }
-
- private Decoder Decoder_Prop {
- get { return decoder; }
- }
-
- private bool DetectEncoding_Prop {
- get { return _detectEncoding; }
- }
-
- private Char[] CharBuffer_Prop {
- get { return charBuffer; }
- }
-
- private Byte[] ByteBuffer_Prop {
- get { return byteBuffer; }
- }
-
- private bool IsBlocked_Prop {
- get { return _isBlocked; }
- set { _isBlocked = value; }
- }
-
- private Stream Stream_Prop {
- get { return stream; }
- }
-
- private Int32 MaxCharsPerBuffer_Prop {
- get { return _maxCharsPerBuffer; }
- }
- #endregion Private properties for async method performance
private async Task<int> ReadBufferAsync()
{
- CharLen_Prop = 0;
- CharPos_Prop = 0;
- Byte[] tmpByteBuffer = ByteBuffer_Prop;
- Stream tmpStream = Stream_Prop;
+ charLen = 0;
+ charPos = 0;
+ Byte[] tmpByteBuffer = byteBuffer;
+ Stream tmpStream = stream;
- if (!CheckPreamble_Prop)
- ByteLen_Prop = 0;
+ if (!_checkPreamble)
+ byteLen = 0;
do {
- if (CheckPreamble_Prop) {
- Debug.Assert(BytePos_Prop <= Preamble_Prop.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
- int tmpBytePos = BytePos_Prop;
+ if (_checkPreamble) {
+ Debug.Assert(bytePos <= _preamble.Length, "possible bug in _compressPreamble. Are two threads using this StreamReader at the same time?");
+ int tmpBytePos = bytePos;
int len = await tmpStream.ReadAsync(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos).ConfigureAwait(false);
Debug.Assert(len >= 0, "Stream.Read returned a negative number! This is a bug in your stream class.");
if (len == 0) {
// EOF but we might have buffered bytes from previous
// attempt to detect preamble that needs to be decoded now
- if (ByteLen_Prop > 0)
+ if (byteLen > 0)
{
- CharLen_Prop += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, CharLen_Prop);
+ charLen += decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, charLen);
// Need to zero out the _byteLen after we consume these bytes so that we don't keep infinitely hitting this code path
- BytePos_Prop = 0; ByteLen_Prop = 0;
+ bytePos = 0; byteLen = 0;
}
- return CharLen_Prop;
+ return charLen;
}
- ByteLen_Prop += len;
+ byteLen += len;
}
else {
- Debug.Assert(BytePos_Prop == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
- ByteLen_Prop = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
- Debug.Assert(ByteLen_Prop >= 0, "Stream.Read returned a negative number! Bug in stream class.");
+ Debug.Assert(bytePos == 0, "_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this StreamReader at the same time?");
+ byteLen = await tmpStream.ReadAsync(tmpByteBuffer, 0, tmpByteBuffer.Length).ConfigureAwait(false);
+ Debug.Assert(byteLen >= 0, "Stream.Read returned a negative number! Bug in stream class.");
- if (ByteLen_Prop == 0) // We're at EOF
- return CharLen_Prop;
+ if (byteLen == 0) // We're at EOF
+ return charLen;
}
// _isBlocked == whether we read fewer bytes than we asked for.
// Note we must check it here because CompressBuffer or
// DetectEncoding will change _byteLen.
- IsBlocked_Prop = (ByteLen_Prop < tmpByteBuffer.Length);
+ _isBlocked = (byteLen < tmpByteBuffer.Length);
// Check for preamble before detect encoding. This is not to override the
// user suppplied Encoding for the one we implicitly detect. The user could
@@ -1199,13 +1136,13 @@ namespace System.IO
// If we're supposed to detect the encoding and haven't done so yet,
// do it. Note this may need to be called more than once.
- if (DetectEncoding_Prop && ByteLen_Prop >= 2)
+ if (_detectEncoding && byteLen >= 2)
DetectEncoding();
- CharLen_Prop += Decoder_Prop.GetChars(tmpByteBuffer, 0, ByteLen_Prop, CharBuffer_Prop, CharLen_Prop);
- } while (CharLen_Prop == 0);
+ charLen += decoder.GetChars(tmpByteBuffer, 0, byteLen, charBuffer, charLen);
+ } while (charLen == 0);
- return CharLen_Prop;
+ return charLen;
}
#endregion
@@ -1254,12 +1191,6 @@ namespace System.IO
{
return String.Empty;
}
-
- internal override int ReadBuffer()
- {
- return 0;
- }
-
}
}
}
diff --git a/src/mscorlib/src/System/IO/TextReader.cs b/src/mscorlib/src/System/IO/TextReader.cs
index 15ba8fba7d..3da68591b0 100644
--- a/src/mscorlib/src/System/IO/TextReader.cs
+++ b/src/mscorlib/src/System/IO/TextReader.cs
@@ -93,13 +93,13 @@ namespace System.IO {
public virtual int Read([In, Out] char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count));
Contract.EndContractBlock();
@@ -192,11 +192,11 @@ namespace System.IO {
public virtual Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
return ReadAsyncInternal(buffer, index, count);
@@ -221,11 +221,11 @@ namespace System.IO {
public virtual Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
@@ -362,11 +362,11 @@ namespace System.IO {
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
@@ -377,11 +377,11 @@ namespace System.IO {
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
return Task.FromResult(Read(buffer, index, count));
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
index f3fd71833c..5f6f588cbe 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryAccessor.cs
@@ -12,6 +12,7 @@
**
**
===========================================================*/
+
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -21,13 +22,13 @@ using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-namespace System.IO {
-
+namespace System.IO
+{
/// Perf notes: ReadXXX, WriteXXX (for basic types) acquire and release the
/// SafeBuffer pointer rather than relying on generic Read(T) from SafeBuffer because
/// this gives better throughput; benchmarks showed about 12-15% better.
- public class UnmanagedMemoryAccessor : IDisposable {
-
+ public class UnmanagedMemoryAccessor : IDisposable
+ {
private SafeBuffer _buffer;
private Int64 _offset;
[ContractPublicPropertyName("Capacity")]
@@ -37,7 +38,8 @@ namespace System.IO {
private bool _canRead;
private bool _canWrite;
- protected UnmanagedMemoryAccessor() {
+ protected UnmanagedMemoryAccessor()
+ {
_isOpen = false;
}
@@ -45,47 +47,61 @@ namespace System.IO {
// <SecurityKernel Critical="True" Ring="1">
// <ReferencesCritical Name="Method: Initialize(SafeBuffer, Int64, Int64, FileAccess):Void" Ring="1" />
// </SecurityKernel>
- public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity) {
+ public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity)
+ {
Initialize(buffer, offset, capacity, FileAccess.Read);
}
- public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
+ public UnmanagedMemoryAccessor(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access)
+ {
Initialize(buffer, offset, capacity, access);
}
- protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access) {
- if (buffer == null) {
+ protected void Initialize(SafeBuffer buffer, Int64 offset, Int64 capacity, FileAccess access)
+ {
+ if (buffer == null)
+ {
throw new ArgumentNullException(nameof(buffer));
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (capacity < 0) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (capacity < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (buffer.ByteLength < (UInt64)(offset + capacity)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndCapacityOutOfBounds"));
+ if (buffer.ByteLength < (UInt64)(offset + capacity))
+ {
+ throw new ArgumentException(SR.Argument_OffsetAndCapacityOutOfBounds);
}
- if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
+ if (access < FileAccess.Read || access > FileAccess.ReadWrite)
+ {
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
- if (_isOpen) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
+ if (_isOpen)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
buffer.AcquirePointer(ref pointer);
- if (((byte*)((Int64)pointer + offset + capacity)) < pointer) {
- throw new ArgumentException(Environment.GetResourceString("Argument_UnmanagedMemAccessorWrapAround"));
+ if (((byte*)((Int64)pointer + offset + capacity)) < pointer)
+ {
+ throw new ArgumentException(SR.Argument_UnmanagedMemAccessorWrapAround);
}
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
buffer.ReleasePointer();
}
}
@@ -102,38 +118,48 @@ namespace System.IO {
#endregion
- public Int64 Capacity {
- get {
- return _capacity;
+ public Int64 Capacity
+ {
+ get
+ {
+ return _capacity;
}
}
- public bool CanRead {
- get {
- return _isOpen && _canRead;
+ public bool CanRead
+ {
+ get
+ {
+ return _isOpen && _canRead;
}
}
- public bool CanWrite {
- get {
- return _isOpen && _canWrite;
+ public bool CanWrite
+ {
+ get
+ {
+ return _isOpen && _canWrite;
}
}
- protected virtual void Dispose(bool disposing) {
+ protected virtual void Dispose(bool disposing)
+ {
_isOpen = false;
}
- public void Dispose() {
+ public void Dispose()
+ {
Dispose(true);
GC.SuppressFinalize(this);
}
- protected bool IsOpen {
+ protected bool IsOpen
+ {
get { return _isOpen; }
}
- public bool ReadBoolean(Int64 position) {
+ public bool ReadBoolean(Int64 position)
+ {
int sizeOfType = sizeof(bool);
EnsureSafeToRead(position, sizeOfType);
@@ -141,40 +167,32 @@ namespace System.IO {
return b != 0;
}
- public byte ReadByte(Int64 position) {
+ public byte ReadByte(Int64 position)
+ {
int sizeOfType = sizeof(byte);
EnsureSafeToRead(position, sizeOfType);
return InternalReadByte(position);
}
- public char ReadChar(Int64 position) {
- int sizeOfType = sizeof(char);
- EnsureSafeToRead(position, sizeOfType);
-
- char result;
+ public char ReadChar(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(char));
- unsafe {
+ char result;
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((char*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (char)( *pointer | *(pointer + 1) << 8 ) ;
- }
-#endif
+ result = Unsafe.ReadUnaligned<char>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -184,33 +202,24 @@ namespace System.IO {
}
// See comment above.
- public Int16 ReadInt16(Int64 position) {
- int sizeOfType = sizeof(Int16);
- EnsureSafeToRead(position, sizeOfType);
+ public Int16 ReadInt16(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Int16));
Int16 result;
-
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((Int16*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (Int16)( *pointer | *(pointer + 1) << 8 );
- }
-#endif
+ result = Unsafe.ReadUnaligned<Int16>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -220,32 +229,24 @@ namespace System.IO {
}
- public Int32 ReadInt32(Int64 position) {
- int sizeOfType = sizeof(Int32);
- EnsureSafeToRead(position, sizeOfType);
+ public Int32 ReadInt32(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Int32));
Int32 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((Int32*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (Int32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- }
-#endif
+ result = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -254,34 +255,24 @@ namespace System.IO {
return result;
}
- public Int64 ReadInt64(Int64 position) {
- int sizeOfType = sizeof(Int64);
- EnsureSafeToRead(position, sizeOfType);
+ public Int64 ReadInt64(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Int64));
Int64 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((Int64*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- int lo = *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24;
- int hi = *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24;
- result = (Int64)(((Int64)hi << 32) | (UInt32)lo);
- }
-#endif
- }
- finally {
- if (pointer != null) {
+ result = Unsafe.ReadUnaligned<Int64>(pointer + _offset + position);
+ }
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -290,28 +281,14 @@ namespace System.IO {
return result;
}
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private unsafe Int32 UnsafeReadInt32(byte* pointer)
+ public Decimal ReadDecimal(Int64 position)
{
- Int32 result;
- // check if pointer is aligned
- if (((int)pointer & (sizeof(Int32) - 1)) == 0)
- {
- result = *((Int32*)pointer);
- }
- else
- {
- result = (Int32)(*(pointer) | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24);
- }
-
- return result;
- }
- public Decimal ReadDecimal(Int64 position) {
const int ScaleMask = 0x00FF0000;
const int SignMask = unchecked((int)0x80000000);
- int sizeOfType = sizeof(Decimal);
- EnsureSafeToRead(position, sizeOfType);
+ EnsureSafeToRead(position, sizeof(Decimal));
+
+ int lo, mid, hi, flags;
unsafe
{
@@ -319,23 +296,11 @@ namespace System.IO {
try
{
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
- int lo = UnsafeReadInt32(pointer);
- int mid = UnsafeReadInt32(pointer + 4);
- int hi = UnsafeReadInt32(pointer + 8);
- int flags = UnsafeReadInt32(pointer + 12);
-
- // Check for invalid Decimal values
- if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_BadDecimal")); // Throw same Exception type as Decimal(int[]) ctor for compat
- }
-
- bool isNegative = (flags & SignMask) != 0;
- byte scale = (byte)(flags >> 16);
-
- return new decimal(lo, mid, hi, isNegative, scale);
+
+ lo = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position);
+ mid = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 4);
+ hi = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 8);
+ flags = Unsafe.ReadUnaligned<Int32>(pointer + _offset + position + 12);
}
finally
{
@@ -345,35 +310,37 @@ namespace System.IO {
}
}
}
+
+ // Check for invalid Decimal values
+ if (!((flags & ~(SignMask | ScaleMask)) == 0 && (flags & ScaleMask) <= (28 << 16)))
+ {
+ throw new ArgumentException(SR.Arg_BadDecimal); // Throw same Exception type as Decimal(int[]) ctor for compat
+ }
+
+ bool isNegative = (flags & SignMask) != 0;
+ byte scale = (byte)(flags >> 16);
+
+ return new decimal(lo, mid, hi, isNegative, scale);
}
- public Single ReadSingle(Int64 position) {
- int sizeOfType = sizeof(Single);
- EnsureSafeToRead(position, sizeOfType);
+ public Single ReadSingle(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Single));
Single result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = BitConverter.Int32BitsToSingle(*((int*)(pointer)));
-#if ALIGN_ACCESS
- }
- else {
- UInt32 tempResult = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- result = *((float*)&tempResult);
- }
-#endif
+ result = Unsafe.ReadUnaligned<Single>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -382,37 +349,24 @@ namespace System.IO {
return result;
}
- public Double ReadDouble(Int64 position) {
- int sizeOfType = sizeof(Double);
- EnsureSafeToRead(position, sizeOfType);
+ public Double ReadDouble(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(Double));
Double result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = BitConverter.Int64BitsToDouble(*((long*)(pointer)));
-#if ALIGN_ACCESS
- }
- else {
-
- UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 );
- UInt64 tempResult = ((UInt64)hi) << 32 | lo;
- result = *((double*)&tempResult);
-
- }
-#endif
+ result = Unsafe.ReadUnaligned<Double>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -422,21 +376,25 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public SByte ReadSByte(Int64 position) {
+ public SByte ReadSByte(Int64 position)
+ {
int sizeOfType = sizeof(SByte);
EnsureSafeToRead(position, sizeOfType);
SByte result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
- result = *((SByte*)pointer);
+ result = *((SByte*)(pointer + _offset + position));
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -444,35 +402,26 @@ namespace System.IO {
return result;
}
-
+
[CLSCompliant(false)]
- public UInt16 ReadUInt16(Int64 position) {
- int sizeOfType = sizeof(UInt16);
- EnsureSafeToRead(position, sizeOfType);
+ public UInt16 ReadUInt16(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(UInt16));
UInt16 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((UInt16*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (UInt16)( *pointer | *(pointer + 1) << 8 );
- }
-#endif
-
+ result = Unsafe.ReadUnaligned<UInt16>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -480,35 +429,26 @@ namespace System.IO {
return result;
}
-
+
[CLSCompliant(false)]
- public UInt32 ReadUInt32(Int64 position) {
- int sizeOfType = sizeof(UInt32);
- EnsureSafeToRead(position, sizeOfType);
+ public UInt32 ReadUInt32(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(UInt32));
UInt32 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((UInt32*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- result = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- }
-#endif
-
+ result = Unsafe.ReadUnaligned<UInt32>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -518,35 +458,24 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public UInt64 ReadUInt64(Int64 position) {
- int sizeOfType = sizeof(UInt64);
- EnsureSafeToRead(position, sizeOfType);
+ public UInt64 ReadUInt64(Int64 position)
+ {
+ EnsureSafeToRead(position, sizeof(UInt64));
UInt64 result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- result = *((UInt64*)(pointer));
-#if ALIGN_ACCESS
- }
- else {
- UInt32 lo = (UInt32)( *pointer | *(pointer + 1) << 8 | *(pointer + 2) << 16 | *(pointer + 3) << 24 );
- UInt32 hi = (UInt32)( *(pointer + 4) | *(pointer + 5) << 8 | *(pointer + 6) << 16 | *(pointer + 7) << 24 );
- result = (UInt64)(((UInt64)hi << 32) | lo );
- }
-#endif
-
+ result = Unsafe.ReadUnaligned<UInt64>(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -569,26 +498,33 @@ namespace System.IO {
// such, it is best to use the ReadXXX methods for small standard types such as ints, longs,
// bools, etc.
- public void Read<T>(Int64 position, out T structure) where T : struct {
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public void Read<T>(Int64 position, out T structure) where T : struct
+ {
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanRead) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
+ if (!CanRead)
+ {
+ throw new NotSupportedException(SR.NotSupported_Reading);
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
- if (position > _capacity - sizeOfT) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfT)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead", typeof(T).FullName), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToRead, typeof (T).FullName), nameof(position));
}
}
@@ -601,47 +537,60 @@ namespace System.IO {
// struct that contains reference members will most likely cause the runtime to AV. This
// is consistent with Marshal.PtrToStructure.
- public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
- if (array == null) {
+ public int ReadArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct
+ {
+ if (array == null)
+ {
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (array.Length - offset < count) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
+ if (array.Length - offset < count)
+ {
+ throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
Contract.EndContractBlock();
- if (!CanRead) {
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!CanRead)
+ {
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- else {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
+ else
+ {
+ throw new NotSupportedException(SR.NotSupported_Reading);
}
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
UInt32 sizeOfT = Marshal.AlignedSizeOf<T>();
// only check position and ask for fewer Ts if count is too big
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
int n = count;
long spaceLeft = _capacity - position;
- if (spaceLeft < 0) {
+ if (spaceLeft < 0)
+ {
n = 0;
}
- else {
+ else
+ {
ulong spaceNeeded = (ulong)(sizeOfT * count);
- if ((ulong)spaceLeft < spaceNeeded) {
+ if ((ulong)spaceLeft < spaceNeeded)
+ {
n = (int)(spaceLeft / sizeOfT);
}
}
@@ -659,7 +608,8 @@ namespace System.IO {
// double, short, int, long, sbyte, float, ushort, uint, or ulong.
- public void Write(Int64 position, bool value) {
+ public void Write(Int64 position, bool value)
+ {
int sizeOfType = sizeof(bool);
EnsureSafeToWrite(position, sizeOfType);
@@ -667,73 +617,55 @@ namespace System.IO {
InternalWrite(position, b);
}
- public void Write(Int64 position, byte value) {
+ public void Write(Int64 position, byte value)
+ {
int sizeOfType = sizeof(byte);
EnsureSafeToWrite(position, sizeOfType);
InternalWrite(position, value);
}
- public void Write(Int64 position, char value) {
- int sizeOfType = sizeof(char);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, char value)
+ {
+ EnsureSafeToWrite(position, sizeof(char));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((char*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer+1) = (byte)(value >> 8);
- }
-#endif
+ Unsafe.WriteUnaligned<char>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
-
}
- public void Write(Int64 position, Int16 value) {
- int sizeOfType = sizeof(Int16);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Int16 value)
+ {
+ EnsureSafeToWrite(position, sizeof(Int16));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((Int16*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- }
-#endif
+ Unsafe.WriteUnaligned<Int16>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -741,116 +673,73 @@ namespace System.IO {
}
- public void Write(Int64 position, Int32 value) {
- int sizeOfType = sizeof(Int32);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Int32 value)
+ {
+ EnsureSafeToWrite(position, sizeof(Int32));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((Int32*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- }
-#endif
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- public void Write(Int64 position, Int64 value) {
- int sizeOfType = sizeof(Int64);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Int64 value)
+ {
+ EnsureSafeToWrite(position, sizeof(Int64));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((Int64*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- *(pointer + 4) = (byte)(value >> 32);
- *(pointer + 5) = (byte)(value >> 40);
- *(pointer + 6) = (byte)(value >> 48);
- *(pointer + 7) = (byte)(value >> 56);
- }
-#endif
+ Unsafe.WriteUnaligned<Int64>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- private unsafe void UnsafeWriteInt32(byte* pointer, Int32 value)
+ public void Write(Int64 position, Decimal value)
{
- // check if pointer is aligned
- if (((int)pointer & (sizeof(Int32) - 1)) == 0)
- {
- *((Int32*)pointer) = value;
- }
- else
- {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- }
- }
-
- public void Write(Int64 position, Decimal value) {
- int sizeOfType = sizeof(Decimal);
- EnsureSafeToWrite(position, sizeOfType);
+ EnsureSafeToWrite(position, sizeof(Decimal));
unsafe
{
+ int* valuePtr = (int*)(&value);
+ int flags = *valuePtr;
+ int hi = *(valuePtr + 1);
+ int lo = *(valuePtr + 2);
+ int mid = *(valuePtr + 3);
+
byte* pointer = null;
try
{
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
- int* valuePtr = (int*)(&value);
- int flags = *valuePtr;
- int hi = *(valuePtr + 1);
- int lo = *(valuePtr + 2);
- int mid = *(valuePtr + 3);
-
- UnsafeWriteInt32(pointer, lo);
- UnsafeWriteInt32(pointer + 4, mid);
- UnsafeWriteInt32(pointer + 8, hi);
- UnsafeWriteInt32(pointer + 12, flags);
+
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position, lo);
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 4, mid);
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 8, hi);
+ Unsafe.WriteUnaligned<Int32>(pointer + _offset + position + 12, flags);
}
finally
{
@@ -862,74 +751,46 @@ namespace System.IO {
}
}
- public void Write(Int64 position, Single value) {
- int sizeOfType = sizeof(Single);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Single value)
+ {
+ EnsureSafeToWrite(position, sizeof(Single));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((int*)pointer) = BitConverter.SingleToInt32Bits(value);
-#if ALIGN_ACCESS
- }
- else {
- UInt32 tmpValue = *(UInt32*)&value;
- *(pointer) = (byte)tmpValue;
- *(pointer + 1) = (byte)(tmpValue >> 8);
- *(pointer + 2) = (byte)(tmpValue >> 16);
- *(pointer + 3) = (byte)(tmpValue >> 24);
-
- }
-#endif
+ Unsafe.WriteUnaligned<Single>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- public void Write(Int64 position, Double value) {
- int sizeOfType = sizeof(Double);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, Double value)
+ {
+ EnsureSafeToWrite(position, sizeof(Double));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((long*)pointer) = BitConverter.DoubleToInt64Bits(value);
-#if ALIGN_ACCESS
- }
- else {
- UInt64 tmpValue = *(UInt64 *)&value;
- *(pointer) = (byte) tmpValue;
- *(pointer + 1) = (byte) (tmpValue >> 8);
- *(pointer + 2) = (byte) (tmpValue >> 16);
- *(pointer + 3) = (byte) (tmpValue >> 24);
- *(pointer + 4) = (byte) (tmpValue >> 32);
- *(pointer + 5) = (byte) (tmpValue >> 40);
- *(pointer + 6) = (byte) (tmpValue >> 48);
- *(pointer + 7) = (byte) (tmpValue >> 56);
-
- }
-#endif
+ Unsafe.WriteUnaligned<Double>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -937,20 +798,23 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, SByte value) {
- int sizeOfType = sizeof(SByte);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, SByte value)
+ {
+ EnsureSafeToWrite(position, sizeof(SByte));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
- *((SByte*)pointer) = value;
+ *((SByte*)(pointer + _offset + position)) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -958,32 +822,24 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt16 value) {
+ public void Write(Int64 position, UInt16 value)
+ {
int sizeOfType = sizeof(UInt16);
EnsureSafeToWrite(position, sizeOfType);
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((UInt16*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- }
-#endif
+ Unsafe.WriteUnaligned<UInt16>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -991,35 +847,23 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt32 value) {
- int sizeOfType = sizeof(UInt32);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, UInt32 value)
+ {
+ EnsureSafeToWrite(position, sizeof(UInt32));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((UInt32*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- }
-#endif
-
+ Unsafe.WriteUnaligned<UInt32>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1027,38 +871,23 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public void Write(Int64 position, UInt64 value) {
- int sizeOfType = sizeof(UInt64);
- EnsureSafeToWrite(position, sizeOfType);
+ public void Write(Int64 position, UInt64 value)
+ {
+ EnsureSafeToWrite(position, sizeof(UInt64));
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- pointer += (_offset + position);
-#if ALIGN_ACCESS
- // check if pointer is aligned
- if (((int)pointer & (sizeOfType - 1)) == 0) {
-#endif
- *((UInt64*)pointer) = value;
-#if ALIGN_ACCESS
- }
- else {
- *(pointer) = (byte)value;
- *(pointer + 1) = (byte)(value >> 8);
- *(pointer + 2) = (byte)(value >> 16);
- *(pointer + 3) = (byte)(value >> 24);
- *(pointer + 4) = (byte)(value >> 32);
- *(pointer + 5) = (byte)(value >> 40);
- *(pointer + 6) = (byte)(value >> 48);
- *(pointer + 7) = (byte)(value >> 56);
- }
-#endif
-
+ Unsafe.WriteUnaligned<UInt64>(pointer + _offset + position, value);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1070,26 +899,33 @@ namespace System.IO {
// though this is number is JIT and architecture dependent). As such, it is best to use
// the WriteX methods for small standard types such as ints, longs, bools, etc.
- public void Write<T>(Int64 position, ref T structure) where T : struct {
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ public void Write<T>(Int64 position, ref T structure) where T : struct
+ {
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanWrite) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
+ if (!CanWrite)
+ {
+ throw new NotSupportedException(SR.NotSupported_Writing);
}
UInt32 sizeOfT = Marshal.SizeOfType(typeof(T));
- if (position > _capacity - sizeOfT) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfT)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", typeof(T).FullName), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, typeof (T).FullName), nameof(position));
}
}
@@ -1099,52 +935,66 @@ namespace System.IO {
// Writes 'count' structs of type T from 'array' (starting at 'offset') into unmanaged memory.
- public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct {
- if (array == null) {
+ public void WriteArray<T>(Int64 position, T[] array, Int32 offset, Int32 count) where T : struct
+ {
+ if (array == null)
+ {
throw new ArgumentNullException(nameof(array), "Buffer cannot be null.");
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (array.Length - offset < count) {
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetAndLengthOutOfBounds"));
+ if (array.Length - offset < count)
+ {
+ throw new ArgumentException(SR.Argument_OffsetAndLengthOutOfBounds);
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (position >= Capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position >= Capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
Contract.EndContractBlock();
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanWrite) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
+ if (!CanWrite)
+ {
+ throw new NotSupportedException(SR.NotSupported_Writing);
}
_buffer.WriteArray<T>((UInt64)(_offset + position), array, offset, count);
}
- private byte InternalReadByte(Int64 position) {
+ private byte InternalReadByte(Int64 position)
+ {
Debug.Assert(CanRead, "UMA not readable");
Debug.Assert(position >= 0, "position less than 0");
Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
byte result;
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- result = *((byte*)(pointer + _offset + position));
+ result = *(pointer + _offset + position);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
@@ -1152,67 +1002,85 @@ namespace System.IO {
return result;
}
- private void InternalWrite(Int64 position, byte value) {
+ private void InternalWrite(Int64 position, byte value)
+ {
Debug.Assert(CanWrite, "UMA not writable");
Debug.Assert(position >= 0, "position less than 0");
Debug.Assert(position <= _capacity - sizeof(byte), "position is greater than capacity - sizeof(byte)");
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
- *((byte*)(pointer + _offset + position)) = value;
+ *(pointer + _offset + position) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- private void EnsureSafeToRead(Int64 position, int sizeOfType) {
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ private void EnsureSafeToRead(Int64 position, int sizeOfType)
+ {
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanRead) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Reading"));
+ if (!CanRead)
+ {
+ throw new NotSupportedException(SR.NotSupported_Reading);
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (position > _capacity - sizeOfType) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfType)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToRead"), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Argument_NotEnoughBytesToRead, nameof(position));
}
}
}
- private void EnsureSafeToWrite(Int64 position, int sizeOfType) {
- if (!_isOpen) {
- throw new ObjectDisposedException("UnmanagedMemoryAccessor", Environment.GetResourceString("ObjectDisposed_ViewAccessorClosed"));
+ private void EnsureSafeToWrite(Int64 position, int sizeOfType)
+ {
+ if (!_isOpen)
+ {
+ throw new ObjectDisposedException("UnmanagedMemoryAccessor", SR.ObjectDisposed_ViewAccessorClosed);
}
- if (!CanWrite) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_Writing"));
+ if (!CanWrite)
+ {
+ throw new NotSupportedException(SR.NotSupported_Writing);
}
- if (position < 0) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (position < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Contract.EndContractBlock();
- if (position > _capacity - sizeOfType) {
- if (position >= _capacity) {
- throw new ArgumentOutOfRangeException(nameof(position), Environment.GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"));
+ if (position > _capacity - sizeOfType)
+ {
+ if (position >= _capacity)
+ {
+ throw new ArgumentOutOfRangeException(nameof(position), SR.ArgumentOutOfRange_PositionLessThanCapacityRequired);
}
- else {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotEnoughBytesToWrite", nameof(Byte)), nameof(position));
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_NotEnoughBytesToWrite, nameof(Byte)), nameof(position));
}
}
}
-
}
}
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
index 165b6d2b19..f21fe47371 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStream.cs
@@ -12,6 +12,7 @@
**
**
===========================================================*/
+
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
@@ -20,11 +21,11 @@ using System.Security;
using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-using System.Threading.Tasks;
-
+using System.Threading.Tasks;
-namespace System.IO {
+namespace System.IO
+{
/*
* This class is used to access a contiguous block of memory, likely outside
* the GC heap (or pinned in place in the GC heap, but a MemoryStream may
@@ -93,61 +94,76 @@ namespace System.IO {
private long _offset;
private FileAccess _access;
internal bool _isOpen;
- [NonSerialized]
+ [NonSerialized]
private Task<Int32> _lastReadTask; // The last successful task returned from ReadAsync
// Needed for subclasses that need to map a file, etc.
protected UnmanagedMemoryStream()
{
- unsafe {
+ unsafe
+ {
_mem = null;
}
_isOpen = false;
}
- public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length) {
+ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length)
+ {
Initialize(buffer, offset, length, FileAccess.Read);
}
- public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access) {
+ public UnmanagedMemoryStream(SafeBuffer buffer, long offset, long length, FileAccess access)
+ {
Initialize(buffer, offset, length, access);
}
- protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access) {
- if (buffer == null) {
+ protected void Initialize(SafeBuffer buffer, long offset, long length, FileAccess access)
+ {
+ if (buffer == null)
+ {
throw new ArgumentNullException(nameof(buffer));
}
- if (offset < 0) {
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (offset < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ if (length < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
}
- if (buffer.ByteLength < (ulong)(offset + length)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSafeBufferOffLen"));
+ if (buffer.ByteLength < (ulong)(offset + length))
+ {
+ throw new ArgumentException(SR.Argument_InvalidSafeBufferOffLen);
}
- if (access < FileAccess.Read || access > FileAccess.ReadWrite) {
+ if (access < FileAccess.Read || access > FileAccess.ReadWrite)
+ {
throw new ArgumentOutOfRangeException(nameof(access));
}
Contract.EndContractBlock();
- if (_isOpen) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
+ if (_isOpen)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
}
// check for wraparound
- unsafe {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
buffer.AcquirePointer(ref pointer);
- if ( (pointer + offset + length) < pointer) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
+ if ((pointer + offset + length) < pointer)
+ {
+ throw new ArgumentException(SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
}
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
buffer.ReleasePointer();
}
}
@@ -168,28 +184,28 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
+ public unsafe UnmanagedMemoryStream(byte* pointer, long length, long capacity, FileAccess access)
{
Initialize(pointer, length, capacity, access);
}
[CLSCompliant(false)]
- protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
+ protected unsafe void Initialize(byte* pointer, long length, long capacity, FileAccess access)
{
if (pointer == null)
throw new ArgumentNullException(nameof(pointer));
if (length < 0 || capacity < 0)
- throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((length < 0) ? nameof(length) : nameof(capacity), SR.ArgumentOutOfRange_NeedNonNegNum);
if (length > capacity)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_LengthGreaterThanCapacity);
Contract.EndContractBlock();
// Check for wraparound.
- if (((byte*) ((long)pointer + capacity)) < pointer)
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"));
+ if (((byte*)((long)pointer + capacity)) < pointer)
+ throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_UnmanagedMemStreamWrapAround);
if (access < FileAccess.Read || access > FileAccess.ReadWrite)
- throw new ArgumentOutOfRangeException(nameof(access), Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum);
if (_isOpen)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CalledTwice"));
+ throw new InvalidOperationException(SR.InvalidOperation_CalledTwice);
_mem = pointer;
_offset = 0;
@@ -199,17 +215,20 @@ namespace System.IO {
_isOpen = true;
}
- public override bool CanRead {
+ public override bool CanRead
+ {
[Pure]
get { return _isOpen && (_access & FileAccess.Read) != 0; }
}
- public override bool CanSeek {
+ public override bool CanSeek
+ {
[Pure]
get { return _isOpen; }
}
- public override bool CanWrite {
+ public override bool CanWrite
+ {
[Pure]
get { return _isOpen && (_access & FileAccess.Write) != 0; }
}
@@ -225,58 +244,66 @@ namespace System.IO {
base.Dispose(disposing);
}
- public override void Flush() {
+ public override void Flush()
+ {
if (!_isOpen) __Error.StreamIsClosed();
}
-
- public override Task FlushAsync(CancellationToken cancellationToken) {
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- try {
-
- Flush();
- return Task.CompletedTask;
-
- } catch(Exception ex) {
-
- return Task.FromException(ex);
- }
- }
-
-
- public override long Length {
- get {
+
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
+ if (cancellationToken.IsCancellationRequested)
+ return Task.FromCanceled(cancellationToken);
+
+ try
+ {
+ Flush();
+ return Task.CompletedTask;
+ }
+ catch (Exception ex)
+ {
+ return Task.FromException(ex);
+ }
+ }
+
+
+ public override long Length
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return Interlocked.Read(ref _length);
}
}
- public long Capacity {
- get {
+ public long Capacity
+ {
+ get
+ {
if (!_isOpen) __Error.StreamIsClosed();
return _capacity;
}
}
- public override long Position {
- get {
+ public override long Position
+ {
+ get
+ {
if (!CanSeek) __Error.StreamIsClosed();
Contract.EndContractBlock();
return Interlocked.Read(ref _position);
}
- set {
+ set
+ {
if (value < 0)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (!CanSeek) __Error.StreamIsClosed();
-
+
#if !BIT64
unsafe {
// On 32 bit machines, ensure we don't wrap around.
if (value > (long) Int32.MaxValue || _mem + value < _mem)
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
}
#endif
Interlocked.Exchange(ref _position, value);
@@ -284,54 +311,61 @@ namespace System.IO {
}
[CLSCompliant(false)]
- public unsafe byte* PositionPointer {
- get {
- if (_buffer != null) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ public unsafe byte* PositionPointer
+ {
+ get
+ {
+ if (_buffer != null)
+ {
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
}
// Use a temp to avoid a race
long pos = Interlocked.Read(ref _position);
if (pos > _capacity)
- throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_UMSPosition"));
- byte * ptr = _mem + pos;
+ throw new IndexOutOfRangeException(SR.IndexOutOfRange_UMSPosition);
+ byte* ptr = _mem + pos;
if (!_isOpen) __Error.StreamIsClosed();
return ptr;
}
- set {
+ set
+ {
if (_buffer != null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) __Error.StreamIsClosed();
// Note: subtracting pointers returns an Int64. Working around
// to avoid hitting compiler warning CS0652 on this line.
if (new IntPtr(value - _mem).ToInt64() > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
+ throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
if (value < _mem)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
+ throw new IOException(SR.IO_SeekBeforeBegin);
Interlocked.Exchange(ref _position, value - _mem);
}
}
- internal unsafe byte* Pointer {
- get {
+ internal unsafe byte* Pointer
+ {
+ get
+ {
if (_buffer != null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
return _mem;
}
}
-
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
if (!_isOpen) __Error.StreamIsClosed();
@@ -347,7 +381,7 @@ namespace System.IO {
if (n <= 0)
return 0;
- int nInt = (int) n; // Safe because n <= count, which is an Int32
+ 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.
@@ -383,35 +417,37 @@ namespace System.IO {
Interlocked.Exchange(ref _position, pos + n);
return nInt;
}
-
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Read(...)
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled<Int32>(cancellationToken);
-
- try {
-
- Int32 n = Read(buffer, offset, count);
+
+ if (cancellationToken.IsCancellationRequested)
+ return Task.FromCanceled<Int32>(cancellationToken);
+
+ try
+ {
+ Int32 n = Read(buffer, offset, count);
Task<Int32> t = _lastReadTask;
- return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
-
- } catch (Exception ex) {
-
- Debug.Assert(! (ex is OperationCanceledException));
- return Task.FromException<Int32>(ex);
- }
- }
-
- public override int ReadByte() {
+ return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<Int32>(n));
+ }
+ catch (Exception ex)
+ {
+ Debug.Assert(!(ex is OperationCanceledException));
+ return Task.FromException<Int32>(ex);
+ }
+ }
+
+ public override int ReadByte()
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
@@ -421,56 +457,65 @@ namespace System.IO {
return -1;
Interlocked.Exchange(ref _position, pos + 1);
int result;
- if (_buffer != null) {
- unsafe {
+ if (_buffer != null)
+ {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
result = *(pointer + pos + _offset);
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- else {
- unsafe {
+ else
+ {
+ unsafe
+ {
result = _mem[pos];
}
}
return result;
}
- public override long Seek(long offset, SeekOrigin loc) {
+ public override long Seek(long offset, SeekOrigin loc)
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (offset > UnmanagedMemStreamMaxLength)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"));
- switch(loc) {
- case SeekOrigin.Begin:
- if (offset < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- Interlocked.Exchange(ref _position, offset);
- break;
-
- case SeekOrigin.Current:
- long pos = Interlocked.Read(ref _position);
- if (offset + pos < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- Interlocked.Exchange(ref _position, offset + pos);
- break;
-
- case SeekOrigin.End:
- long len = Interlocked.Read(ref _length);
- if (len + offset < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
- Interlocked.Exchange(ref _position, len + offset);
- break;
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_UnmanagedMemStreamLength);
+ switch (loc)
+ {
+ case SeekOrigin.Begin:
+ if (offset < 0)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ Interlocked.Exchange(ref _position, offset);
+ break;
+
+ case SeekOrigin.Current:
+ long pos = Interlocked.Read(ref _position);
+ if (offset + pos < 0)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ Interlocked.Exchange(ref _position, offset + pos);
+ break;
+
+ case SeekOrigin.End:
+ long len = Interlocked.Read(ref _length);
+ if (len + offset < 0)
+ throw new IOException(SR.IO_SeekBeforeBegin);
+ Interlocked.Exchange(ref _position, len + offset);
+ break;
+
+ default:
+ throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
long finalPos = Interlocked.Read(ref _position);
@@ -478,40 +523,45 @@ namespace System.IO {
return finalPos;
}
- public override void SetLength(long value) {
+ public override void SetLength(long value)
+ {
if (value < 0)
- throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
if (_buffer != null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UmsSafeBuffer"));
+ throw new NotSupportedException(SR.NotSupported_UmsSafeBuffer);
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
if (value > _capacity)
- throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ throw new IOException(SR.IO_FixedCapacity);
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
- if (value > len) {
- unsafe {
- Buffer.ZeroMemory(_mem+len, value-len);
+ if (value > len)
+ {
+ unsafe
+ {
+ Buffer.ZeroMemory(_mem + len, value - len);
}
}
Interlocked.Exchange(ref _length, value);
- if (pos > value) {
+ if (pos > value)
+ {
Interlocked.Exchange(ref _position, value);
- }
+ }
}
- public override void Write(byte[] buffer, int offset, int count) {
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+ public override void Write(byte[] buffer, int offset, int count)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
if (!_isOpen) __Error.StreamIsClosed();
@@ -522,23 +572,28 @@ namespace System.IO {
long n = pos + count;
// Check for overflow
if (n < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
+ throw new IOException(SR.IO_StreamTooLong);
- if (n > _capacity) {
- throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ if (n > _capacity)
+ {
+ throw new NotSupportedException(SR.IO_FixedCapacity);
}
- if (_buffer == null) {
+ if (_buffer == null)
+ {
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
- if (pos > len) {
- unsafe {
- Buffer.ZeroMemory(_mem+len, pos-len);
+ if (pos > len)
+ {
+ unsafe
+ {
+ Buffer.ZeroMemory(_mem + len, pos - len);
}
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
- if (n > len) {
+ if (n > len)
+ {
Interlocked.Exchange(ref _length, n);
}
}
@@ -552,7 +607,7 @@ namespace System.IO {
long bytesLeft = _capacity - pos;
if (bytesLeft < count)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
+ throw new ArgumentException(SR.Arg_BufferTooSmall);
}
byte* pointer = null;
@@ -579,57 +634,62 @@ namespace System.IO {
Interlocked.Exchange(ref _position, n);
return;
}
-
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
- if (buffer==null)
- throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
+
+ public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
+ if (buffer == null)
+ throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
- throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock(); // contract validation copied from Write(..)
-
- if (cancellationToken.IsCancellationRequested)
- return Task.FromCanceled(cancellationToken);
-
- try {
-
- Write(buffer, offset, count);
- return Task.CompletedTask;
-
- } catch (Exception ex) {
-
- Debug.Assert(! (ex is OperationCanceledException));
- return Task.FromException<Int32>(ex);
- }
- }
-
-
- public override void WriteByte(byte value) {
+
+ if (cancellationToken.IsCancellationRequested)
+ return Task.FromCanceled(cancellationToken);
+
+ try
+ {
+ Write(buffer, offset, count);
+ return Task.CompletedTask;
+ }
+ catch (Exception ex)
+ {
+ Debug.Assert(!(ex is OperationCanceledException));
+ return Task.FromException<Int32>(ex);
+ }
+ }
+
+
+ public override void WriteByte(byte value)
+ {
if (!_isOpen) __Error.StreamIsClosed();
if (!CanWrite) __Error.WriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
long n = pos + 1;
- if (pos >= len) {
+ if (pos >= len)
+ {
// Check for overflow
if (n < 0)
- throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
-
+ throw new IOException(SR.IO_StreamTooLong);
+
if (n > _capacity)
- throw new NotSupportedException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ throw new NotSupportedException(SR.IO_FixedCapacity);
// Check to see whether we are now expanding the stream and must
// zero any memory in the middle.
// don't do if created from SafeBuffer
- if (_buffer == null) {
- if (pos > len) {
- unsafe {
- Buffer.ZeroMemory(_mem+len, pos-len);
+ if (_buffer == null)
+ {
+ if (pos > len)
+ {
+ unsafe
+ {
+ Buffer.ZeroMemory(_mem + len, pos - len);
}
}
@@ -638,24 +698,31 @@ namespace System.IO {
}
}
- if (_buffer != null) {
- unsafe {
+ if (_buffer != null)
+ {
+ unsafe
+ {
byte* pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
_buffer.AcquirePointer(ref pointer);
*(pointer + pos + _offset) = value;
}
- finally {
- if (pointer != null) {
+ finally
+ {
+ if (pointer != null)
+ {
_buffer.ReleasePointer();
}
}
}
}
- else {
- unsafe {
- _mem[pos] = value;
+ else
+ {
+ unsafe
+ {
+ _mem[pos] = value;
}
}
Interlocked.Exchange(ref _position, n);
diff --git a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
index 99b257ea56..86e4707dfd 100644
--- a/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
+++ b/src/mscorlib/src/System/IO/UnmanagedMemoryStreamWrapper.cs
@@ -18,94 +18,117 @@ using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
-namespace System.IO {
+namespace System.IO
+{
// Needed for backwards compatibility with V1.x usages of the
// ResourceManager, where a MemoryStream is now returned as an
// UnmanagedMemoryStream from ResourceReader.
- internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream {
+ internal sealed class UnmanagedMemoryStreamWrapper : MemoryStream
+ {
private UnmanagedMemoryStream _unmanagedStream;
-
- internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream) {
+
+ internal UnmanagedMemoryStreamWrapper(UnmanagedMemoryStream stream)
+ {
_unmanagedStream = stream;
}
-
- public override bool CanRead {
+
+ public override bool CanRead
+ {
[Pure]
get { return _unmanagedStream.CanRead; }
}
-
- public override bool CanSeek {
+
+ public override bool CanSeek
+ {
[Pure]
get { return _unmanagedStream.CanSeek; }
}
-
- public override bool CanWrite {
+
+ public override bool CanWrite
+ {
[Pure]
get { return _unmanagedStream.CanWrite; }
}
-
+
protected override void Dispose(bool disposing)
{
- try {
+ try
+ {
if (disposing)
_unmanagedStream.Close();
}
- finally {
+ finally
+ {
base.Dispose(disposing);
}
}
-
- public override void Flush() {
+
+ public override void Flush()
+ {
_unmanagedStream.Flush();
}
-
- public override byte[] GetBuffer() {
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
+
+ public override byte[] GetBuffer()
+ {
+ throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
}
- public override bool TryGetBuffer(out ArraySegment<byte> buffer) {
+ public override bool TryGetBuffer(out ArraySegment<byte> buffer)
+ {
buffer = default(ArraySegment<byte>);
return false;
}
- public override int Capacity {
- get {
- return (int) _unmanagedStream.Capacity;
+ public override int Capacity
+ {
+ get
+ {
+ return (int)_unmanagedStream.Capacity;
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
- set {
- throw new IOException(Environment.GetResourceString("IO.IO_FixedCapacity"));
+ set
+ {
+ throw new IOException(SR.IO_FixedCapacity);
}
- }
-
- public override long Length {
- get {
+ }
+
+ public override long Length
+ {
+ get
+ {
return _unmanagedStream.Length;
}
}
- public override long Position {
- get {
+ public override long Position
+ {
+ get
+ {
return _unmanagedStream.Position;
}
- set {
+ set
+ {
_unmanagedStream.Position = value;
}
}
-
- public override int Read([In, Out] byte[] buffer, int offset, int count) {
+
+ public override int Read([In, Out] byte[] buffer, int offset, int count)
+ {
return _unmanagedStream.Read(buffer, offset, count);
}
-
- public override int ReadByte() {
+
+ public override int ReadByte()
+ {
return _unmanagedStream.ReadByte();
}
-
- public override long Seek(long offset, SeekOrigin loc) {
+
+ public override long Seek(long offset, SeekOrigin loc)
+ {
return _unmanagedStream.Seek(offset, loc);
}
- public unsafe override byte[] ToArray() {
+ public unsafe override byte[] ToArray()
+ {
if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
if (!_unmanagedStream.CanRead) __Error.ReadNotSupported();
@@ -113,31 +136,34 @@ namespace System.IO {
Buffer.Memcpy(buffer, 0, _unmanagedStream.Pointer, 0, (int)_unmanagedStream.Length);
return buffer;
}
-
- public override void Write(byte[] buffer, int offset, int count) {
+
+ public override void Write(byte[] buffer, int offset, int count)
+ {
_unmanagedStream.Write(buffer, offset, count);
}
-
- public override void WriteByte(byte value) {
+
+ public override void WriteByte(byte value)
+ {
_unmanagedStream.WriteByte(value);
}
-
+
// Writes this MemoryStream to another stream.
- public unsafe override void WriteTo(Stream stream) {
- if (stream==null)
- throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
+ public unsafe override void WriteTo(Stream stream)
+ {
+ if (stream == null)
+ throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
Contract.EndContractBlock();
if (!_unmanagedStream._isOpen) __Error.StreamIsClosed();
if (!CanRead) __Error.ReadNotSupported();
byte[] buffer = ToArray();
-
+
stream.Write(buffer, 0, buffer.Length);
}
- public override void SetLength(Int64 value) {
-
+ public override void SetLength(Int64 value)
+ {
// This was probably meant to call _unmanagedStream.SetLength(value), but it was forgotten in V.4.0.
// Now this results in a call to the base which touches the underlying array which is never actually used.
// We cannot fix it due to compat now, but we should fix this at the next SxS release oportunity.
@@ -145,26 +171,26 @@ namespace System.IO {
}
- public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) {
-
+ public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
+ {
// The parameter checks must be in sync with the base version:
if (destination == null)
throw new ArgumentNullException(nameof(destination));
-
+
if (bufferSize <= 0)
- throw new ArgumentOutOfRangeException(nameof(bufferSize), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum);
if (!CanRead && !CanWrite)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
if (!destination.CanRead && !destination.CanWrite)
- throw new ObjectDisposedException(nameof(destination), Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+ throw new ObjectDisposedException(nameof(destination), SR.ObjectDisposed_StreamClosed);
if (!CanRead)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
+ throw new NotSupportedException(SR.NotSupported_UnreadableStream);
if (!destination.CanWrite)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
+ throw new NotSupportedException(SR.NotSupported_UnwritableStream);
Contract.EndContractBlock();
@@ -172,23 +198,22 @@ namespace System.IO {
}
- public override Task FlushAsync(CancellationToken cancellationToken) {
-
+ public override Task FlushAsync(CancellationToken cancellationToken)
+ {
return _unmanagedStream.FlushAsync(cancellationToken);
}
- public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
+ public override Task<Int32> ReadAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken);
}
- public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken) {
-
+ public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
+ {
return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken);
}
-
} // class UnmanagedMemoryStreamWrapper
} // namespace
diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs
index 955ddbec63..70f83261ed 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -23,46 +23,56 @@ using System.Globalization;
using System.Security;
using System.Diagnostics.Contracts;
-namespace System.IO {
+namespace System.IO
+{
[Pure]
internal static class __Error
{
- internal static void EndOfFile() {
- throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF"));
+ internal static void EndOfFile()
+ {
+ throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF);
}
- internal static void FileNotOpen() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed"));
+ internal static void FileNotOpen()
+ {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed);
}
-
- internal static void StreamIsClosed() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
+
+ internal static void StreamIsClosed()
+ {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed);
}
-
- internal static void MemoryStreamNotExpandable() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable"));
+
+ internal static void MemoryStreamNotExpandable()
+ {
+ throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
}
-
- internal static void ReaderClosed() {
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed"));
+
+ internal static void ReaderClosed()
+ {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
- internal static void ReadNotSupported() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
+ internal static void ReadNotSupported()
+ {
+ throw new NotSupportedException(SR.NotSupported_UnreadableStream);
}
- internal static void WrongAsyncResult() {
- throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult"));
+ internal static void WrongAsyncResult()
+ {
+ throw new ArgumentException(SR.Arg_WrongAsyncResult);
}
- internal static void EndReadCalledTwice() {
+ internal static void EndReadCalledTwice()
+ {
// Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple);
}
- internal static void EndWriteCalledTwice() {
+ internal static void EndWriteCalledTwice()
+ {
// Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple"));
+ throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
}
// Given a possible fully qualified path, ensure that we have path
@@ -71,7 +81,6 @@ namespace System.IO {
// directory name.
internal static String GetDisplayablePath(String path, bool isInvalidPath)
{
-
if (String.IsNullOrEmpty(path))
return String.Empty;
@@ -81,7 +90,8 @@ namespace System.IO {
return path;
if (PathInternal.IsDirectorySeparator(path[0]) && PathInternal.IsDirectorySeparator(path[1]))
isFullyQualified = true;
- else if (path[1] == Path.VolumeSeparatorChar) {
+ else if (path[1] == Path.VolumeSeparatorChar)
+ {
isFullyQualified = true;
}
@@ -89,26 +99,32 @@ namespace System.IO {
return path;
bool safeToReturn = false;
- try {
- if (!isInvalidPath) {
+ try
+ {
+ if (!isInvalidPath)
+ {
safeToReturn = true;
}
}
- catch (SecurityException) {
+ catch (SecurityException)
+ {
}
- catch (ArgumentException) {
+ catch (ArgumentException)
+ {
// ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters
// inside FileIOPermission.AddPathList
}
- catch (NotSupportedException) {
+ catch (NotSupportedException)
+ {
// paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown
// from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path
// beyond string index position 1.
}
-
- if (!safeToReturn) {
+
+ if (!safeToReturn)
+ {
if (PathInternal.IsDirectorySeparator(path[path.Length - 1]))
- path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName");
+ path = SR.IO_NoPermissionToDirectoryName;
else
path = Path.GetFileName(path);
}
@@ -116,81 +132,85 @@ namespace System.IO {
return path;
}
- internal static void WinIOError() {
+ 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 maybeFullPath) {
+ internal static void WinIOError(int errorCode, String maybeFullPath)
+ {
// This doesn't have to be perfect, but is a perf optimization.
bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME;
String str = GetDisplayablePath(maybeFullPath, isInvalidPath);
- switch (errorCode) {
- case Win32Native.ERROR_FILE_NOT_FOUND:
- if (str.Length == 0)
- throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound"));
- else
- throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str);
-
- case Win32Native.ERROR_PATH_NOT_FOUND:
- if (str.Length == 0)
- throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName"));
- else
- throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str));
-
- case Win32Native.ERROR_ACCESS_DENIED:
- if (str.Length == 0)
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"));
- else
- throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str));
-
- case Win32Native.ERROR_ALREADY_EXISTS:
- if (str.Length == 0)
- goto default;
- throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_FILENAME_EXCED_RANGE:
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
-
- case Win32Native.ERROR_INVALID_DRIVE:
- throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str));
-
- case Win32Native.ERROR_INVALID_PARAMETER:
- throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_SHARING_VIOLATION:
- if (str.Length == 0)
- throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
- else
- throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_FILE_EXISTS:
- if (str.Length == 0)
- goto default;
- throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
-
- case Win32Native.ERROR_OPERATION_ABORTED:
- throw new OperationCanceledException();
-
- default:
- throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+ 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), maybeFullPath);
+
+ case Win32Native.ERROR_FILENAME_EXCED_RANGE:
+ throw new PathTooLongException(SR.IO_PathTooLong);
+
+ 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), maybeFullPath);
+
+ case Win32Native.ERROR_SHARING_VIOLATION:
+ if (str.Length == 0)
+ throw new IOException(SR.IO_SharingViolation_NoFileName, Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+ else
+ throw new IOException(SR.Format(SR.IO_SharingViolation_File, str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+
+ case Win32Native.ERROR_FILE_EXISTS:
+ if (str.Length == 0)
+ goto default;
+ throw new IOException(SR.Format(SR.IO_FileExists_Name, str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
+
+ case Win32Native.ERROR_OPERATION_ABORTED:
+ throw new OperationCanceledException();
+
+ default:
+ throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
}
}
-
- internal static void WriteNotSupported() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
+
+ internal static void WriteNotSupported()
+ {
+ throw new NotSupportedException(SR.NotSupported_UnwritableStream);
}
// From WinError.h
internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND;
internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND;
- internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
+ internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER;
}
}
diff --git a/src/mscorlib/src/System/IO/__HResults.cs b/src/mscorlib/src/System/IO/__HResults.cs
index e19f28f833..633c3538c5 100644
--- a/src/mscorlib/src/System/IO/__HResults.cs
+++ b/src/mscorlib/src/System/IO/__HResults.cs
@@ -11,8 +11,11 @@
//
//
//===========================================================================*/
-namespace System.IO {
- using System;
+
+using System;
+
+namespace System.IO
+{
// Only static data no need to serialize
internal static class __HResults
{
diff --git a/src/mscorlib/src/System/IObserver.cs b/src/mscorlib/src/System/IObserver.cs
deleted file mode 100644
index 39e123de8d..0000000000
--- a/src/mscorlib/src/System/IObserver.cs
+++ /dev/null
@@ -1,13 +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.
-
-namespace System
-{
- public interface IObserver<in T>
- {
- void OnNext(T value);
- void OnError(Exception error);
- void OnCompleted();
- }
-}
diff --git a/src/mscorlib/src/System/IProgress.cs b/src/mscorlib/src/System/IProgress.cs
deleted file mode 100644
index 724c7bdce9..0000000000
--- a/src/mscorlib/src/System/IProgress.cs
+++ /dev/null
@@ -1,15 +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.
-
-namespace System
-{
- /// <summary>Defines a provider for progress updates.</summary>
- /// <typeparam name="T">The type of progress update value.</typeparam>
- public interface IProgress<in T>
- {
- /// <summary>Reports a progress update.</summary>
- /// <param name="value">The value of the updated progress.</param>
- void Report(T value);
- }
-}
diff --git a/src/mscorlib/src/System/IServiceObjectProvider.cs b/src/mscorlib/src/System/IServiceObjectProvider.cs
deleted file mode 100644
index feb1143487..0000000000
--- a/src/mscorlib/src/System/IServiceObjectProvider.cs
+++ /dev/null
@@ -1,16 +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.
-
-namespace System {
-
- using System;
- using System.Runtime.InteropServices;
-
-
- public interface IServiceProvider
- {
- // Interface does not need to be marked with the serializable attribute
- Object GetService(Type serviceType);
- }
-}
diff --git a/src/mscorlib/src/System/IndexOutOfRangeException.cs b/src/mscorlib/src/System/IndexOutOfRangeException.cs
deleted file mode 100644
index 4969c2b86d..0000000000
--- a/src/mscorlib/src/System/IndexOutOfRangeException.cs
+++ /dev/null
@@ -1,41 +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 class for invalid array indices.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class IndexOutOfRangeException : SystemException
- {
- public IndexOutOfRangeException()
- : base(SR.Arg_IndexOutOfRangeException)
- {
- HResult = __HResults.COR_E_INDEXOUTOFRANGE;
- }
-
- public IndexOutOfRangeException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_INDEXOUTOFRANGE;
- }
-
- public IndexOutOfRangeException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_INDEXOUTOFRANGE;
- }
-
- internal IndexOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/InsufficientExecutionStackException.cs b/src/mscorlib/src/System/InsufficientExecutionStackException.cs
deleted file mode 100644
index b9a4a12ddd..0000000000
--- a/src/mscorlib/src/System/InsufficientExecutionStackException.cs
+++ /dev/null
@@ -1,32 +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.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class InsufficientExecutionStackException : SystemException
- {
- public InsufficientExecutionStackException()
- : base(SR.Arg_InsufficientExecutionStackException)
- {
- HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
- }
-
- public InsufficientExecutionStackException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
- }
-
- public InsufficientExecutionStackException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
- }
-
- internal InsufficientExecutionStackException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/InsufficientMemoryException.cs b/src/mscorlib/src/System/InsufficientMemoryException.cs
index 448a061821..eb5e4d7430 100644
--- a/src/mscorlib/src/System/InsufficientMemoryException.cs
+++ b/src/mscorlib/src/System/InsufficientMemoryException.cs
@@ -16,30 +16,35 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
public sealed class InsufficientMemoryException : OutOfMemoryException
{
- public InsufficientMemoryException()
- : base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory)) {
- SetErrorCode(__HResults.COR_E_INSUFFICIENTMEMORY);
+ public InsufficientMemoryException()
+ : base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory))
+ {
+ HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
}
-
- public InsufficientMemoryException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INSUFFICIENTMEMORY);
+
+ public InsufficientMemoryException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
}
-
- public InsufficientMemoryException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_INSUFFICIENTMEMORY);
+
+ public InsufficientMemoryException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
}
- private InsufficientMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ private InsufficientMemoryException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/Int16.cs b/src/mscorlib/src/System/Int16.cs
index a5e62233e4..69f71af278 100644
--- a/src/mscorlib/src/System/Int16.cs
+++ b/src/mscorlib/src/System/Int16.cs
@@ -12,47 +12,54 @@
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [Serializable]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int16 : IComparable, IFormattable, IConvertible
- , IComparable<Int16>, IEquatable<Int16>
+ , IComparable<Int16>, IEquatable<Int16>
{
internal short m_value;
-
+
public const short MaxValue = (short)0x7FFF;
public const short MinValue = unchecked((short)0x8000);
-
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int16, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
-
- if (value is Int16) {
+
+ if (value is Int16)
+ {
return m_value - ((Int16)value).m_value;
}
-
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt16"));
+
+ throw new ArgumentException(SR.Arg_MustBeInt16);
}
- public int CompareTo(Int16 value) {
+ public int CompareTo(Int16 value)
+ {
return m_value - value;
}
-
- public override bool Equals(Object obj) {
- if (!(obj is Int16)) {
+
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Int16))
+ {
return false;
}
return m_value == ((Int16)obj).m_value;
@@ -65,199 +72,220 @@ namespace System {
}
// Returns a HashCode for the Int16
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return ((int)((ushort)m_value) | (((int)m_value) << 16));
}
-
- public override String ToString() {
+
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
-
- public String ToString(IFormatProvider provider) {
+
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
- }
+ }
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
- }
-
- public String ToString(String format, IFormatProvider provider) {
+ }
+
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
- private String ToString(String format, NumberFormatInfo info) {
+ private String ToString(String format, NumberFormatInfo info)
+ {
Contract.Ensures(Contract.Result<String>() != null);
- if (m_value<0 && format!=null && format.Length>0 && (format[0]=='X' || format[0]=='x')) {
+ if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
+ {
uint temp = (uint)(m_value & 0x0000FFFF);
- return Number.FormatUInt32(temp,format, info);
+ return Number.FormatUInt32(temp, format, info);
}
return Number.FormatInt32(m_value, format, info);
}
-
- public static short Parse(String s) {
+
+ public static short Parse(String s)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
- public static short Parse(String s, NumberStyles style) {
+
+ public static short Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
- public static short Parse(String s, IFormatProvider provider) {
+ public static short Parse(String s, IFormatProvider provider)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
- public static short Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static short Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
-
- private static short Parse(String s, NumberStyles style, NumberFormatInfo info) {
+ private static short Parse(String s, NumberStyles style, NumberFormatInfo info)
+ {
int i = 0;
- try {
+ try
+ {
i = Number.ParseInt32(s, style, info);
}
- catch(OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int16"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_Int16, e);
}
// We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result
// for negative numbers
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number
- if ((i < 0) || (i > UInt16.MaxValue)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // We are parsing a hexadecimal number
+ if ((i < 0) || (i > UInt16.MaxValue))
+ {
+ throw new OverflowException(SR.Overflow_Int16);
}
return (short)i;
}
-
- if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_Int16"));
+
+ if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Int16);
return (short)i;
}
- public static bool TryParse(String s, out Int16 result) {
+ public static bool TryParse(String s, out Int16 result)
+ {
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result) {
+ public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result)
+ {
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(String s, NumberStyles style, NumberFormatInfo info, out Int16 result)
+ {
result = 0;
int i;
- if (!Number.TryParseInt32(s, style, info, out i)) {
+ if (!Number.TryParseInt32(s, style, info, out i))
+ {
return false;
}
// We need this check here since we don't allow signs to specified in hex numbers. So we fixup the result
// for negative numbers
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number
- if ((i < 0) || i > UInt16.MaxValue) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // We are parsing a hexadecimal number
+ if ((i < 0) || i > UInt16.MaxValue)
+ {
return false;
}
- result = (Int16) i;
+ result = (Int16)i;
return true;
}
-
- if (i < MinValue || i > MaxValue) {
+
+ if (i < MinValue || i > MaxValue)
+ {
return false;
}
- result = (Int16) i;
+ result = (Int16)i;
return true;
}
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Int16;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int16", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
-
}
}
diff --git a/src/mscorlib/src/System/Int32.cs b/src/mscorlib/src/System/Int32.cs
index 0e1ed56a41..90b70a9554 100644
--- a/src/mscorlib/src/System/Int32.cs
+++ b/src/mscorlib/src/System/Int32.cs
@@ -11,35 +11,39 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+
+using System;
+using System.Globalization;
+using System.Runtime;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [Serializable]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int32 : IComparable, IFormattable, IConvertible
- , IComparable<Int32>, IEquatable<Int32>
+ , IComparable<Int32>, IEquatable<Int32>
{
internal int m_value;
-
+
public const int MaxValue = 0x7fffffff;
public const int MinValue = unchecked((int)0x80000000);
-
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Int32, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is Int32) {
+ if (value is Int32)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
int i = (int)value;
@@ -47,19 +51,22 @@ namespace System {
if (m_value > i) return 1;
return 0;
}
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt32"));
+ throw new ArgumentException(SR.Arg_MustBeInt32);
}
- public int CompareTo(int value) {
+ public int CompareTo(int value)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
-
- public override bool Equals(Object obj) {
- if (!(obj is Int32)) {
+
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Int32))
+ {
return false;
}
return m_value == ((Int32)obj).m_value;
@@ -72,41 +79,48 @@ namespace System {
}
// The absolute value of the int contained.
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return m_value;
}
[Pure]
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
[Pure]
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
-
+
[Pure]
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
[Pure]
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[Pure]
- public static int Parse(String s) {
+ public static int Parse(String s)
+ {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
- public static int Parse(String s, NumberStyles style) {
+ public static int Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
}
@@ -116,16 +130,18 @@ namespace System {
// NumberFormatInfo is assumed.
//
[Pure]
- public static int Parse(String s, IFormatProvider provider) {
+ public static int Parse(String s, IFormatProvider provider)
+ {
return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
-
+
// Parses an integer from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[Pure]
- public static int Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static int Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
@@ -134,7 +150,8 @@ namespace System {
// than throwing exceptin if input is invalid
//
[Pure]
- public static bool TryParse(String s, out Int32 result) {
+ public static bool TryParse(String s, out Int32 result)
+ {
return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
@@ -142,7 +159,8 @@ namespace System {
// than throwing exceptin if input is invalid
//
[Pure]
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result) {
+ public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
@@ -150,84 +168,85 @@ namespace System {
//
// IConvertible implementation
//
-
+
[Pure]
- public TypeCode GetTypeCode() {
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Int32;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int32", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/Int64.cs b/src/mscorlib/src/System/Int64.cs
index 3520ede533..3d64362e30 100644
--- a/src/mscorlib/src/System/Int64.cs
+++ b/src/mscorlib/src/System/Int64.cs
@@ -11,20 +11,21 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [Serializable]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Int64 : IComparable, IFormattable, IConvertible
- , IComparable<Int64>, IEquatable<Int64>
+ , IComparable<Int64>, IEquatable<Int64>
{
internal long m_value;
-
+
public const long MaxValue = 0x7fffffffffffffffL;
public const long MinValue = unchecked((long)0x8000000000000000L);
@@ -34,11 +35,14 @@ namespace System {
// null is considered to be less than any instance.
// If object is not of type Int64, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is Int64) {
+ if (value is Int64)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
long i = (long)value;
@@ -46,19 +50,22 @@ namespace System {
if (m_value > i) return 1;
return 0;
}
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeInt64"));
+ throw new ArgumentException(SR.Arg_MustBeInt64);
}
- public int CompareTo(Int64 value) {
+ public int CompareTo(Int64 value)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
-
- public override bool Equals(Object obj) {
- if (!(obj is Int64)) {
+
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Int64))
+ {
return false;
}
return m_value == ((Int64)obj).m_value;
@@ -71,40 +78,48 @@ namespace System {
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return (unchecked((int)((long)m_value)) ^ (int)(m_value >> 32));
}
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
-
- public String ToString(IFormatProvider provider) {
+
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
}
-
- public String ToString(String format) {
+
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
- public static long Parse(String s) {
+ public static long Parse(String s)
+ {
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
- public static long Parse(String s, NumberStyles style) {
+
+ public static long Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo);
}
- public static long Parse(String s, IFormatProvider provider) {
+ public static long Parse(String s, IFormatProvider provider)
+ {
return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
@@ -113,16 +128,19 @@ namespace System {
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
- public static long Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static long Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
- public static Boolean TryParse(String s, out Int64 result) {
+ public static Boolean TryParse(String s, out Int64 result)
+ {
return Number.TryParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
- public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result) {
+ public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
@@ -130,83 +148,84 @@ namespace System {
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Int64;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Int64", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int64", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/IntPtr.cs b/src/mscorlib/src/System/IntPtr.cs
index dbddcd319a..28f1b1baa8 100644
--- a/src/mscorlib/src/System/IntPtr.cs
+++ b/src/mscorlib/src/System/IntPtr.cs
@@ -11,8 +11,8 @@
**
===========================================================*/
-namespace System {
-
+namespace System
+{
using System;
using System.Globalization;
using System.Runtime;
@@ -26,31 +26,31 @@ namespace System {
public struct IntPtr : IEquatable<IntPtr>, ISerializable
{
unsafe private void* m_value; // The compiler treats void* closest to uint hence explicit casts are required to preserve int behavior
-
+
public static readonly IntPtr Zero;
// fast way to compare IntPtr to (IntPtr)0 while IntPtr.Zero doesn't work due to slow statics access
[Pure]
internal unsafe bool IsNull()
{
- return (this.m_value == null);
+ return (m_value == null);
}
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(int value)
{
#if BIT64
- m_value = (void *)(long)value;
+ m_value = (void*)(long)value;
#else // !BIT64 (32)
m_value = (void *)value;
#endif
}
-
+
[System.Runtime.Versioning.NonVersionable]
public unsafe IntPtr(long value)
{
#if BIT64
- m_value = (void *)value;
+ m_value = (void*)value;
#else // !BIT64 (32)
m_value = (void *)checked((int)value);
#endif
@@ -63,30 +63,36 @@ namespace System {
m_value = value;
}
- private unsafe IntPtr(SerializationInfo info, StreamingContext context) {
+ private unsafe IntPtr(SerializationInfo info, StreamingContext context)
+ {
long l = info.GetInt64("value");
- if (Size==4 && (l>Int32.MaxValue || l<Int32.MinValue)) {
- throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue"));
+ if (Size == 4 && (l > Int32.MaxValue || l < Int32.MinValue))
+ {
+ throw new ArgumentException(SR.Serialization_InvalidPtrValue);
}
- m_value = (void *)l;
+ m_value = (void*)l;
}
- unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
#if BIT64
- info.AddValue("value", (long)(m_value));
+ info.AddValue("value", (long)(m_value));
#else // !BIT64 (32)
info.AddValue("value", (long)((int)m_value));
#endif
}
- public unsafe override bool Equals(Object obj) {
- if (obj is IntPtr) {
+ public unsafe override bool Equals(Object obj)
+ {
+ if (obj is IntPtr)
+ {
return (m_value == ((IntPtr)obj).m_value);
}
return false;
@@ -96,8 +102,9 @@ namespace System {
{
return m_value == other.m_value;
}
-
- public unsafe override int GetHashCode() {
+
+ public unsafe override int GetHashCode()
+ {
#if BIT64
long l = (long)m_value;
return (unchecked((int)l) ^ (int)(l >> 32));
@@ -107,38 +114,41 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe int ToInt32() {
+ public unsafe int ToInt32()
+ {
#if BIT64
- long l = (long)m_value;
- return checked((int)l);
+ long l = (long)m_value;
+ return checked((int)l);
#else // !BIT64 (32)
return (int)m_value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe long ToInt64() {
+ public unsafe long ToInt64()
+ {
#if BIT64
- return (long)m_value;
+ return (long)m_value;
#else // !BIT64 (32)
return (long)(int)m_value;
#endif
}
- public unsafe override String ToString() {
+ public unsafe override String ToString()
+ {
#if BIT64
- return ((long)m_value).ToString(CultureInfo.InvariantCulture);
+ return ((long)m_value).ToString(CultureInfo.InvariantCulture);
#else // !BIT64 (32)
return ((int)m_value).ToString(CultureInfo.InvariantCulture);
#endif
}
- public unsafe String ToString(String format)
+ public unsafe String ToString(String format)
{
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
- return ((long)m_value).ToString(format, CultureInfo.InvariantCulture);
+ return ((long)m_value).ToString(format, CultureInfo.InvariantCulture);
#else // !BIT64 (32)
return ((int)m_value).ToString(format, CultureInfo.InvariantCulture);
#endif
@@ -146,20 +156,20 @@ namespace System {
[System.Runtime.Versioning.NonVersionable]
- public static explicit operator IntPtr (int value)
+ public static explicit operator IntPtr(int value)
{
return new IntPtr(value);
}
[System.Runtime.Versioning.NonVersionable]
- public static explicit operator IntPtr (long value)
+ public static explicit operator IntPtr(long value)
{
return new IntPtr(value);
}
[CLSCompliant(false), ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
[System.Runtime.Versioning.NonVersionable]
- public static unsafe explicit operator IntPtr (void* value)
+ public static unsafe explicit operator IntPtr(void* value)
{
return new IntPtr(value);
}
@@ -172,34 +182,34 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe static explicit operator int (IntPtr value)
+ public unsafe static explicit operator int(IntPtr value)
{
#if BIT64
- long l = (long)value.m_value;
- return checked((int)l);
+ long l = (long)value.m_value;
+ return checked((int)l);
#else // !BIT64 (32)
return (int)value.m_value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe static explicit operator long (IntPtr value)
+ public unsafe static explicit operator long(IntPtr value)
{
#if BIT64
- return (long)value.m_value;
+ return (long)value.m_value;
#else // !BIT64 (32)
return (long)(int)value.m_value;
#endif
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool operator == (IntPtr value1, IntPtr value2)
+ public unsafe static bool operator ==(IntPtr value1, IntPtr value2)
{
return value1.m_value == value2.m_value;
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool operator != (IntPtr value1, IntPtr value2)
+ public unsafe static bool operator !=(IntPtr value1, IntPtr value2)
{
return value1.m_value != value2.m_value;
}
@@ -211,24 +221,26 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public static IntPtr operator +(IntPtr pointer, int offset)
+ public static IntPtr operator +(IntPtr pointer, int offset)
{
#if BIT64
- return new IntPtr(pointer.ToInt64() + offset);
+ return new IntPtr(pointer.ToInt64() + offset);
#else // !BIT64 (32)
return new IntPtr(pointer.ToInt32() + offset);
#endif
}
[System.Runtime.Versioning.NonVersionable]
- public static IntPtr Subtract(IntPtr pointer, int offset) {
+ public static IntPtr Subtract(IntPtr pointer, int offset)
+ {
return pointer - offset;
}
[System.Runtime.Versioning.NonVersionable]
- public static IntPtr operator -(IntPtr pointer, int offset) {
+ public static IntPtr operator -(IntPtr pointer, int offset)
+ {
#if BIT64
- return new IntPtr(pointer.ToInt64() - offset);
+ return new IntPtr(pointer.ToInt64() - offset);
#else // !BIT64 (32)
return new IntPtr(pointer.ToInt32() - offset);
#endif
@@ -241,13 +253,13 @@ namespace System {
get
{
#if BIT64
- return 8;
+ return 8;
#else // !BIT64 (32)
return 4;
#endif
}
}
-
+
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
diff --git a/src/mscorlib/src/System/Internal.cs b/src/mscorlib/src/System/Internal.cs
index b0860109d9..1534326921 100644
--- a/src/mscorlib/src/System/Internal.cs
+++ b/src/mscorlib/src/System/Internal.cs
@@ -10,6 +10,7 @@
**
**
===========================================================*/
+
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Collections.Generic;
@@ -22,13 +23,13 @@ using System.Threading.Tasks;
using System.Runtime.InteropServices.WindowsRuntime;
#endif // FEATURE_COMINTEROP
-[assembly:DefaultDependencyAttribute(LoadHint.Always)]
+[assembly: DefaultDependencyAttribute(LoadHint.Always)]
// mscorlib would like to have its literal strings frozen if possible
[assembly: System.Runtime.CompilerServices.StringFreezingAttribute()]
namespace System
{
- static class Internal
+ static class CommonlyUsedGenericInstantiations
{
// This method is purely an aid for NGen to statically deduce which
// instantiations to save in the ngen image.
@@ -44,7 +45,7 @@ namespace System
// instantiation closure process is driven by "fixup" references
// left in the final code stream.
[MethodImplAttribute(MethodImplOptions.NoOptimization)]
- static void CommonlyUsedGenericInstantiations()
+ static CommonlyUsedGenericInstantiations()
{
// Make absolutely sure we include some of the most common
// instantiations here in mscorlib's ngen image.
@@ -86,14 +87,14 @@ namespace System
new EnumEqualityComparer<System.Reflection.MemberTypes>();
// Microsoft.Expression.DesignModel
- new Dictionary<Object, KeyValuePair<Object,Object>>();
- new Dictionary<KeyValuePair<Object,Object>, Object>();
+ new Dictionary<Object, KeyValuePair<Object, Object>>();
+ new Dictionary<KeyValuePair<Object, Object>, Object>();
NullableHelper<Boolean>();
NullableHelper<Byte>();
NullableHelper<Char>();
- NullableHelper<DateTime>();
- NullableHelper<Decimal>();
+ NullableHelper<DateTime>();
+ NullableHelper<Decimal>();
NullableHelper<Double>();
NullableHelper<Guid>();
NullableHelper<Int16>();
@@ -127,7 +128,7 @@ namespace System
new KeyValuePair<Char, UInt16>('\0', UInt16.MinValue);
new KeyValuePair<UInt16, Double>(UInt16.MinValue, Double.MinValue);
new KeyValuePair<Object, Int32>(String.Empty, Int32.MinValue);
- new KeyValuePair<Int32, Int32>(Int32.MinValue, Int32.MinValue);
+ new KeyValuePair<Int32, Int32>(Int32.MinValue, Int32.MinValue);
SZArrayHelper<Boolean>(null);
SZArrayHelper<Byte>(null);
SZArrayHelper<DateTime>(null);
@@ -156,15 +157,15 @@ namespace System
#pragma warning restore 4014
}
- static T NullableHelper<T>() where T : struct
+ private static T NullableHelper<T>() where T : struct
{
- Nullable.Compare<T>(null, null);
- Nullable.Equals<T>(null, null);
+ Nullable.Compare<T>(null, null);
+ Nullable.Equals<T>(null, null);
Nullable<T> nullable = new Nullable<T>();
return nullable.GetValueOrDefault();
- }
+ }
- static void SZArrayHelper<T>(SZArrayHelper oSZArrayHelper)
+ private static void SZArrayHelper<T>(SZArrayHelper oSZArrayHelper)
{
// Instantiate common methods for IList implementation on Array
oSZArrayHelper.get_Count<T>();
@@ -174,20 +175,20 @@ namespace System
// System.Runtime.CompilerServices.AsyncVoidMethodBuilder
// System.Runtime.CompilerServices.TaskAwaiter
- static async void AsyncHelper<T>()
+ private static async void AsyncHelper<T>()
{
await Task.Delay(1);
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1[System.__Canon]
// System.Runtime.CompilerServices.TaskAwaiter'[System.__Canon]
- static async Task<String> AsyncHelper2<T>()
+ private static async Task<String> AsyncHelper2<T>()
{
return await Task.FromResult<string>("");
}
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder
// System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1[VoidTaskResult]
- static async Task AsyncHelper3()
+ private static async Task AsyncHelper3()
{
await Task.FromResult<string>("");
}
@@ -201,7 +202,7 @@ namespace System
// typed as matching instantiations of mscorlib copies of WinRT interfaces (IIterable<T>, IVector<T>,
// IMap<K, V>, ...) which is necessary to generate all required IL stubs.
- static void CommonlyUsedWinRTRedirectedInterfaceStubs()
+ private static void CommonlyUsedWinRTRedirectedInterfaceStubs()
{
WinRT_IEnumerable<byte>(null, null, null);
WinRT_IEnumerable<char>(null, null, null);
@@ -247,14 +248,14 @@ namespace System
WinRT_Nullable<double>();
}
- static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
+ private static void WinRT_IEnumerable<T>(IterableToEnumerableAdapter iterableToEnumerableAdapter, EnumerableToIterableAdapter enumerableToIterableAdapter, IIterable<T> iterable)
{
// instantiate stubs for the one method on IEnumerable<T> and the one method on IIterable<T>
iterableToEnumerableAdapter.GetEnumerator_Stub<T>();
enumerableToIterableAdapter.First_Stub<T>();
}
- static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
+ private static void WinRT_IList<T>(VectorToListAdapter vectorToListAdapter, VectorToCollectionAdapter vectorToCollectionAdapter, ListToVectorAdapter listToVectorAdapter, IVector<T> vector)
{
WinRT_IEnumerable<T>(null, null, null);
@@ -278,7 +279,7 @@ namespace System
listToVectorAdapter.Clear<T>();
}
- static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
+ private static void WinRT_IReadOnlyCollection<T>(VectorViewToReadOnlyCollectionAdapter vectorViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<T>(null, null, null);
@@ -286,7 +287,7 @@ namespace System
vectorViewToReadOnlyCollectionAdapter.Count<T>();
}
- static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
+ private static void WinRT_IReadOnlyList<T>(IVectorViewToIReadOnlyListAdapter vectorToListAdapter, IReadOnlyListToIVectorViewAdapter listToVectorAdapter, IVectorView<T> vectorView)
{
WinRT_IEnumerable<T>(null, null, null);
WinRT_IReadOnlyCollection<T>(null);
@@ -299,7 +300,7 @@ namespace System
listToVectorAdapter.Size<T>();
}
- static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
+ private static void WinRT_IDictionary<K, V>(MapToDictionaryAdapter mapToDictionaryAdapter, MapToCollectionAdapter mapToCollectionAdapter, DictionaryToMapAdapter dictionaryToMapAdapter, IMap<K, V> map)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
@@ -324,7 +325,7 @@ namespace System
dictionaryToMapAdapter.Clear<K, V>();
}
- static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
+ private static void WinRT_IReadOnlyDictionary<K, V>(IMapViewToIReadOnlyDictionaryAdapter mapToDictionaryAdapter, IReadOnlyDictionaryToIMapViewAdapter dictionaryToMapAdapter, IMapView<K, V> mapView, MapViewToReadOnlyCollectionAdapter mapViewToReadOnlyCollectionAdapter)
{
WinRT_IEnumerable<KeyValuePair<K, V>>(null, null, null);
WinRT_IReadOnlyCollection<KeyValuePair<K, V>>(null);
@@ -344,7 +345,7 @@ namespace System
dictionaryToMapAdapter.HasKey<K, V>(default(K));
}
- static void WinRT_Nullable<T>() where T : struct
+ private static void WinRT_Nullable<T>() where T : struct
{
Nullable<T> nullable = new Nullable<T>();
NullableMarshaler.ConvertToNative(ref nullable);
diff --git a/src/mscorlib/src/System/InvalidCastException.cs b/src/mscorlib/src/System/InvalidCastException.cs
deleted file mode 100644
index 01d92b2837..0000000000
--- a/src/mscorlib/src/System/InvalidCastException.cs
+++ /dev/null
@@ -1,44 +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 class for invalid cast conditions!
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class InvalidCastException : SystemException
- {
- public InvalidCastException()
- : base(SR.Arg_InvalidCastException)
- {
- HResult = __HResults.COR_E_INVALIDCAST;
- }
-
- public InvalidCastException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_INVALIDCAST;
- }
-
- public InvalidCastException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_INVALIDCAST;
- }
-
- public InvalidCastException(String message, int errorCode)
- : base(message)
- {
- HResult = errorCode;
- }
-
- protected InvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/InvalidOperationException.cs b/src/mscorlib/src/System/InvalidOperationException.cs
deleted file mode 100644
index 24a08c8089..0000000000
--- a/src/mscorlib/src/System/InvalidOperationException.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: Exception class for denoting an object was in a state that
-** made calling a method illegal.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class InvalidOperationException : SystemException
- {
- public InvalidOperationException()
- : base(SR.Arg_InvalidOperationException)
- {
- HResult = __HResults.COR_E_INVALIDOPERATION;
- }
-
- public InvalidOperationException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_INVALIDOPERATION;
- }
-
- public InvalidOperationException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_INVALIDOPERATION;
- }
-
- protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/InvalidProgramException.cs b/src/mscorlib/src/System/InvalidProgramException.cs
deleted file mode 100644
index 401b3a0ddb..0000000000
--- a/src/mscorlib/src/System/InvalidProgramException.cs
+++ /dev/null
@@ -1,41 +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 for programs with invalid IL or bad metadata.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class InvalidProgramException : SystemException
- {
- public InvalidProgramException()
- : base(SR.InvalidProgram_Default)
- {
- HResult = __HResults.COR_E_INVALIDPROGRAM;
- }
-
- public InvalidProgramException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_INVALIDPROGRAM;
- }
-
- public InvalidProgramException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_INVALIDPROGRAM;
- }
-
- internal InvalidProgramException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/InvalidTimeZoneException.cs b/src/mscorlib/src/System/InvalidTimeZoneException.cs
deleted file mode 100644
index 8f0751c426..0000000000
--- a/src/mscorlib/src/System/InvalidTimeZoneException.cs
+++ /dev/null
@@ -1,28 +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.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class InvalidTimeZoneException : Exception
- {
- public InvalidTimeZoneException()
- {
- }
-
- public InvalidTimeZoneException(String message)
- : base(message)
- {
- }
-
- public InvalidTimeZoneException(String message, Exception innerException)
- : base(message, innerException)
- {
- }
-
- protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Lazy.cs b/src/mscorlib/src/System/Lazy.cs
deleted file mode 100644
index 0ddd6da3a2..0000000000
--- a/src/mscorlib/src/System/Lazy.cs
+++ /dev/null
@@ -1,506 +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.
-#pragma warning disable 0420
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// --------------------------------------------------------------------------------------
-//
-// A class that provides a simple, lightweight implementation of lazy initialization,
-// obviating the need for a developer to implement a custom, thread-safe lazy initialization
-// solution.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System.Runtime;
-using System.Runtime.InteropServices;
-using System.Security;
-using System.Diagnostics;
-using System.Runtime.Serialization;
-using System.Threading;
-using System.Diagnostics.Contracts;
-using System.Runtime.ExceptionServices;
-
-namespace System
-{
- // Lazy<T> is generic, but not all of its state needs to be generic. Avoid creating duplicate
- // objects per instantiation by putting them here.
- internal static class LazyHelpers
- {
- // Dummy object used as the value of m_threadSafeObj if in PublicationOnly mode.
- internal static readonly object PUBLICATION_ONLY_SENTINEL = new object();
- }
-
- /// <summary>
- /// Provides support for lazy initialization.
- /// </summary>
- /// <typeparam name="T">Specifies the type of element being lazily initialized.</typeparam>
- /// <remarks>
- /// <para>
- /// By default, all public and protected members of <see cref="Lazy{T}"/> are thread-safe and may be used
- /// concurrently from multiple threads. These thread-safety guarantees may be removed optionally and per instance
- /// using parameters to the type's constructors.
- /// </para>
- /// </remarks>
- [Serializable]
- [DebuggerTypeProxy(typeof(System_LazyDebugView<>))]
- [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")]
- public class Lazy<T>
- {
-
-#region Inner classes
- /// <summary>
- /// wrapper class to box the initialized value, this is mainly created to avoid boxing/unboxing the value each time the value is called in case T is
- /// a value type
- /// </summary>
- [Serializable]
- class Boxed
- {
- internal Boxed(T value)
- {
- m_value = value;
- }
- internal T m_value;
- }
-
-
- /// <summary>
- /// Wrapper class to wrap the excpetion thrown by the value factory
- /// </summary>
- class LazyInternalExceptionHolder
- {
- internal ExceptionDispatchInfo m_edi;
- internal LazyInternalExceptionHolder(Exception ex)
- {
- m_edi = ExceptionDispatchInfo.Capture(ex);
- }
- }
-#endregion
-
- // A dummy delegate used as a :
- // 1- Flag to avoid recursive call to Value in None and ExecutionAndPublication modes in m_valueFactory
- // 2- Flag to m_threadSafeObj if ExecutionAndPublication mode and the value is known to be initialized
- static readonly Func<T> ALREADY_INVOKED_SENTINEL = delegate
- {
- Debug.Assert(false, "ALREADY_INVOKED_SENTINEL should never be invoked.");
- return default(T);
- };
-
- //null --> value is not created
- //m_value is Boxed --> the value is created, and m_value holds the value
- //m_value is LazyExceptionHolder --> it holds an exception
- private object m_boxed;
-
- // The factory delegate that returns the value.
- // In None and ExecutionAndPublication modes, this will be set to ALREADY_INVOKED_SENTINEL as a flag to avoid recursive calls
- [NonSerialized]
- private Func<T> m_valueFactory;
-
- // null if it is not thread safe mode
- // LazyHelpers.PUBLICATION_ONLY_SENTINEL if PublicationOnly mode
- // object if ExecutionAndPublication mode (may be ALREADY_INVOKED_SENTINEL if the value is already initialized)
- [NonSerialized]
- private object m_threadSafeObj;
-
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
- /// uses <typeparamref name="T"/>'s default constructor for lazy initialization.
- /// </summary>
- /// <remarks>
- /// An instance created with this constructor may be used concurrently from multiple threads.
- /// </remarks>
- public Lazy()
- : this(LazyThreadSafetyMode.ExecutionAndPublication)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that
- /// uses a pre-initialized specified value.
- /// </summary>
- /// <remarks>
- /// An instance created with this constructor should be usable by multiple threads
- // concurrently.
- /// </remarks>
- public Lazy(T value)
- {
- m_boxed = new Boxed(value);
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class that uses a
- /// specified initialization function.
- /// </summary>
- /// <param name="valueFactory">
- /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is
- /// needed.
- /// </param>
- /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is a null
- /// reference (Nothing in Visual Basic).</exception>
- /// <remarks>
- /// An instance created with this constructor may be used concurrently from multiple threads.
- /// </remarks>
- public Lazy(Func<T> valueFactory)
- : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication)
- {
- }
-
- /// <summary>
- /// 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="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
- /// </param>
- public Lazy(bool isThreadSafe) :
- this(isThreadSafe? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
- {
- }
-
- /// <summary>
- /// 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>
- /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
- public Lazy(LazyThreadSafetyMode mode)
- {
- m_threadSafeObj = GetObjectFromMode(mode);
- }
-
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class
- /// that uses a specified initialization function and a specified thread-safety mode.
- /// </summary>
- /// <param name="valueFactory">
- /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
- /// </param>
- /// <param name="isThreadSafe">true if this instance should be usable by multiple threads concurrently; false if the instance will only be used by one thread at a time.
- /// </param>
- /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
- /// a null reference (Nothing in Visual Basic).</exception>
- public Lazy(Func<T> valueFactory, bool isThreadSafe)
- : this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/> class
- /// that uses a specified initialization function and a specified thread-safety mode.
- /// </summary>
- /// <param name="valueFactory">
- /// The <see cref="T:System.Func{T}"/> invoked to produce the lazily-initialized value when it is needed.
- /// </param>
- /// <param name="mode">The lazy thread-safety mode.</param>
- /// <exception cref="System.ArgumentNullException"><paramref name="valueFactory"/> is
- /// a null reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid value.</exception>
- public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
- {
- if (valueFactory == null)
- throw new ArgumentNullException(nameof(valueFactory));
-
- m_threadSafeObj = GetObjectFromMode(mode);
- m_valueFactory = valueFactory;
- }
-
- /// <summary>
- /// Static helper function that returns an object based on the given mode. it also throws an exception if the mode is invalid
- /// </summary>
- private static object GetObjectFromMode(LazyThreadSafetyMode mode)
- {
- if (mode == LazyThreadSafetyMode.ExecutionAndPublication)
- return new object();
- else if (mode == LazyThreadSafetyMode.PublicationOnly)
- return LazyHelpers.PUBLICATION_ONLY_SENTINEL;
- else if (mode != LazyThreadSafetyMode.None)
- throw new ArgumentOutOfRangeException(nameof(mode), Environment.GetResourceString("Lazy_ctor_ModeInvalid"));
-
- return null; // None mode
- }
-
- /// <summary>Forces initialization during serialization.</summary>
- /// <param name="context">The StreamingContext for the serialization operation.</param>
- [OnSerializing]
- private void OnSerializing(StreamingContext context)
- {
- // Force initialization
- T dummy = Value;
- }
-
- /// <summary>Creates and returns a string representation of this instance.</summary>
- /// <returns>The result of calling <see cref="System.Object.ToString"/> on the <see
- /// cref="Value"/>.</returns>
- /// <exception cref="T:System.NullReferenceException">
- /// The <see cref="Value"/> is null.
- /// </exception>
- public override string ToString()
- {
- return IsValueCreated ? Value.ToString() : Environment.GetResourceString("Lazy_ToString_ValueNotCreated");
- }
-
- /// <summary>Gets the value of the Lazy&lt;T&gt; for debugging display purposes.</summary>
- internal T ValueForDebugDisplay
- {
- get
- {
- if (!IsValueCreated)
- {
- return default(T);
- }
- return ((Boxed)m_boxed).m_value;
- }
- }
-
- /// <summary>
- /// Gets a value indicating whether this instance may be used concurrently from multiple threads.
- /// </summary>
- internal LazyThreadSafetyMode Mode
- {
- get
- {
- if (m_threadSafeObj == null) return LazyThreadSafetyMode.None;
- if (m_threadSafeObj == (object)LazyHelpers.PUBLICATION_ONLY_SENTINEL) return LazyThreadSafetyMode.PublicationOnly;
- return LazyThreadSafetyMode.ExecutionAndPublication;
- }
- }
-
- /// <summary>
- /// Gets whether the value creation is faulted or not
- /// </summary>
- internal bool IsValueFaulted
- {
- get { return m_boxed is LazyInternalExceptionHolder; }
- }
-
- /// <summary>Gets a value indicating whether the <see cref="T:System.Lazy{T}"/> has been initialized.
- /// </summary>
- /// <value>true if the <see cref="T:System.Lazy{T}"/> instance has been initialized;
- /// otherwise, false.</value>
- /// <remarks>
- /// The initialization of a <see cref="T:System.Lazy{T}"/> instance may result in either
- /// a value being produced or an exception being thrown. If an exception goes unhandled during initialization,
- /// <see cref="IsValueCreated"/> will return false.
- /// </remarks>
- public bool IsValueCreated
- {
- get
- {
- return m_boxed != null && m_boxed is Boxed;
- }
- }
-
- /// <summary>Gets the lazily initialized value of the current <see
- /// cref="T:System.Threading.Lazy{T}"/>.</summary>
- /// <value>The lazily initialized value of the current <see
- /// cref="T:System.Threading.Lazy{T}"/>.</value>
- /// <exception cref="T:System.MissingMemberException">
- /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor
- /// of the type being lazily initialized, and that type does not have a public, parameterless constructor.
- /// </exception>
- /// <exception cref="T:System.MemberAccessException">
- /// The <see cref="T:System.Threading.Lazy{T}"/> was initialized to use the default constructor
- /// of the type being lazily initialized, and permissions to access the constructor were missing.
- /// </exception>
- /// <exception cref="T:System.InvalidOperationException">
- /// The <see cref="T:System.Threading.Lazy{T}"/> was constructed with the <see cref="T:System.Threading.LazyThreadSafetyMode.ExecutionAndPublication"/> or
- /// <see cref="T:System.Threading.LazyThreadSafetyMode.None"/> and the initialization function attempted to access <see cref="Value"/> on this instance.
- /// </exception>
- /// <remarks>
- /// If <see cref="IsValueCreated"/> is false, accessing <see cref="Value"/> will force initialization.
- /// Please <see cref="System.Threading.LazyThreadSafetyMode"> for more information on how <see cref="T:System.Threading.Lazy{T}"/> will behave if an exception is thrown
- /// from initialization delegate.
- /// </remarks>
- [DebuggerBrowsable(DebuggerBrowsableState.Never)]
- public T Value
- {
- get
- {
- Boxed boxed = null;
- if (m_boxed != null )
- {
- // Do a quick check up front for the fast path.
- boxed = m_boxed as Boxed;
- if (boxed != null)
- {
- return boxed.m_value;
- }
-
- LazyInternalExceptionHolder exc = m_boxed as LazyInternalExceptionHolder;
- Debug.Assert(exc != null);
- exc.m_edi.Throw();
- }
-
- // Fall through to the slow path.
- return LazyInitValue();
- }
- }
-
- /// <summary>
- /// local helper method to initialize the value
- /// </summary>
- /// <returns>The inititialized T value</returns>
- private T LazyInitValue()
- {
- Boxed boxed = null;
- LazyThreadSafetyMode mode = Mode;
- if (mode == LazyThreadSafetyMode.None)
- {
- boxed = CreateValue();
- m_boxed = boxed;
- }
- else if (mode == LazyThreadSafetyMode.PublicationOnly)
- {
- boxed = CreateValue();
- if (boxed == null ||
- Interlocked.CompareExchange(ref m_boxed, boxed, null) != null)
- {
- // If CreateValue returns null, it means another thread successfully invoked the value factory
- // and stored the result, so we should just take what was stored. If CreateValue returns non-null
- // but another thread set the value we should just take what was stored.
- boxed = (Boxed)m_boxed;
- }
- else
- {
- // We successfully created and stored the value. At this point, the value factory delegate is
- // no longer needed, and we don't want to hold onto its resources.
- m_valueFactory = ALREADY_INVOKED_SENTINEL;
- }
- }
- else
- {
- object threadSafeObj = Volatile.Read(ref m_threadSafeObj);
- bool lockTaken = false;
- try
- {
- if (threadSafeObj != (object)ALREADY_INVOKED_SENTINEL)
- Monitor.Enter(threadSafeObj, ref lockTaken);
- else
- Debug.Assert(m_boxed != null);
-
- if (m_boxed == null)
- {
- boxed = CreateValue();
- m_boxed = boxed;
- Volatile.Write(ref m_threadSafeObj, ALREADY_INVOKED_SENTINEL);
- }
- else // got the lock but the value is not null anymore, check if it is created by another thread or faulted and throw if so
- {
- boxed = m_boxed as Boxed;
- if (boxed == null) // it is not Boxed, so it is a LazyInternalExceptionHolder
- {
- LazyInternalExceptionHolder exHolder = m_boxed as LazyInternalExceptionHolder;
- Debug.Assert(exHolder != null);
- exHolder.m_edi.Throw();
- }
- }
- }
- finally
- {
- if (lockTaken)
- Monitor.Exit(threadSafeObj);
- }
- }
- Debug.Assert(boxed != null);
- return boxed.m_value;
- }
-
- /// <summary>Creates an instance of T using m_valueFactory in case its not null or use reflection to create a new T()</summary>
- /// <returns>An instance of Boxed.</returns>
- private Boxed CreateValue()
- {
- Boxed boxed = null;
- LazyThreadSafetyMode mode = Mode;
- if (m_valueFactory != null)
- {
- try
- {
- // check for recursion
- if (mode != LazyThreadSafetyMode.PublicationOnly && m_valueFactory == ALREADY_INVOKED_SENTINEL)
- throw new InvalidOperationException(Environment.GetResourceString("Lazy_Value_RecursiveCallsToValue"));
-
- Func<T> factory = m_valueFactory;
- if (mode != LazyThreadSafetyMode.PublicationOnly) // only detect recursion on None and ExecutionAndPublication modes
- {
- m_valueFactory = ALREADY_INVOKED_SENTINEL;
- }
- else if (factory == ALREADY_INVOKED_SENTINEL)
- {
- // Another thread raced to successfully invoke the factory.
- return null;
- }
- boxed = new Boxed(factory());
- }
- catch (Exception ex)
- {
- if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode
- m_boxed = new LazyInternalExceptionHolder(ex);
- throw;
- }
- }
- else
- {
- try
- {
- boxed = new Boxed((T)Activator.CreateInstance(typeof(T)));
-
- }
- catch (System.MissingMethodException)
- {
- Exception ex = new System.MissingMemberException(Environment.GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT"));
- if (mode != LazyThreadSafetyMode.PublicationOnly) // don't cache the exception for PublicationOnly mode
- m_boxed = new LazyInternalExceptionHolder(ex);
- throw ex;
- }
- }
-
- return boxed;
- }
-
- }
-
- /// <summary>A debugger view of the Lazy&lt;T&gt; to surface additional debugging properties and
- /// to ensure that the Lazy&lt;T&gt; does not become initialized if it was not already.</summary>
- internal sealed class System_LazyDebugView<T>
- {
- //The Lazy object being viewed.
- private readonly Lazy<T> m_lazy;
-
- /// <summary>Constructs a new debugger view object for the provided Lazy object.</summary>
- /// <param name="lazy">A Lazy object to browse in the debugger.</param>
- public System_LazyDebugView(Lazy<T> lazy)
- {
- m_lazy = lazy;
- }
-
- /// <summary>Returns whether the Lazy object is initialized or not.</summary>
- public bool IsValueCreated
- {
- get { return m_lazy.IsValueCreated; }
- }
-
- /// <summary>Returns the value of the Lazy object.</summary>
- public T Value
- {
- get
- { return m_lazy.ValueForDebugDisplay; }
- }
-
- /// <summary>Returns the execution mode of the Lazy object</summary>
- public LazyThreadSafetyMode Mode
- {
- get { return m_lazy.Mode; }
- }
-
- /// <summary>Returns the execution mode of the Lazy object</summary>
- public bool IsValueFaulted
- {
- get { return m_lazy.IsValueFaulted; }
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/MarshalByRefObject.cs b/src/mscorlib/src/System/MarshalByRefObject.cs
deleted file mode 100644
index 9014de00c7..0000000000
--- a/src/mscorlib/src/System/MarshalByRefObject.cs
+++ /dev/null
@@ -1,30 +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.
-
-namespace System
-{
- [Serializable]
- public abstract class MarshalByRefObject
- {
- protected MarshalByRefObject()
- {
- }
-
- public object GetLifetimeService()
- {
- throw new PlatformNotSupportedException();
- }
-
- public virtual object InitializeLifetimeService()
- {
- throw new PlatformNotSupportedException();
- }
-
- protected MarshalByRefObject MemberwiseClone(bool cloneIdentity)
- {
- MarshalByRefObject mbr = (MarshalByRefObject)base.MemberwiseClone();
- return mbr;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Math.cs b/src/mscorlib/src/System/Math.cs
index 8b2af3d3e4..6f7d731ab1 100644
--- a/src/mscorlib/src/System/Math.cs
+++ b/src/mscorlib/src/System/Math.cs
@@ -10,260 +10,297 @@
**
**
===========================================================*/
-namespace System {
-
- //This class contains only static members and doesn't require serialization.
- using System;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
- public static class Math {
-
- private static double doubleRoundLimit = 1e16d;
-
- private const int maxRoundingDigits = 15;
-
- // This table is required for the Round function which can specify the number of digits to round to
- private static double[] roundPower10Double = new double[] {
+
+//This class contains only static members and doesn't require serialization.
+
+using System;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ public static class Math
+ {
+ private static double doubleRoundLimit = 1e16d;
+
+ private const int maxRoundingDigits = 15;
+
+ // This table is required for the Round function which can specify the number of digits to round to
+ private static double[] roundPower10Double = new double[] {
1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15
- };
-
- public const double PI = 3.14159265358979323846;
- public const double E = 2.7182818284590452354;
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Acos(double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Asin(double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Atan(double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Atan2(double y,double x);
-
- public static Decimal Ceiling(Decimal d) {
- return Decimal.Ceiling(d);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Ceiling(double a);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Cos (double d);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Cosh(double value);
-
- public static Decimal Floor(Decimal d) {
- return Decimal.Floor(d);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Floor(double d);
-
- private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) {
- if (Abs(value) < doubleRoundLimit) {
- Double power10 = roundPower10Double[digits];
- value *= power10;
- if (mode == MidpointRounding.AwayFromZero) {
- double fraction = SplitFractionDouble(&value);
- if (Abs(fraction) >= 0.5d) {
- value += Sign(fraction);
+ };
+
+ public const double PI = 3.14159265358979323846;
+ public const double E = 2.7182818284590452354;
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Acos(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Asin(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Atan(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Atan2(double y, double x);
+
+ public static Decimal Ceiling(Decimal d)
+ {
+ return Decimal.Ceiling(d);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Ceiling(double a);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Cos(double d);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Cosh(double value);
+
+ public static Decimal Floor(Decimal d)
+ {
+ return Decimal.Floor(d);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Floor(double d);
+
+ private static unsafe double InternalRound(double value, int digits, MidpointRounding mode)
+ {
+ if (Abs(value) < doubleRoundLimit)
+ {
+ Double power10 = roundPower10Double[digits];
+ value *= power10;
+ if (mode == MidpointRounding.AwayFromZero)
+ {
+ double fraction = SplitFractionDouble(&value);
+ if (Abs(fraction) >= 0.5d)
+ {
+ value += Sign(fraction);
+ }
}
+ else
+ {
+ // On X86 this can be inlined to just a few instructions
+ value = Round(value);
+ }
+ value /= power10;
}
- else {
- // On X86 this can be inlined to just a few instructions
- value = Round(value);
- }
- value /= power10;
- }
- return value;
- }
-
- private unsafe static double InternalTruncate(double d) {
- SplitFractionDouble(&d);
- return d;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Sin(double a);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Tan(double a);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Sinh(double value);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Tanh(double value);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Round(double a);
-
- public static double Round(double value, int digits)
- {
- if ((digits < 0) || (digits > maxRoundingDigits))
- throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
- Contract.EndContractBlock();
- return InternalRound(value, digits, MidpointRounding.ToEven);
- }
-
- public static double Round(double value, MidpointRounding mode) {
- return Round(value, 0, mode);
- }
-
- public static double Round(double value, int digits, MidpointRounding mode) {
- if ((digits < 0) || (digits > maxRoundingDigits))
- throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
- if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, nameof(MidpointRounding)), nameof(mode));
- }
- Contract.EndContractBlock();
- return InternalRound(value, digits, mode);
- }
-
- public static Decimal Round(Decimal d) {
- return Decimal.Round(d,0);
- }
-
- public static Decimal Round(Decimal d, int decimals) {
- return Decimal.Round(d,decimals);
- }
-
- public static Decimal Round(Decimal d, MidpointRounding mode) {
- return Decimal.Round(d, 0, mode);
- }
-
- public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) {
- return Decimal.Round(d, decimals, mode);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static unsafe extern double SplitFractionDouble(double* value);
-
- public static Decimal Truncate(Decimal d) {
- return Decimal.Truncate(d);
- }
-
- public static double Truncate(double d) {
- return InternalTruncate(d);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Sqrt(double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Log (double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Log10(double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Exp(double d);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double Pow(double x, double y);
-
- public static double IEEERemainder(double x, double y) {
- if (Double.IsNaN(x)) {
- return x; // IEEE 754-2008: NaN payload must be preserved
- }
- if (Double.IsNaN(y)) {
- return y; // IEEE 754-2008: NaN payload must be preserved
- }
-
- double regularMod = x % y;
- if (Double.IsNaN(regularMod)) {
- return Double.NaN;
- }
- if (regularMod == 0) {
- if (Double.IsNegative(x)) {
- return Double.NegativeZero;
- }
- }
- double alternativeResult;
- alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x));
- if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) {
- double divisionResult = x/y;
- double roundedResult = Math.Round(divisionResult);
- if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) {
- return alternativeResult;
- }
- else {
- return regularMod;
- }
- }
- if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) {
- return alternativeResult;
- }
- else {
- return regularMod;
- }
- }
-
- /*================================Abs=========================================
- **Returns the absolute value of it's argument.
- ============================================================================*/
- [CLSCompliant(false)]
- public static sbyte Abs(sbyte value) {
- if (value >= 0)
return value;
- else
- return AbsHelper(value);
- }
-
- private static sbyte AbsHelper(sbyte value)
- {
- Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
- if (value == SByte.MinValue)
- throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
- Contract.EndContractBlock();
- return ((sbyte)(-value));
- }
-
- public static short Abs(short value) {
- if (value >= 0)
- return value;
- else
- return AbsHelper(value);
- }
-
- private static short AbsHelper(short value) {
- Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
- if (value == Int16.MinValue)
- throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
- Contract.EndContractBlock();
- return (short) -value;
- }
-
- public static int Abs(int value) {
- if (value >= 0)
- return value;
- else
- return AbsHelper(value);
- }
-
- private static int AbsHelper(int value) {
- Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
- if (value == Int32.MinValue)
- throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
- Contract.EndContractBlock();
- return -value;
- }
-
- public static long Abs(long value) {
- if (value >= 0)
- return value;
- else
- return AbsHelper(value);
- }
-
- private static long AbsHelper(long value) {
- Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
- if (value == Int64.MinValue)
- throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
- Contract.EndContractBlock();
- return -value;
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern public static float Abs(float value);
+ }
+
+ private unsafe static double InternalTruncate(double d)
+ {
+ SplitFractionDouble(&d);
+ return d;
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Sin(double a);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Tan(double a);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Sinh(double value);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Tanh(double value);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Round(double a);
+
+ public static double Round(double value, int digits)
+ {
+ if ((digits < 0) || (digits > maxRoundingDigits))
+ throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
+ Contract.EndContractBlock();
+ return InternalRound(value, digits, MidpointRounding.ToEven);
+ }
+
+ public static double Round(double value, MidpointRounding mode)
+ {
+ return Round(value, 0, mode);
+ }
+
+ public static double Round(double value, int digits, MidpointRounding mode)
+ {
+ if ((digits < 0) || (digits > maxRoundingDigits))
+ throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
+ if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
+ }
+ Contract.EndContractBlock();
+ return InternalRound(value, digits, mode);
+ }
+
+ public static Decimal Round(Decimal d)
+ {
+ return Decimal.Round(d, 0);
+ }
+
+ public static Decimal Round(Decimal d, int decimals)
+ {
+ return Decimal.Round(d, decimals);
+ }
+
+ public static Decimal Round(Decimal d, MidpointRounding mode)
+ {
+ return Decimal.Round(d, 0, mode);
+ }
+
+ public static Decimal Round(Decimal d, int decimals, MidpointRounding mode)
+ {
+ return Decimal.Round(d, decimals, mode);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private static unsafe extern double SplitFractionDouble(double* value);
+
+ public static Decimal Truncate(Decimal d)
+ {
+ return Decimal.Truncate(d);
+ }
+
+ public static double Truncate(double d)
+ {
+ return InternalTruncate(d);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Sqrt(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Log(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Log10(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Exp(double d);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern double Pow(double x, double y);
+
+ public static double IEEERemainder(double x, double y)
+ {
+ if (Double.IsNaN(x))
+ {
+ return x; // IEEE 754-2008: NaN payload must be preserved
+ }
+ if (Double.IsNaN(y))
+ {
+ return y; // IEEE 754-2008: NaN payload must be preserved
+ }
+
+ double regularMod = x % y;
+ if (Double.IsNaN(regularMod))
+ {
+ return Double.NaN;
+ }
+ if (regularMod == 0)
+ {
+ if (Double.IsNegative(x))
+ {
+ return Double.NegativeZero;
+ }
+ }
+ double alternativeResult;
+ alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x));
+ if (Math.Abs(alternativeResult) == Math.Abs(regularMod))
+ {
+ double divisionResult = x / y;
+ double roundedResult = Math.Round(divisionResult);
+ if (Math.Abs(roundedResult) > Math.Abs(divisionResult))
+ {
+ return alternativeResult;
+ }
+ else
+ {
+ return regularMod;
+ }
+ }
+ if (Math.Abs(alternativeResult) < Math.Abs(regularMod))
+ {
+ return alternativeResult;
+ }
+ else
+ {
+ return regularMod;
+ }
+ }
+
+ /*================================Abs=========================================
+ **Returns the absolute value of it's argument.
+ ============================================================================*/
+ [CLSCompliant(false)]
+ public static sbyte Abs(sbyte value)
+ {
+ if (value >= 0)
+ return value;
+ else
+ return AbsHelper(value);
+ }
+
+ private static sbyte AbsHelper(sbyte value)
+ {
+ Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
+ if (value == SByte.MinValue)
+ throw new OverflowException(SR.Overflow_NegateTwosCompNum);
+ Contract.EndContractBlock();
+ return ((sbyte)(-value));
+ }
+
+ public static short Abs(short value)
+ {
+ if (value >= 0)
+ return value;
+ else
+ return AbsHelper(value);
+ }
+
+ private static short AbsHelper(short value)
+ {
+ Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
+ if (value == Int16.MinValue)
+ throw new OverflowException(SR.Overflow_NegateTwosCompNum);
+ Contract.EndContractBlock();
+ return (short)-value;
+ }
+
+ public static int Abs(int value)
+ {
+ if (value >= 0)
+ return value;
+ else
+ return AbsHelper(value);
+ }
+
+ private static int AbsHelper(int value)
+ {
+ Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
+ if (value == Int32.MinValue)
+ throw new OverflowException(SR.Overflow_NegateTwosCompNum);
+ Contract.EndContractBlock();
+ return -value;
+ }
+
+ public static long Abs(long value)
+ {
+ if (value >= 0)
+ return value;
+ else
+ return AbsHelper(value);
+ }
+
+ private static long AbsHelper(long value)
+ {
+ Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)");
+ if (value == Int64.MinValue)
+ throw new OverflowException(SR.Overflow_NegateTwosCompNum);
+ Contract.EndContractBlock();
+ return -value;
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ extern public static float Abs(float value);
// This is special code to handle NaN (We need to make sure NaN's aren't
// negated). In CSharp, the else clause here should always be taken if
// value is NaN, since the normal case is taken if and only if value < 0.
@@ -272,9 +309,9 @@ namespace System {
// The bge command branches for comparisons with the unordered NaN. So
// it runs the else case, which returns +value instead of negating it.
// return (value < 0) ? -value : value;
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern public static double Abs(double value);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ extern public static double Abs(double value);
// This is special code to handle NaN (We need to make sure NaN's aren't
// negated). In CSharp, the else clause here should always be taken if
// value is NaN, since the normal case is taken if and only if value < 0.
@@ -284,152 +321,174 @@ namespace System {
// it runs the else case, which returns +value instead of negating it.
// return (value < 0) ? -value : value;
- public static Decimal Abs(Decimal value)
- {
- return Decimal.Abs(value);
- }
-
- /*================================MAX=========================================
- **Returns the larger of val1 and val2
- ============================================================================*/
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static sbyte Max(sbyte val1, sbyte val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static byte Max(byte val1, byte val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static short Max(short val1, short val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static ushort Max(ushort val1, ushort val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static int Max(int val1, int val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static uint Max(uint val1, uint val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static long Max(long val1, long val2) {
- return (val1>=val2)?val1:val2;
- }
-
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static ulong Max(ulong val1, ulong val2) {
- return (val1>=val2)?val1:val2;
- }
-
- public static float Max(float val1, float val2) {
- if (val1 > val2)
- return val1;
-
- if (Single.IsNaN(val1))
- return val1;
-
- return val2;
- }
-
- public static double Max(double val1, double val2) {
- if (val1 > val2)
- return val1;
-
- if (Double.IsNaN(val1))
- return val1;
-
- return val2;
- }
-
- public static Decimal Max(Decimal val1, Decimal val2) {
- return Decimal.Max(val1,val2);
- }
-
- /*================================MIN=========================================
- **Returns the smaller of val1 and val2.
- ============================================================================*/
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static sbyte Min(sbyte val1, sbyte val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static byte Min(byte val1, byte val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static short Min(short val1, short val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static ushort Min(ushort val1, ushort val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static int Min(int val1, int val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static uint Min(uint val1, uint val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [System.Runtime.Versioning.NonVersionable]
- public static long Min(long val1, long val2) {
- return (val1<=val2)?val1:val2;
- }
-
- [CLSCompliant(false)]
- [System.Runtime.Versioning.NonVersionable]
- public static ulong Min(ulong val1, ulong val2) {
- return (val1<=val2)?val1:val2;
- }
-
- public static float Min(float val1, float val2) {
- if (val1 < val2)
- return val1;
-
- if (Single.IsNaN(val1))
- return val1;
-
- return val2;
- }
-
- public static double Min(double val1, double val2) {
- if (val1 < val2)
- return val1;
-
- if (Double.IsNaN(val1))
- return val1;
-
- return val2;
- }
-
- public static Decimal Min(Decimal val1, Decimal val2) {
- return Decimal.Min(val1,val2);
- }
+ public static Decimal Abs(Decimal value)
+ {
+ return Decimal.Abs(value);
+ }
+
+ /*================================MAX=========================================
+ **Returns the larger of val1 and val2
+ ============================================================================*/
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static sbyte Max(sbyte val1, sbyte val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static byte Max(byte val1, byte val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static short Max(short val1, short val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static ushort Max(ushort val1, ushort val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static int Max(int val1, int val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static uint Max(uint val1, uint val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static long Max(long val1, long val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static ulong Max(ulong val1, ulong val2)
+ {
+ return (val1 >= val2) ? val1 : val2;
+ }
+
+ public static float Max(float val1, float val2)
+ {
+ if (val1 > val2)
+ return val1;
+
+ if (Single.IsNaN(val1))
+ return val1;
+
+ return val2;
+ }
+
+ public static double Max(double val1, double val2)
+ {
+ if (val1 > val2)
+ return val1;
+
+ if (Double.IsNaN(val1))
+ return val1;
+
+ return val2;
+ }
+
+ public static Decimal Max(Decimal val1, Decimal val2)
+ {
+ return Decimal.Max(val1, val2);
+ }
+
+ /*================================MIN=========================================
+ **Returns the smaller of val1 and val2.
+ ============================================================================*/
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static sbyte Min(sbyte val1, sbyte val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static byte Min(byte val1, byte val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static short Min(short val1, short val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static ushort Min(ushort val1, ushort val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static int Min(int val1, int val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static uint Min(uint val1, uint val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public static long Min(long val1, long val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ [CLSCompliant(false)]
+ [System.Runtime.Versioning.NonVersionable]
+ public static ulong Min(ulong val1, ulong val2)
+ {
+ return (val1 <= val2) ? val1 : val2;
+ }
+
+ public static float Min(float val1, float val2)
+ {
+ if (val1 < val2)
+ return val1;
+
+ if (Single.IsNaN(val1))
+ return val1;
+
+ return val2;
+ }
+
+ public static double Min(double val1, double val2)
+ {
+ if (val1 < val2)
+ return val1;
+
+ if (Double.IsNaN(val1))
+ return val1;
+
+ return val2;
+ }
+
+ public static Decimal Min(Decimal val1, Decimal val2)
+ {
+ return Decimal.Min(val1, val2);
+ }
/*=====================================Clamp====================================
**
@@ -572,29 +631,32 @@ namespace System {
private static void ThrowMinMaxException<T>(T min, T max)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_MinMaxValue", min, max));
- }
-
- /*=====================================Log======================================
- **
- ==============================================================================*/
- public static double Log(double a, double newBase) {
- if (Double.IsNaN(a)) {
- return a; // IEEE 754-2008: NaN payload must be preserved
- }
- if (Double.IsNaN(newBase)) {
- return newBase; // IEEE 754-2008: NaN payload must be preserved
- }
-
- if (newBase == 1)
- return Double.NaN;
- if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase)))
- return Double.NaN;
-
- return (Log(a)/Log(newBase));
- }
-
-
+ throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max));
+ }
+
+ /*=====================================Log======================================
+ **
+ ==============================================================================*/
+ public static double Log(double a, double newBase)
+ {
+ if (Double.IsNaN(a))
+ {
+ return a; // IEEE 754-2008: NaN payload must be preserved
+ }
+ if (Double.IsNaN(newBase))
+ {
+ return newBase; // IEEE 754-2008: NaN payload must be preserved
+ }
+
+ if (newBase == 1)
+ return Double.NaN;
+ if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase)))
+ return Double.NaN;
+
+ return (Log(a) / Log(newBase));
+ }
+
+
// Sign function for VB. Returns -1, 0, or 1 if the sign of the number
// is negative, 0, or positive. Throws for floating point NaN's.
[CLSCompliant(false)]
@@ -642,8 +704,8 @@ namespace System {
else
return 0;
}
-
- public static int Sign (float value)
+
+ public static int Sign(float value)
{
if (value < 0)
return -1;
@@ -651,7 +713,7 @@ namespace System {
return 1;
else if (value == 0)
return 0;
- throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN"));
+ throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(double value)
@@ -662,7 +724,7 @@ namespace System {
return 1;
else if (value == 0)
return 0;
- throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN"));
+ throw new ArithmeticException(SR.Arithmetic_NaN);
}
public static int Sign(Decimal value)
@@ -675,11 +737,13 @@ namespace System {
return 0;
}
- public static long BigMul(int a, int b) {
+ public static long BigMul(int a, int b)
+ {
return ((long)a) * b;
}
- public static int DivRem(int a, int b, out int result) {
+ public static int DivRem(int a, int b, out int result)
+ {
// TODO https://github.com/dotnet/coreclr/issues/3439:
// Restore to using % and / when the JIT is able to eliminate one of the idivs.
// In the meantime, a * and - is measurably faster than an extra /.
@@ -688,7 +752,8 @@ namespace System {
return div;
}
- public static long DivRem(long a, long b, out long result) {
+ public static long DivRem(long a, long b, out long result)
+ {
// TODO https://github.com/dotnet/coreclr/issues/3439:
// Restore to using % and / when the JIT is able to eliminate one of the idivs.
// In the meantime, a * and - is measurably faster than an extra /.
diff --git a/src/mscorlib/src/System/MathF.cs b/src/mscorlib/src/System/MathF.cs
index 545774cc32..60669a4561 100644
--- a/src/mscorlib/src/System/MathF.cs
+++ b/src/mscorlib/src/System/MathF.cs
@@ -7,16 +7,18 @@
** Purpose: Some single-precision floating-point math operations
**
===========================================================*/
-namespace System {
- //This class contains only static members and doesn't require serialization.
- using System;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
+//This class contains only static members and doesn't require serialization.
+using System;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
public static class MathF
{
private static float singleRoundLimit = 1e8f;
@@ -77,7 +79,7 @@ namespace System {
if (float.IsNaN(regularMod))
{
- return float.NaN;
+ return float.NaN;
}
if ((regularMod == 0) && float.IsNegative(x))
@@ -157,7 +159,7 @@ namespace System {
{
if ((digits < 0) || (digits > maxRoundingDigits))
{
- throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
+ throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
}
Contract.EndContractBlock();
@@ -168,12 +170,12 @@ namespace System {
{
if ((digits < 0) || (digits > maxRoundingDigits))
{
- throw new ArgumentOutOfRangeException(nameof(digits), Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits"));
+ throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
}
-
+
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidEnum, mode, nameof(MidpointRounding)), nameof(mode));
}
Contract.EndContractBlock();
@@ -184,10 +186,10 @@ namespace System {
{
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumx", mode, nameof(MidpointRounding)), nameof(mode));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidEnum, mode, nameof(MidpointRounding)), nameof(mode));
}
Contract.EndContractBlock();
-
+
return InternalRound(x, 0, mode);
}
@@ -215,13 +217,13 @@ namespace System {
if (Abs(x) < singleRoundLimit)
{
var power10 = roundPower10Single[digits];
-
+
x *= power10;
-
+
if (mode == MidpointRounding.AwayFromZero)
{
var fraction = SplitFractionSingle(&x);
-
+
if (Abs(fraction) >= 0.5f)
{
x += Sign(fraction);
diff --git a/src/mscorlib/src/System/MemberAccessException.cs b/src/mscorlib/src/System/MemberAccessException.cs
deleted file mode 100644
index 54eee67b07..0000000000
--- a/src/mscorlib/src/System/MemberAccessException.cs
+++ /dev/null
@@ -1,48 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-// MemberAccessException
-// Thrown when we try accessing a member that we cannot
-// access, due to it being removed, private or something similar.
-////////////////////////////////////////////////////////////////////////////////
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The MemberAccessException is thrown when trying to access a class
- // member fails.
- //
- [Serializable]
- public class MemberAccessException : SystemException
- {
- // Creates a new MemberAccessException with its message string set to
- // the empty string, its HRESULT set to COR_E_MEMBERACCESS,
- // and its ExceptionInfo reference set to null.
- public MemberAccessException()
- : base(SR.Arg_AccessException)
- {
- HResult = __HResults.COR_E_MEMBERACCESS;
- }
-
- // Creates a new MemberAccessException with its message string set to
- // message, its HRESULT set to COR_E_ACCESS,
- // and its ExceptionInfo reference set to null.
- //
- public MemberAccessException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_MEMBERACCESS;
- }
-
- public MemberAccessException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_MEMBERACCESS;
- }
-
- protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/MethodAccessException.cs b/src/mscorlib/src/System/MethodAccessException.cs
deleted file mode 100644
index 2ecbd14d6d..0000000000
--- a/src/mscorlib/src/System/MethodAccessException.cs
+++ /dev/null
@@ -1,39 +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 for class loading failures.
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class MethodAccessException : MemberAccessException
- {
- public MethodAccessException()
- : base(SR.Arg_MethodAccessException)
- {
- HResult = __HResults.COR_E_METHODACCESS;
- }
-
- public MethodAccessException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_METHODACCESS;
- }
-
- public MethodAccessException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_METHODACCESS;
- }
-
- protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs
index 660e39cb47..5668f9e9b3 100644
--- a/src/mscorlib/src/System/MissingFieldException.cs
+++ b/src/mscorlib/src/System/MissingFieldException.cs
@@ -9,53 +9,62 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
- using System.Globalization;
+
+using System;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+using System.Runtime.CompilerServices;
+using System.Globalization;
+
+namespace System
+{
[Serializable]
- public class MissingFieldException : MissingMemberException, ISerializable {
- public MissingFieldException()
- : base(Environment.GetResourceString("Arg_MissingFieldException")) {
- SetErrorCode(__HResults.COR_E_MISSINGFIELD);
+ public class MissingFieldException : MissingMemberException, ISerializable
+ {
+ public MissingFieldException()
+ : base(SR.Arg_MissingFieldException)
+ {
+ HResult = __HResults.COR_E_MISSINGFIELD;
}
-
- public MissingFieldException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_MISSINGFIELD);
+
+ public MissingFieldException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_MISSINGFIELD;
}
-
- public MissingFieldException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_MISSINGFIELD);
+
+ public MissingFieldException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_MISSINGFIELD;
}
- protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
-
+
public override String Message
{
- get {
- if (ClassName == null) {
+ get
+ {
+ if (ClassName == null)
+ {
return base.Message;
- } else {
+ }
+ else
+ {
// do any desired fixups to classname here.
- return Environment.GetResourceString("MissingField_Name",
- (Signature != null ? FormatSignature(Signature) + " " : "") +
- ClassName + "." + MemberName);
+ return SR.Format(SR.MissingField_Name, (Signature != null ? FormatSignature(Signature) + " " : "") + ClassName + "." + MemberName);
}
}
}
-
+
public MissingFieldException(String className, String fieldName)
{
- ClassName = className;
- MemberName = fieldName;
+ ClassName = className;
+ MemberName = fieldName;
}
-
+
// If ClassName != null, Message will construct on the fly using it
// and the other variables. This allows customization of the
// format depending on the language environment.
diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs
index bb9be8827a..51150e113c 100644
--- a/src/mscorlib/src/System/MissingMemberException.cs
+++ b/src/mscorlib/src/System/MissingMemberException.cs
@@ -11,65 +11,75 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
+
+using System;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+using System.Runtime.CompilerServices;
+using System.Globalization;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
[Serializable]
- public class MissingMemberException : MemberAccessException, ISerializable {
- public MissingMemberException()
- : base(Environment.GetResourceString("Arg_MissingMemberException")) {
- SetErrorCode(__HResults.COR_E_MISSINGMEMBER);
+ public class MissingMemberException : MemberAccessException, ISerializable
+ {
+ public MissingMemberException()
+ : base(SR.Arg_MissingMemberException)
+ {
+ HResult = __HResults.COR_E_MISSINGMEMBER;
}
-
- public MissingMemberException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_MISSINGMEMBER);
+
+ public MissingMemberException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_MISSINGMEMBER;
}
-
- public MissingMemberException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_MISSINGMEMBER);
+
+ public MissingMemberException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_MISSINGMEMBER;
}
- protected MissingMemberException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected MissingMemberException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
ClassName = (String)info.GetString("MMClassName");
MemberName = (String)info.GetString("MMMemberName");
Signature = (byte[])info.GetValue("MMSignature", typeof(byte[]));
}
-
+
public override String Message
{
- get {
- if (ClassName == null) {
+ get
+ {
+ if (ClassName == null)
+ {
return base.Message;
- } else {
+ }
+ else
+ {
// do any desired fixups to classname here.
- return Environment.GetResourceString("MissingMember_Name",
- ClassName + "." + MemberName +
- (Signature != null ? " " + FormatSignature(Signature) : ""));
+ return SR.Format(SR.MissingMember_Name, ClassName + "." + MemberName + (Signature != null ? " " + FormatSignature(Signature) : ""));
}
}
}
-
+
// Called to format signature
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String FormatSignature(byte [] signature);
-
+ internal static extern String FormatSignature(byte[] signature);
+
public MissingMemberException(String className, String memberName)
{
- ClassName = className;
- MemberName = memberName;
+ ClassName = className;
+ MemberName = memberName;
}
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -78,13 +88,13 @@ namespace System {
info.AddValue("MMMemberName", MemberName, typeof(String));
info.AddValue("MMSignature", Signature, typeof(byte[]));
}
-
-
+
+
// If ClassName != null, GetMessage will construct on the fly using it
// and the other variables. This allows customization of the
// format depending on the language environment.
- protected String ClassName;
- protected String MemberName;
- protected byte[] Signature;
+ protected String ClassName;
+ protected String MemberName;
+ protected byte[] Signature;
}
}
diff --git a/src/mscorlib/src/System/MissingMethodException.cs b/src/mscorlib/src/System/MissingMethodException.cs
deleted file mode 100644
index 426711f953..0000000000
--- a/src/mscorlib/src/System/MissingMethodException.cs
+++ /dev/null
@@ -1,65 +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 for class loading failures.
-**
-**
-=============================================================================*/
-
-namespace System {
-
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- [Serializable]
- public class MissingMethodException : MissingMemberException, ISerializable {
- public MissingMethodException()
- : base(Environment.GetResourceString("Arg_MissingMethodException")) {
- SetErrorCode(__HResults.COR_E_MISSINGMETHOD);
- }
-
- public MissingMethodException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_MISSINGMETHOD);
- }
-
- public MissingMethodException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_MISSINGMETHOD);
- }
-
- protected MissingMethodException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
-
- public override String Message
- {
- get {
- if (ClassName == null) {
- return base.Message;
- } else {
- // do any desired fixups to classname here.
- return Environment.GetResourceString("MissingMethod_Name",
- ClassName + "." + MemberName +
- (Signature != null ? " " + FormatSignature(Signature) : ""));
- }
- }
- }
-
- public MissingMethodException(String className, String methodName)
- {
- ClassName = className;
- MemberName = methodName;
- }
-
- // If ClassName != null, Message will construct on the fly using it
- // and the other variables. This allows customization of the
- // format depending on the language environment.
- }
-}
diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs
index aa3271ceab..440c9a60bc 100644
--- a/src/mscorlib/src/System/MulticastDelegate.cs
+++ b/src/mscorlib/src/System/MulticastDelegate.cs
@@ -2,17 +2,17 @@
// 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.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Reflection.Emit;
+
namespace System
{
- using System;
- using System.Reflection;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Reflection.Emit;
-
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class MulticastDelegate : Delegate
@@ -21,8 +21,8 @@ namespace System
// 1. Multicast delegate
// 2. Secure/Wrapper delegate
// 3. Inner delegate of secure delegate where the secure delegate security context is a collectible method
- private Object _invocationList;
- private IntPtr _invocationCount;
+ private Object _invocationList;
+ private IntPtr _invocationCount;
// This constructor is called from the class generated by the
// compiler generated code (This must match the constructor
@@ -30,11 +30,11 @@ namespace System
protected MulticastDelegate(Object target, String method) : base(target, method)
{
}
-
+
// This constructor is called from a class to generate a
// delegate based upon a static method name and the Type object
// for the class defining the method.
- protected MulticastDelegate(Type target, String method) : base(target, method)
+ protected MulticastDelegate(Type target, String method) : base(target, method)
{
}
@@ -58,25 +58,25 @@ namespace System
// A MethodInfo object can be a RuntimeMethodInfo, a RefEmit method (MethodBuilder, etc), or a DynamicMethod
// One can only create delegates on RuntimeMethodInfo and DynamicMethod.
// If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, throw
- if ( !(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr() )
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
+ if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr())
+ throw new SerializationException(SR.Serialization_InvalidDelegateType);
// We can't deal with secure delegates either.
if (!InvocationListLogicallyNull() && !_invocationCount.IsNull() && !_methodPtrAux.IsNull())
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
+ throw new SerializationException(SR.Serialization_InvalidDelegateType);
- DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, method, targetIndex);
+ DelegateSerializationHolder.GetDelegateSerializationInfo(info, this.GetType(), Target, method, targetIndex);
}
else
{
DelegateSerializationHolder.DelegateEntry nextDe = null;
int invocationCount = (int)_invocationCount;
- for (int i = invocationCount; --i >= 0; )
+ for (int i = invocationCount; --i >= 0;)
{
MulticastDelegate d = (MulticastDelegate)invocationList[i];
MethodInfo method = d.Method;
// If it is not a RuntimeMethodInfo (must be a DynamicMethod) or if it is an unmanaged function pointer, skip
- if ( !(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr() )
+ if (!(method is RuntimeMethodInfo) || IsUnmanagedFunctionPtr())
continue;
// We can't deal with secure delegates either.
@@ -86,12 +86,12 @@ namespace System
DelegateSerializationHolder.DelegateEntry de = DelegateSerializationHolder.GetDelegateSerializationInfo(info, d.GetType(), d.Target, method, targetIndex++);
if (nextDe != null)
nextDe.Entry = de;
-
+
nextDe = de;
}
// if nothing was serialized it is a delegate over a DynamicMethod, so just throw
- if (nextDe == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidDelegateType"));
+ if (nextDe == null)
+ throw new SerializationException(SR.Serialization_InvalidDelegateType);
}
}
@@ -105,14 +105,14 @@ namespace System
return true;
if (!InternalEqualTypes(this, obj))
return false;
-
+
// Since this is a MulticastDelegate and we know
// the types are the same, obj should also be a
// MulticastDelegate
Debug.Assert(obj is MulticastDelegate, "Shouldn't have failed here since we already checked the types are the same!");
var d = JitHelpers.UnsafeCast<MulticastDelegate>(obj);
- if (_invocationCount != (IntPtr)0)
+ if (_invocationCount != (IntPtr)0)
{
// there are 4 kind of delegate kinds that fall into this bucket
// 1- Multicast (_invocationList is Object[])
@@ -134,17 +134,17 @@ namespace System
if ((d._invocationList as Delegate) != null)
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
return Equals(d._invocationList);
-
+
return base.Equals(obj);
}
else
{
- if ((_invocationList as Delegate) != null)
+ if ((_invocationList as Delegate) != null)
{
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
- return _invocationList.Equals(obj);
+ return _invocationList.Equals(obj);
}
- else
+ else
{
Debug.Assert((_invocationList as Object[]) != null, "empty invocation list on multicast delegate");
return InvocationListEquals(d);
@@ -159,11 +159,11 @@ namespace System
// and call the base.Equals()
if (!InvocationListLogicallyNull())
{
- if (!_invocationList.Equals(d._invocationList))
+ if (!_invocationList.Equals(d._invocationList))
return false;
return base.Equals(d);
}
-
+
// now we know 'this' is not a special one, so we can work out what the other is
if ((d._invocationList as Delegate) != null)
// this is a secure/wrapper delegate so we need to unwrap and check the inner one
@@ -173,7 +173,7 @@ namespace System
return base.Equals(d);
}
}
-
+
// Recursive function which will check for equality of the invocation list.
private bool InvocationListEquals(MulticastDelegate d)
{
@@ -181,7 +181,7 @@ namespace System
Object[] invocationList = _invocationList as Object[];
if (d._invocationCount != _invocationCount)
return false;
-
+
int invocationCount = (int)_invocationCount;
for (int i = 0; i < invocationCount; i++)
{
@@ -197,16 +197,16 @@ namespace System
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Object>(ref a[index], o, null) == null)
return true;
-
+
// The slot may be already set because we have added and removed the same method before.
// Optimize this case, because it's cheaper than copying the array.
if (a[index] != null)
{
- MulticastDelegate d = (MulticastDelegate)o;
+ MulticastDelegate d = (MulticastDelegate)o;
MulticastDelegate dd = (MulticastDelegate)a[index];
-
- if (dd._methodPtr == d._methodPtr &&
- dd._target == d._target &&
+
+ if (dd._methodPtr == d._methodPtr &&
+ dd._target == d._target &&
dd._methodPtrAux == d._methodPtrAux)
{
return true;
@@ -224,12 +224,12 @@ namespace System
// copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them
if (thisIsMultiCastAlready)
{
- result._methodPtr = this._methodPtr;
+ result._methodPtr = this._methodPtr;
result._methodPtrAux = this._methodPtrAux;
}
else
{
- result._methodPtr = GetMulticastInvoke();
+ result._methodPtr = GetMulticastInvoke();
result._methodPtrAux = GetInvokeMethod();
}
result._target = result;
@@ -244,17 +244,16 @@ namespace System
return NewMulticastDelegate(invocationList, invocationCount, false);
}
- internal void StoreDynamicMethod(MethodInfo dynamicMethod)
+ internal void StoreDynamicMethod(MethodInfo dynamicMethod)
{
- if (_invocationCount != (IntPtr)0)
+ if (_invocationCount != (IntPtr)0)
{
Debug.Assert(!IsUnmanagedFunctionPtr(), "dynamic method and unmanaged fntptr delegate combined");
// must be a secure/wrapper one, unwrap and save
MulticastDelegate d = (MulticastDelegate)_invocationList;
d._methodBase = dynamicMethod;
-
}
- else
+ else
_methodBase = dynamicMethod;
}
@@ -267,15 +266,15 @@ namespace System
// Verify that the types are the same...
if (!InternalEqualTypes(this, follow))
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTypeMis"));
+ throw new ArgumentException(SR.Arg_DlgtTypeMis);
MulticastDelegate dFollow = (MulticastDelegate)follow;
Object[] resultList;
int followCount = 1;
Object[] followList = dFollow._invocationList as Object[];
if (followList != null)
- followCount = (int)dFollow._invocationCount;
-
+ followCount = (int)dFollow._invocationCount;
+
int resultCount;
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
@@ -325,12 +324,12 @@ namespace System
int allocCount = invocationList.Length;
while (allocCount < resultCount)
allocCount *= 2;
-
+
resultList = new Object[allocCount];
-
+
for (int i = 0; i < invocationCount; i++)
resultList[i] = invocationList[i];
-
+
if (followList == null)
{
resultList[invocationCount] = dFollow;
@@ -344,22 +343,22 @@ namespace System
return NewMulticastDelegate(resultList, resultCount, true);
}
}
-
+
private Object[] DeleteFromInvocationList(Object[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Object[] thisInvocationList = _invocationList as Object[];
int allocCount = thisInvocationList.Length;
- while (allocCount/2 >= invocationCount - deleteCount)
+ while (allocCount / 2 >= invocationCount - deleteCount)
allocCount /= 2;
-
+
Object[] newInvocationList = new Object[allocCount];
-
+
for (int i = 0; i < deleteIndex; i++)
newInvocationList[i] = invocationList[i];
-
+
for (int i = deleteIndex + deleteCount; i < invocationCount; i++)
newInvocationList[i - deleteCount] = invocationList[i];
-
+
return newInvocationList;
}
@@ -384,8 +383,8 @@ namespace System
// the value we need to check for this case
//
MulticastDelegate v = value as MulticastDelegate;
-
- if (v == null)
+
+ if (v == null)
return this;
if (v._invocationList as Object[] == null)
{
@@ -399,19 +398,19 @@ namespace System
else
{
int invocationCount = (int)_invocationCount;
- for (int i = invocationCount; --i >= 0; )
+ for (int i = invocationCount; --i >= 0;)
{
if (value.Equals(invocationList[i]))
{
if (invocationCount == 2)
{
// Special case - only one value left, either at the beginning or the end
- return (Delegate)invocationList[1-i];
+ return (Delegate)invocationList[1 - i];
}
else
{
Object[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1);
- return NewMulticastDelegate(list, invocationCount-1, true);
+ return NewMulticastDelegate(list, invocationCount - 1, true);
}
}
}
@@ -420,7 +419,8 @@ namespace System
else
{
Object[] invocationList = _invocationList as Object[];
- if (invocationList != null) {
+ if (invocationList != null)
+ {
int invocationCount = (int)_invocationCount;
int vInvocationCount = (int)v._invocationCount;
for (int i = invocationCount - vInvocationCount; i >= 0; i--)
@@ -435,7 +435,7 @@ namespace System
else if (invocationCount - vInvocationCount == 1)
{
// Special case - only one value left, either at the beginning or the end
- return (Delegate)invocationList[i != 0 ? 0 : invocationCount-1];
+ return (Delegate)invocationList[i != 0 ? 0 : invocationCount - 1];
}
else
{
@@ -446,7 +446,7 @@ namespace System
}
}
}
-
+
return this;
}
@@ -467,7 +467,7 @@ namespace System
// Create an array of delegate copies and each
// element into the array
del = new Delegate[(int)_invocationCount];
-
+
for (int i = 0; i < del.Length; i++)
del[i] = (Delegate)invocationList[i];
}
@@ -478,7 +478,7 @@ namespace System
{
if ((Object)d1 == null)
return (Object)d2 == null;
-
+
return d1.Equals(d2);
}
@@ -486,10 +486,10 @@ namespace System
{
if ((Object)d1 == null)
return (Object)d2 != null;
-
+
return !d1.Equals(d2);
}
-
+
public override sealed int GetHashCode()
{
if (IsUnmanagedFunctionPtr())
@@ -505,16 +505,16 @@ namespace System
int hash = 0;
for (int i = 0; i < (int)_invocationCount; i++)
{
- hash = hash*33 + invocationList[i].GetHashCode();
+ hash = hash * 33 + invocationList[i].GetHashCode();
}
-
+
return hash;
}
}
internal override Object GetTarget()
{
- if (_invocationCount != (IntPtr)0)
+ if (_invocationCount != (IntPtr)0)
{
// _invocationCount != 0 we are in one of these cases:
// - Multicast -> return the target of the last delegate in the list
@@ -529,7 +529,7 @@ namespace System
else
{
Object[] invocationList = _invocationList as Object[];
- if (invocationList != null)
+ if (invocationList != null)
{
int invocationCount = (int)_invocationCount;
return ((Delegate)invocationList[invocationCount - 1]).GetTarget();
@@ -537,7 +537,7 @@ namespace System
else
{
Delegate receiver = _invocationList as Delegate;
- if (receiver != null)
+ if (receiver != null)
return receiver.GetTarget();
}
}
@@ -587,18 +587,18 @@ namespace System
// Otherwise, must be an inner delegate of a SecureDelegate of an open virtual method. In that case, call base implementation
return base.GetMethodImpl();
}
-
+
// this should help inlining
[System.Diagnostics.DebuggerNonUserCode]
- private void ThrowNullThisInDelegateToInstance()
+ private void ThrowNullThisInDelegateToInstance()
{
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtNullInst"));
+ throw new ArgumentException(SR.Arg_DlgtNullInst);
}
[System.Diagnostics.DebuggerNonUserCode]
private void CtorClosed(Object target, IntPtr methodPtr)
{
- if (target == null)
+ if (target == null)
ThrowNullThisInDelegateToInstance();
this._target = target;
this._methodPtr = methodPtr;
@@ -631,35 +631,35 @@ namespace System
{
MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
realDelegate.CtorClosed(target, methodPtr);
- this._invocationList = realDelegate;
+ _invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
- this._invocationCount = GetInvokeMethod();
+ _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);
- this._invocationList = realDelegate;
+ _invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
- this._invocationCount = GetInvokeMethod();
+ _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);
- this._invocationList = realDelegate;
+ _invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
- this._invocationCount = GetInvokeMethod();
+ _invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
@@ -667,11 +667,11 @@ namespace System
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorOpened(target, methodPtr, shuffleThunk);
- this._invocationList = realDelegate;
+ _invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
- this._invocationCount = GetInvokeMethod();
+ _invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
@@ -687,11 +687,11 @@ namespace System
{
MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
realDelegate.CtorVirtualDispatch(target, methodPtr, shuffleThunk);
- this._invocationList = realDelegate;
+ _invocationList = realDelegate;
this._target = this;
this._methodPtr = callThunk;
this._methodPtrAux = creatorMethod;
- this._invocationCount = GetInvokeMethod();
+ _invocationCount = GetInvokeMethod();
}
[System.Diagnostics.DebuggerNonUserCode]
diff --git a/src/mscorlib/src/System/MulticastNotSupportedException.cs b/src/mscorlib/src/System/MulticastNotSupportedException.cs
deleted file mode 100644
index 4fcaa9857d..0000000000
--- a/src/mscorlib/src/System/MulticastNotSupportedException.cs
+++ /dev/null
@@ -1,37 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-// MulticastNotSupportedException
-// This is thrown when you add multiple callbacks to a non-multicast delegate.
-////////////////////////////////////////////////////////////////////////////////
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class MulticastNotSupportedException : SystemException
- {
- public MulticastNotSupportedException()
- : base(SR.Arg_MulticastNotSupportedException)
- {
- HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
- }
-
- public MulticastNotSupportedException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
- }
-
- public MulticastNotSupportedException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
- }
-
- internal MulticastNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/NonSerializedAttribute.cs b/src/mscorlib/src/System/NonSerializedAttribute.cs
index 39f186212a..be05e113c6 100644
--- a/src/mscorlib/src/System/NonSerializedAttribute.cs
+++ b/src/mscorlib/src/System/NonSerializedAttribute.cs
@@ -10,23 +10,24 @@
**
**
============================================================*/
-namespace System
-{
- using System.Reflection;
- [AttributeUsage(AttributeTargets.Field, Inherited=false)]
- public sealed class NonSerializedAttribute : Attribute
+using System.Reflection;
+
+namespace System
+{
+ [AttributeUsage(AttributeTargets.Field, Inherited = false)]
+ public sealed class NonSerializedAttribute : Attribute
{
- internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
- {
+ internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
+ {
if ((field.Attributes & FieldAttributes.NotSerialized) == 0)
return null;
return new NonSerializedAttribute();
}
- internal static bool IsDefined(RuntimeFieldInfo field)
- {
+ internal static bool IsDefined(RuntimeFieldInfo field)
+ {
return (field.Attributes & FieldAttributes.NotSerialized) != 0;
}
diff --git a/src/mscorlib/src/System/NotFiniteNumberException.cs b/src/mscorlib/src/System/NotFiniteNumberException.cs
deleted file mode 100644
index 68e8f88d81..0000000000
--- a/src/mscorlib/src/System/NotFiniteNumberException.cs
+++ /dev/null
@@ -1,71 +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.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class NotFiniteNumberException : ArithmeticException
- {
- private double _offendingNumber;
-
- public NotFiniteNumberException()
- : base(SR.Arg_NotFiniteNumberException)
- {
- _offendingNumber = 0;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
- }
-
- public NotFiniteNumberException(double offendingNumber)
- : base()
- {
- _offendingNumber = offendingNumber;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
- }
-
- public NotFiniteNumberException(String message)
- : base(message)
- {
- _offendingNumber = 0;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
- }
-
- public NotFiniteNumberException(String message, double offendingNumber)
- : base(message)
- {
- _offendingNumber = offendingNumber;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
- }
-
- public NotFiniteNumberException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_NOTFINITENUMBER;
- }
-
- public NotFiniteNumberException(String message, double offendingNumber, Exception innerException)
- : base(message, innerException)
- {
- _offendingNumber = offendingNumber;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
- }
-
- protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- _offendingNumber = info.GetInt32("OffendingNumber");
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
- info.AddValue("OffendingNumber", _offendingNumber, typeof(Int32));
- }
-
- public double OffendingNumber
- {
- get { return _offendingNumber; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/NotImplementedException.cs b/src/mscorlib/src/System/NotImplementedException.cs
deleted file mode 100644
index 4d141eac8c..0000000000
--- a/src/mscorlib/src/System/NotImplementedException.cs
+++ /dev/null
@@ -1,40 +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 thrown when a requested method or operation is not
-** implemented.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class NotImplementedException : SystemException
- {
- public NotImplementedException()
- : base(SR.Arg_NotImplementedException)
- {
- HResult = __HResults.E_NOTIMPL;
- }
- public NotImplementedException(String message)
- : base(message)
- {
- HResult = __HResults.E_NOTIMPL;
- }
- public NotImplementedException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.E_NOTIMPL;
- }
-
- protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/NotSupportedException.cs b/src/mscorlib/src/System/NotSupportedException.cs
deleted file mode 100644
index 21b2d54a46..0000000000
--- a/src/mscorlib/src/System/NotSupportedException.cs
+++ /dev/null
@@ -1,41 +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: For methods that should be implemented on subclasses.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class NotSupportedException : SystemException
- {
- public NotSupportedException()
- : base(SR.Arg_NotSupportedException)
- {
- HResult = __HResults.COR_E_NOTSUPPORTED;
- }
-
- public NotSupportedException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_NOTSUPPORTED;
- }
-
- public NotSupportedException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_NOTSUPPORTED;
- }
-
- protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/NullReferenceException.cs b/src/mscorlib/src/System/NullReferenceException.cs
deleted file mode 100644
index 0aa5c6197a..0000000000
--- a/src/mscorlib/src/System/NullReferenceException.cs
+++ /dev/null
@@ -1,41 +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 class for dereferencing a null reference.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class NullReferenceException : SystemException
- {
- public NullReferenceException()
- : base(SR.Arg_NullReferenceException)
- {
- HResult = __HResults.COR_E_NULLREFERENCE;
- }
-
- public NullReferenceException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_NULLREFERENCE;
- }
-
- public NullReferenceException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_NULLREFERENCE;
- }
-
- protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Nullable.cs b/src/mscorlib/src/System/Nullable.cs
index 5ade2875c5..31a62ecea8 100644
--- a/src/mscorlib/src/System/Nullable.cs
+++ b/src/mscorlib/src/System/Nullable.cs
@@ -3,18 +3,18 @@
// See the LICENSE file in the project root for more information.
- using System;
+using System;
+
+using System.Globalization;
+using System.Reflection;
+using System.Collections.Generic;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Security;
+using System.Diagnostics.Contracts;
namespace System
{
- using System.Globalization;
- using System.Reflection;
- using System.Collections.Generic;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Security;
- using System.Diagnostics.Contracts;
-
// Warning, don't put System.Runtime.Serialization.On*Serializ*Attribute
// on this class without first fixing ObjectClone::InvokeVtsCallbacks
// Also, because we have special type system support that says a a boxed Nullable<T>
@@ -25,25 +25,31 @@ namespace System
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct Nullable<T> where T : struct
{
- private bool hasValue;
+ private bool hasValue;
internal T value;
[System.Runtime.Versioning.NonVersionable]
- public Nullable(T value) {
+ public Nullable(T value)
+ {
this.value = value;
- this.hasValue = true;
- }
+ hasValue = true;
+ }
- public bool HasValue {
+ public bool HasValue
+ {
[System.Runtime.Versioning.NonVersionable]
- get {
+ get
+ {
return hasValue;
- }
- }
+ }
+ }
- public T Value {
- get {
- if (!hasValue) {
+ public T Value
+ {
+ get
+ {
+ if (!hasValue)
+ {
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue);
}
return value;
@@ -51,36 +57,43 @@ namespace System
}
[System.Runtime.Versioning.NonVersionable]
- public T GetValueOrDefault() {
+ public T GetValueOrDefault()
+ {
return value;
}
[System.Runtime.Versioning.NonVersionable]
- public T GetValueOrDefault(T defaultValue) {
+ public T GetValueOrDefault(T defaultValue)
+ {
return hasValue ? value : defaultValue;
}
- public override bool Equals(object other) {
+ public override bool Equals(object other)
+ {
if (!hasValue) return other == null;
if (other == null) return false;
return value.Equals(other);
}
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return hasValue ? value.GetHashCode() : 0;
}
- public override string ToString() {
+ public override string ToString()
+ {
return hasValue ? value.ToString() : "";
}
[System.Runtime.Versioning.NonVersionable]
- public static implicit operator Nullable<T>(T value) {
+ public static implicit operator Nullable<T>(T value)
+ {
return new Nullable<T>(value);
}
[System.Runtime.Versioning.NonVersionable]
- public static explicit operator T(Nullable<T> value) {
+ public static explicit operator T(Nullable<T> value)
+ {
return value.Value;
}
@@ -93,48 +106,54 @@ namespace System
// public string ToString(string format)
// public string ToString(IFormatProvider provider)
// public string ToString(string format, IFormatProvider provider)
-
+
// The following newly obsoleted methods were removed:
// string IFormattable.ToString(string format, IFormatProvider provider)
// int IComparable.CompareTo(object other)
// int IComparable<Nullable<T>>.CompareTo(Nullable<T> other)
// bool IEquatable<Nullable<T>>.Equals(Nullable<T> other)
- }
-
+ }
+
public static class Nullable
{
public static int Compare<T>(Nullable<T> n1, Nullable<T> n2) where T : struct
{
- if (n1.HasValue) {
+ if (n1.HasValue)
+ {
if (n2.HasValue) return Comparer<T>.Default.Compare(n1.value, n2.value);
return 1;
}
if (n2.HasValue) return -1;
- return 0;
- }
-
+ return 0;
+ }
+
public static bool Equals<T>(Nullable<T> n1, Nullable<T> n2) where T : struct
{
- if (n1.HasValue) {
+ if (n1.HasValue)
+ {
if (n2.HasValue) return EqualityComparer<T>.Default.Equals(n1.value, n2.value);
return false;
- }
+ }
if (n2.HasValue) return false;
- return true;
- }
+ return true;
+ }
// If the type provided is not a Nullable Type, return null.
// Otherwise, returns the underlying type of the Nullable type
- public static Type GetUnderlyingType(Type nullableType) {
- if((object)nullableType == null) {
+ public static Type GetUnderlyingType(Type nullableType)
+ {
+ if ((object)nullableType == null)
+ {
throw new ArgumentNullException(nameof(nullableType));
}
Contract.EndContractBlock();
Type result = null;
- if( nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition) {
+ if (nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition)
+ {
// instantiated generic type only
Type genericType = nullableType.GetGenericTypeDefinition();
- if( Object.ReferenceEquals(genericType, typeof(Nullable<>))) {
+ if (Object.ReferenceEquals(genericType, typeof(Nullable<>)))
+ {
result = nullableType.GetGenericArguments()[0];
}
}
@@ -151,5 +170,5 @@ namespace System
// public static object ToObject<T>(Nullable<T> value)
// public static object Wrap(object value, Type type)
// public static object Unwrap(object value)
- }
+ }
}
diff --git a/src/mscorlib/src/System/Number.cs b/src/mscorlib/src/System/Number.cs
index 66d05673a6..b30d4e643f 100644
--- a/src/mscorlib/src/System/Number.cs
+++ b/src/mscorlib/src/System/Number.cs
@@ -2,18 +2,19 @@
// 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 {
-
- using System;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Text;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Globalization;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Security;
+using System.Text;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// The Number class implements methods for formatting and parsing
// numeric values. To format and parse numeric values, applications should
// use the Format and Parse methods provided by the numeric
@@ -287,9 +288,10 @@ namespace System {
[System.Runtime.CompilerServices.FriendAccessAllowed]
internal class Number
{
- private Number() {
+ private Number()
+ {
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatDecimal(Decimal value, String format, NumberFormatInfo info);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -304,7 +306,7 @@ namespace System {
public static extern String FormatUInt64(ulong value, String format, NumberFormatInfo info);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatSingle(float value, String format, NumberFormatInfo info);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public unsafe static extern Boolean NumberBufferToDecimal(byte* number, ref Decimal value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -332,27 +334,29 @@ namespace System {
// structure, except for the digits, and pack those values into the byte buffer
// if called out to managed.
[System.Runtime.CompilerServices.FriendAccessAllowed]
- internal unsafe struct NumberBuffer {
-
+ internal unsafe struct NumberBuffer
+ {
// Enough space for NumberMaxDigit characters plus null and 3 32 bit integers and a pointer
public static readonly Int32 NumberBufferBytes = 12 + ((NumberMaxDigits + 1) * 2) + IntPtr.Size;
- private Byte * baseAddress;
- public Char * digits;
+ private Byte* baseAddress;
+ public Char* digits;
public Int32 precision;
public Int32 scale;
public Boolean sign;
- public NumberBuffer(Byte* stackBuffer) {
- this.baseAddress = stackBuffer;
- this.digits = (((Char*) stackBuffer) + 6);
+ public NumberBuffer(Byte* stackBuffer)
+ {
+ baseAddress = stackBuffer;
+ this.digits = (((Char*)stackBuffer) + 6);
this.precision = 0;
this.scale = 0;
this.sign = false;
}
- public Byte* PackForNative() {
- Int32* baseInteger = (Int32*) baseAddress;
+ public Byte* PackForNative()
+ {
+ Int32* baseInteger = (Int32*)baseAddress;
baseInteger[0] = precision;
baseInteger[1] = scale;
baseInteger[2] = sign ? 1 : 0;
@@ -360,55 +364,67 @@ namespace System {
}
}
- private static Boolean HexNumberToInt32(ref NumberBuffer number, ref Int32 value) {
+ private static Boolean HexNumberToInt32(ref NumberBuffer number, ref Int32 value)
+ {
UInt32 passedValue = 0;
Boolean returnValue = HexNumberToUInt32(ref number, ref passedValue);
value = (Int32)passedValue;
return returnValue;
}
- private static Boolean HexNumberToInt64(ref NumberBuffer number, ref Int64 value) {
+ private static Boolean HexNumberToInt64(ref NumberBuffer number, ref Int64 value)
+ {
UInt64 passedValue = 0;
Boolean returnValue = HexNumberToUInt64(ref number, ref passedValue);
value = (Int64)passedValue;
return returnValue;
}
- private unsafe static Boolean HexNumberToUInt32(ref NumberBuffer number, ref UInt32 value) {
-
+ private unsafe static Boolean HexNumberToUInt32(ref NumberBuffer number, ref UInt32 value)
+ {
Int32 i = number.scale;
- if (i > UInt32Precision || i < number.precision) {
+ if (i > UInt32Precision || i < number.precision)
+ {
return false;
}
Char* p = number.digits;
Debug.Assert(p != null, "");
UInt32 n = 0;
- while (--i >= 0) {
- if (n > ((UInt32)0xFFFFFFFF / 16)) {
+ while (--i >= 0)
+ {
+ if (n > ((UInt32)0xFFFFFFFF / 16))
+ {
return false;
}
n *= 16;
- if (*p != '\0') {
+ if (*p != '\0')
+ {
UInt32 newN = n;
- if (*p != '\0') {
- if (*p >= '0' && *p <= '9') {
+ if (*p != '\0')
+ {
+ if (*p >= '0' && *p <= '9')
+ {
newN += (UInt32)(*p - '0');
}
- else {
- if (*p >= 'A' && *p <= 'F') {
+ else
+ {
+ if (*p >= 'A' && *p <= 'F')
+ {
newN += (UInt32)((*p - 'A') + 10);
}
- else {
+ else
+ {
Debug.Assert(*p >= 'a' && *p <= 'f', "");
newN += (UInt32)((*p - 'a') + 10);
}
}
p++;
}
-
+
// Detect an overflow here...
- if (newN < n) {
+ if (newN < n)
+ {
return false;
}
n = newN;
@@ -418,41 +434,51 @@ namespace System {
return true;
}
- private unsafe static Boolean HexNumberToUInt64(ref NumberBuffer number, ref UInt64 value) {
-
+ private unsafe static Boolean HexNumberToUInt64(ref NumberBuffer number, ref UInt64 value)
+ {
Int32 i = number.scale;
- if (i > UInt64Precision || i < number.precision) {
+ if (i > UInt64Precision || i < number.precision)
+ {
return false;
}
Char* p = number.digits;
Debug.Assert(p != null, "");
-
+
UInt64 n = 0;
- while (--i >= 0) {
- if (n > (0xFFFFFFFFFFFFFFFF / 16)) {
+ while (--i >= 0)
+ {
+ if (n > (0xFFFFFFFFFFFFFFFF / 16))
+ {
return false;
}
n *= 16;
- if (*p != '\0') {
- UInt64 newN = n;
- if (*p != '\0') {
- if (*p >= '0' && *p <= '9') {
+ if (*p != '\0')
+ {
+ UInt64 newN = n;
+ if (*p != '\0')
+ {
+ if (*p >= '0' && *p <= '9')
+ {
newN += (UInt64)(*p - '0');
}
- else {
- if (*p >= 'A' && *p <= 'F') {
+ else
+ {
+ if (*p >= 'A' && *p <= 'F')
+ {
newN += (UInt64)((*p - 'A') + 10);
}
- else {
+ else
+ {
Debug.Assert(*p >= 'a' && *p <= 'f', "");
newN += (UInt64)((*p - 'a') + 10);
}
}
p++;
}
-
+
// Detect an overflow here...
- if (newN < n) {
+ if (newN < n)
+ {
return false;
}
n = newN;
@@ -462,36 +488,45 @@ namespace System {
return true;
}
- private static Boolean IsWhite(char ch) {
+ private static Boolean IsWhite(char ch)
+ {
return (((ch) == 0x20) || ((ch) >= 0x09 && (ch) <= 0x0D));
}
- private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value) {
-
+ private unsafe static Boolean NumberToInt32(ref NumberBuffer number, ref Int32 value)
+ {
Int32 i = number.scale;
- if (i > Int32Precision || i < number.precision) {
+ if (i > Int32Precision || i < number.precision)
+ {
return false;
}
- char * p = number.digits;
+ char* p = number.digits;
Debug.Assert(p != null, "");
Int32 n = 0;
- while (--i >= 0) {
- if ((UInt32)n > (0x7FFFFFFF / 10)) {
+ while (--i >= 0)
+ {
+ if ((UInt32)n > (0x7FFFFFFF / 10))
+ {
return false;
}
n *= 10;
- if (*p != '\0') {
+ if (*p != '\0')
+ {
n += (Int32)(*p++ - '0');
}
}
- if (number.sign) {
+ if (number.sign)
+ {
n = -n;
- if (n > 0) {
+ if (n > 0)
+ {
return false;
}
}
- else {
- if (n < 0) {
+ else
+ {
+ if (n < 0)
+ {
return false;
}
}
@@ -499,32 +534,40 @@ namespace System {
return true;
}
- private unsafe static Boolean NumberToInt64(ref NumberBuffer number, ref Int64 value) {
-
+ private unsafe static Boolean NumberToInt64(ref NumberBuffer number, ref Int64 value)
+ {
Int32 i = number.scale;
- if (i > Int64Precision || i < number.precision) {
+ if (i > Int64Precision || i < number.precision)
+ {
return false;
}
char* p = number.digits;
Debug.Assert(p != null, "");
Int64 n = 0;
- while (--i >= 0) {
- if ((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10)) {
+ while (--i >= 0)
+ {
+ if ((UInt64)n > (0x7FFFFFFFFFFFFFFF / 10))
+ {
return false;
}
n *= 10;
- if (*p != '\0') {
+ if (*p != '\0')
+ {
n += (Int32)(*p++ - '0');
}
}
- if (number.sign) {
+ if (number.sign)
+ {
n = -n;
- if (n > 0) {
+ if (n > 0)
+ {
return false;
}
}
- else {
- if (n < 0) {
+ else
+ {
+ if (n < 0)
+ {
return false;
}
}
@@ -532,24 +575,29 @@ namespace System {
return true;
}
- private unsafe static Boolean NumberToUInt32(ref NumberBuffer number, ref UInt32 value) {
-
+ private unsafe static Boolean NumberToUInt32(ref NumberBuffer number, ref UInt32 value)
+ {
Int32 i = number.scale;
- if (i > UInt32Precision || i < number.precision || number.sign ) {
+ if (i > UInt32Precision || i < number.precision || number.sign)
+ {
return false;
}
char* p = number.digits;
Debug.Assert(p != null, "");
UInt32 n = 0;
- while (--i >= 0) {
- if (n > (0xFFFFFFFF / 10)) {
+ while (--i >= 0)
+ {
+ if (n > (0xFFFFFFFF / 10))
+ {
return false;
}
n *= 10;
- if (*p != '\0') {
+ if (*p != '\0')
+ {
UInt32 newN = n + (UInt32)(*p++ - '0');
// Detect an overflow here...
- if (newN < n) {
+ if (newN < n)
+ {
return false;
}
n = newN;
@@ -559,24 +607,29 @@ namespace System {
return true;
}
- private unsafe static Boolean NumberToUInt64(ref NumberBuffer number, ref UInt64 value) {
-
+ private unsafe static Boolean NumberToUInt64(ref NumberBuffer number, ref UInt64 value)
+ {
Int32 i = number.scale;
- if (i > UInt64Precision || i < number.precision || number.sign) {
+ if (i > UInt64Precision || i < number.precision || number.sign)
+ {
return false;
}
- char * p = number.digits;
+ char* p = number.digits;
Debug.Assert(p != null, "");
UInt64 n = 0;
- while (--i >= 0) {
- if (n > (0xFFFFFFFFFFFFFFFF / 10)) {
+ while (--i >= 0)
+ {
+ if (n > (0xFFFFFFFFFFFFFFFF / 10))
+ {
return false;
}
n *= 10;
- if (*p != '\0') {
+ if (*p != '\0')
+ {
UInt64 newN = n + (UInt64)(*p++ - '0');
// Detect an overflow here...
- if (newN < n) {
+ if (newN < n)
+ {
return false;
}
n = newN;
@@ -586,20 +639,24 @@ namespace System {
return true;
}
- private unsafe static char * MatchChars(char* p, string str) {
- fixed (char* stringPointer = str) {
+ private unsafe static char* MatchChars(char* p, string str)
+ {
+ fixed (char* stringPointer = str)
+ {
return MatchChars(p, stringPointer);
}
}
- private unsafe static char * MatchChars(char* p, char* str) {
+ private unsafe static char* MatchChars(char* p, char* str)
+ {
Debug.Assert(p != null && str != null, "");
- if (*str == '\0') {
+ if (*str == '\0')
+ {
return null;
}
- // We only hurt the failure case
- // This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a
- // space character we use 0x20 space character instead to mean the same.
+ // We only hurt the failure case
+ // This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a
+ // space character we use 0x20 space character instead to mean the same.
while (*p == *str || (*str == '\u00a0' && *p == '\u0020'))
{
p++;
@@ -609,96 +666,113 @@ namespace System {
return null;
}
- internal unsafe static Decimal ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Decimal ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Decimal result = 0;
-
+
StringToNumber(value, options, ref number, numfmt, true);
- if (!NumberBufferToDecimal(number.PackForNative(), ref result)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Decimal"));
+ if (!NumberBufferToDecimal(number.PackForNative(), ref result))
+ {
+ throw new OverflowException(SR.Overflow_Decimal);
}
return result;
}
- internal unsafe static Double ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt) {
- if (value == null) {
+ internal unsafe static Double ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Double d = 0;
-
- if (!TryStringToNumber(value, options, ref number, numfmt, false)) {
+
+ if (!TryStringToNumber(value, options, ref number, numfmt, false))
+ {
//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)) {
+ if (sTrim.Equals(numfmt.PositiveInfinitySymbol))
+ {
return Double.PositiveInfinity;
}
- if (sTrim.Equals(numfmt.NegativeInfinitySymbol)) {
+ if (sTrim.Equals(numfmt.NegativeInfinitySymbol))
+ {
return Double.NegativeInfinity;
}
- if (sTrim.Equals(numfmt.NaNSymbol)) {
+ if (sTrim.Equals(numfmt.NaNSymbol))
+ {
return Double.NaN;
}
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
}
- if (!NumberBufferToDouble(number.PackForNative(), ref d)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Double"));
+ if (!NumberBufferToDouble(number.PackForNative(), ref d))
+ {
+ throw new OverflowException(SR.Overflow_Double);
}
return d;
}
- internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Int32 i = 0;
-
+
StringToNumber(s, style, ref number, info, false);
- if ((style & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToInt32(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToInt32(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_Int32);
}
}
- else {
- if (!NumberToInt32(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
+ else
+ {
+ if (!NumberToInt32(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_Int32);
}
}
- return i;
+ return i;
}
- internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Int64 i = 0;
StringToNumber(value, options, ref number, numfmt, false);
- if ((options & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToInt64(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
+ if ((options & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToInt64(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_Int64);
}
}
- else {
- if (!NumberToInt64(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Int64"));
+ else
+ {
+ if (!NumberToInt64(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_Int64);
}
}
return i;
}
- private unsafe static Boolean ParseNumber(ref char * str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal) {
-
+ private unsafe static Boolean ParseNumber(ref char* str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal)
+ {
const Int32 StateSign = 0x0001;
const Int32 StateParens = 0x0002;
const Int32 StateDigits = 0x0004;
@@ -712,8 +786,9 @@ namespace System {
string groupSep; // group separator from NumberFormatInfo.
string currSymbol = null; // currency symbol from NumberFormatInfo.
- Boolean parsingCurrency = false;
- if ((options & NumberStyles.AllowCurrencySymbol) != 0) {
+ Boolean parsingCurrency = false;
+ if ((options & NumberStyles.AllowCurrencySymbol) != 0)
+ {
currSymbol = numfmt.CurrencySymbol;
// The idea here is to match the currency separators and on failure match the number separators to keep the perf of VB's IsNumeric fast.
@@ -722,7 +797,8 @@ namespace System {
groupSep = numfmt.CurrencyGroupSeparator;
parsingCurrency = true;
}
- else {
+ else
+ {
decSep = numfmt.NumberDecimalSeparator;
groupSep = numfmt.NumberGroupSeparator;
}
@@ -730,69 +806,85 @@ namespace System {
Int32 state = 0;
Boolean bigNumber = (sb != null); // When a StringBuilder is provided then we use it in place of the number.digits char[50]
Int32 maxParseDigits = bigNumber ? Int32.MaxValue : NumberMaxDigits;
-
+
char* p = str;
char ch = *p;
char* next;
- while (true) {
+ while (true)
+ {
// Eat whitespace unless we've found a sign which isn't followed by a currency symbol.
// "-Kr 1231.47" is legal but "- 1231.47" is not.
- if (!IsWhite(ch) || (options & NumberStyles.AllowLeadingWhite) == 0 || ((state & StateSign) != 0 && ((state & StateCurrency) == 0 && numfmt.NumberNegativePattern != 2))){
- if ((((options & NumberStyles.AllowLeadingSign) != 0) && (state & StateSign) == 0) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || ((next = MatchChars(p, numfmt.NegativeSign)) != null && (number.sign = true)))){
- state |= StateSign;
- p = next - 1;
- }
- else if (ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) {
- state |= StateSign | StateParens;
- number.sign = true;
- }
- else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) {
- state |= StateCurrency;
- currSymbol = null;
- // We already found the currency symbol. There should not be more currency symbols. Set
- // currSymbol to NULL so that we won't search it again in the later code path.
- p = next - 1;
- }
- else {
- break;
- }
- }
+ if (!IsWhite(ch) || (options & NumberStyles.AllowLeadingWhite) == 0 || ((state & StateSign) != 0 && ((state & StateCurrency) == 0 && numfmt.NumberNegativePattern != 2)))
+ {
+ if ((((options & NumberStyles.AllowLeadingSign) != 0) && (state & StateSign) == 0) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || ((next = MatchChars(p, numfmt.NegativeSign)) != null && (number.sign = true))))
+ {
+ state |= StateSign;
+ p = next - 1;
+ }
+ else if (ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0))
+ {
+ state |= StateSign | StateParens;
+ number.sign = true;
+ }
+ else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null)
+ {
+ state |= StateCurrency;
+ currSymbol = null;
+ // We already found the currency symbol. There should not be more currency symbols. Set
+ // currSymbol to NULL so that we won't search it again in the later code path.
+ p = next - 1;
+ }
+ else
+ {
+ break;
+ }
+ }
ch = *++p;
}
Int32 digCount = 0;
Int32 digEnd = 0;
- while (true) {
- if ((ch >= '0' && ch <= '9') || (((options & NumberStyles.AllowHexSpecifier) != 0) && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')))) {
+ while (true)
+ {
+ if ((ch >= '0' && ch <= '9') || (((options & NumberStyles.AllowHexSpecifier) != 0) && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))))
+ {
state |= StateDigits;
- if (ch != '0' || (state & StateNonZero) != 0 || (bigNumber && ((options & NumberStyles.AllowHexSpecifier) != 0))) {
- if (digCount < maxParseDigits) {
+ if (ch != '0' || (state & StateNonZero) != 0 || (bigNumber && ((options & NumberStyles.AllowHexSpecifier) != 0)))
+ {
+ if (digCount < maxParseDigits)
+ {
if (bigNumber)
sb.Append(ch);
else
number.digits[digCount++] = ch;
- if (ch != '0' || parseDecimal) {
+ if (ch != '0' || parseDecimal)
+ {
digEnd = digCount;
}
}
- if ((state & StateDecimal) == 0) {
+ if ((state & StateDecimal) == 0)
+ {
number.scale++;
}
state |= StateNonZero;
}
- else if ((state & StateDecimal) != 0) {
+ else if ((state & StateDecimal) != 0)
+ {
number.scale--;
}
}
- else if (((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberDecimalSeparator)) != null)) {
+ else if (((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberDecimalSeparator)) != null))
+ {
state |= StateDecimal;
p = next - 1;
}
- else if (((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberGroupSeparator)) != null)) {
+ else if (((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberGroupSeparator)) != null))
+ {
p = next - 1;
}
- else {
+ else
+ {
break;
}
ch = *++p;
@@ -804,64 +896,84 @@ namespace System {
sb.Append('\0');
else
number.digits[digEnd] = '\0';
- if ((state & StateDigits) != 0) {
- if ((ch == 'E' || ch == 'e') && ((options & NumberStyles.AllowExponent) != 0)) {
+ if ((state & StateDigits) != 0)
+ {
+ if ((ch == 'E' || ch == 'e') && ((options & NumberStyles.AllowExponent) != 0))
+ {
char* temp = p;
ch = *++p;
- if ((next = MatchChars(p, numfmt.positiveSign)) != null) {
+ if ((next = MatchChars(p, numfmt.positiveSign)) != null)
+ {
ch = *(p = next);
}
- else if ((next = MatchChars(p, numfmt.negativeSign)) != null) {
+ else if ((next = MatchChars(p, numfmt.negativeSign)) != null)
+ {
ch = *(p = next);
negExp = true;
}
- if (ch >= '0' && ch <= '9') {
+ if (ch >= '0' && ch <= '9')
+ {
Int32 exp = 0;
- do {
+ do
+ {
exp = exp * 10 + (ch - '0');
ch = *++p;
- if (exp > 1000) {
+ if (exp > 1000)
+ {
exp = 9999;
- while (ch >= '0' && ch <= '9') {
+ while (ch >= '0' && ch <= '9')
+ {
ch = *++p;
}
}
} while (ch >= '0' && ch <= '9');
- if (negExp) {
+ if (negExp)
+ {
exp = -exp;
}
number.scale += exp;
}
- else {
+ else
+ {
p = temp;
ch = *p;
}
}
- while (true) {
- if (!IsWhite(ch) || (options & NumberStyles.AllowTrailingWhite) == 0){
- if (((options & NumberStyles.AllowTrailingSign) != 0 && ((state & StateSign) == 0)) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || (((next = MatchChars(p, numfmt.NegativeSign)) != null) && (number.sign = true)))) {
- state |= StateSign;
- p = next - 1;
- }
- else if (ch == ')' && ((state & StateParens) != 0)) {
- state &= ~StateParens;
- }
- else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) {
- currSymbol = null;
- p = next - 1;
- }
- else {
- break;
- }
- }
+ while (true)
+ {
+ if (!IsWhite(ch) || (options & NumberStyles.AllowTrailingWhite) == 0)
+ {
+ if (((options & NumberStyles.AllowTrailingSign) != 0 && ((state & StateSign) == 0)) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || (((next = MatchChars(p, numfmt.NegativeSign)) != null) && (number.sign = true))))
+ {
+ state |= StateSign;
+ p = next - 1;
+ }
+ else if (ch == ')' && ((state & StateParens) != 0))
+ {
+ state &= ~StateParens;
+ }
+ else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null)
+ {
+ currSymbol = null;
+ p = next - 1;
+ }
+ else
+ {
+ break;
+ }
+ }
ch = *++p;
}
- if ((state & StateParens) == 0) {
- if ((state & StateNonZero) == 0) {
- if (!parseDecimal) {
+ if ((state & StateParens) == 0)
+ {
+ if ((state & StateNonZero) == 0)
+ {
+ if (!parseDecimal)
+ {
number.scale = 0;
}
- if ((state & StateDecimal) == 0) {
+ if ((state & StateDecimal) == 0)
+ {
number.sign = false;
}
}
@@ -873,200 +985,242 @@ namespace System {
return false;
}
- internal unsafe static Single ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt) {
- if (value == null) {
+ internal unsafe static Single ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Double d = 0;
- if (!TryStringToNumber(value, options, ref number, numfmt, false)) {
+ if (!TryStringToNumber(value, options, ref number, numfmt, false))
+ {
//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)) {
+ if (sTrim.Equals(numfmt.PositiveInfinitySymbol))
+ {
return Single.PositiveInfinity;
}
- if (sTrim.Equals(numfmt.NegativeInfinitySymbol)) {
+ if (sTrim.Equals(numfmt.NegativeInfinitySymbol))
+ {
return Single.NegativeInfinity;
}
- if (sTrim.Equals(numfmt.NaNSymbol)) {
+ if (sTrim.Equals(numfmt.NaNSymbol))
+ {
return Single.NaN;
}
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ throw new FormatException(SR.Format_InvalidString);
}
- if (!NumberBufferToDouble(number.PackForNative(), ref d)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Single"));
+ if (!NumberBufferToDouble(number.PackForNative(), ref d))
+ {
+ throw new OverflowException(SR.Overflow_Single);
}
Single castSingle = (Single)d;
- if (Single.IsInfinity(castSingle)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_Single"));
+ if (Single.IsInfinity(castSingle))
+ {
+ throw new OverflowException(SR.Overflow_Single);
}
return castSingle;
}
- internal unsafe static UInt32 ParseUInt32(String value, NumberStyles options, NumberFormatInfo numfmt) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static UInt32 ParseUInt32(String value, NumberStyles options, NumberFormatInfo numfmt)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
UInt32 i = 0;
-
+
StringToNumber(value, options, ref number, numfmt, false);
- if ((options & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToUInt32(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
+ if ((options & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToUInt32(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_UInt32);
}
}
- else {
- if (!NumberToUInt32(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt32"));
+ else
+ {
+ if (!NumberToUInt32(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_UInt32);
}
}
-
+
return i;
}
- internal unsafe static UInt64 ParseUInt64(String value, NumberStyles options, NumberFormatInfo numfmt) {
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static UInt64 ParseUInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
UInt64 i = 0;
StringToNumber(value, options, ref number, numfmt, false);
- if ((options & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToUInt64(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt64"));
+ if ((options & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToUInt64(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_UInt64);
}
}
- else {
- if (!NumberToUInt64(ref number, ref i)) {
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt64"));
+ else
+ {
+ if (!NumberToUInt64(ref number, ref i))
+ {
+ throw new OverflowException(SR.Overflow_UInt64);
}
}
return i;
}
- private unsafe static void StringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal) {
-
- if (str == null) {
+ private unsafe static void StringToNumber(String 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) {
- char * p = stringPointer;
- if (!ParseNumber(ref p, options, ref number, null, info , parseDecimal)
- || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) {
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
+ fixed (char* stringPointer = str)
+ {
+ char* p = stringPointer;
+ if (!ParseNumber(ref p, options, ref number, null, info, parseDecimal)
+ || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer))))
+ {
+ throw new FormatException(SR.Format_InvalidString);
}
}
}
-
- private static Boolean TrailingZeros(String s, Int32 index) {
+
+ private static Boolean TrailingZeros(String 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++) {
- if (s[i] != '\0') {
+ for (int i = index; i < s.Length; i++)
+ {
+ if (s[i] != '\0')
+ {
return false;
}
}
return true;
}
- internal unsafe static Boolean TryParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt, out Decimal result) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt, out Decimal result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
-
- if (!TryStringToNumber(value, options, ref number, numfmt, true)) {
+
+ if (!TryStringToNumber(value, options, ref number, numfmt, true))
+ {
return false;
}
- if (!NumberBufferToDecimal(number.PackForNative(), ref result)) {
+ if (!NumberBufferToDecimal(number.PackForNative(), ref result))
+ {
return false;
}
return true;
}
- internal unsafe static Boolean TryParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt, out Double result) {
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt, out Double result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
- if (!TryStringToNumber(value, options, ref number, numfmt, false)) {
+ if (!TryStringToNumber(value, options, ref number, numfmt, false))
+ {
return false;
}
- if (!NumberBufferToDouble(number.PackForNative(), ref result)) {
+ if (!NumberBufferToDouble(number.PackForNative(), ref result))
+ {
return false;
}
return true;
}
- internal unsafe static Boolean TryParseInt32(String s, NumberStyles style, NumberFormatInfo info, out Int32 result) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseInt32(String s, NumberStyles style, NumberFormatInfo info, out Int32 result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
-
- if (!TryStringToNumber(s, style, ref number, info, false)) {
+
+ if (!TryStringToNumber(s, style, ref number, info, false))
+ {
return false;
}
- if ((style & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToInt32(ref number, ref result)) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToInt32(ref number, ref result))
+ {
return false;
}
}
- else {
- if (!NumberToInt32(ref number, ref result)) {
+ else
+ {
+ if (!NumberToInt32(ref number, ref result))
+ {
return false;
}
}
- return true;
+ return true;
}
- internal unsafe static Boolean TryParseInt64(String s, NumberStyles style, NumberFormatInfo info, out Int64 result) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseInt64(String s, NumberStyles style, NumberFormatInfo info, out Int64 result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
-
- if (!TryStringToNumber(s, style, ref number, info, false)) {
+
+ if (!TryStringToNumber(s, style, ref number, info, false))
+ {
return false;
}
- if ((style & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToInt64(ref number, ref result)) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToInt64(ref number, ref result))
+ {
return false;
}
}
- else {
- if (!NumberToInt64(ref number, ref result)) {
+ else
+ {
+ if (!NumberToInt64(ref number, ref result))
+ {
return false;
}
}
- return true;
+ return true;
}
- internal unsafe static Boolean TryParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt, out Single result) {
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt, out Single result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
Double d = 0;
- if (!TryStringToNumber(value, options, ref number, numfmt, false)) {
+ if (!TryStringToNumber(value, options, ref number, numfmt, false))
+ {
return false;
}
- if (!NumberBufferToDouble(number.PackForNative(), ref d)) {
+ if (!NumberBufferToDouble(number.PackForNative(), ref d))
+ {
return false;
}
Single castSingle = (Single)d;
- if (Single.IsInfinity(castSingle)) {
+ if (Single.IsInfinity(castSingle))
+ {
return false;
}
@@ -1074,68 +1228,82 @@ namespace System {
return true;
}
- internal unsafe static Boolean TryParseUInt32(String s, NumberStyles style, NumberFormatInfo info, out UInt32 result) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseUInt32(String s, NumberStyles style, NumberFormatInfo info, out UInt32 result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
-
- if (!TryStringToNumber(s, style, ref number, info, false)) {
+
+ if (!TryStringToNumber(s, style, ref number, info, false))
+ {
return false;
}
- if ((style & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToUInt32(ref number, ref result)) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToUInt32(ref number, ref result))
+ {
return false;
}
}
- else {
- if (!NumberToUInt32(ref number, ref result)) {
+ else
+ {
+ if (!NumberToUInt32(ref number, ref result))
+ {
return false;
}
}
- return true;
+ return true;
}
- internal unsafe static Boolean TryParseUInt64(String s, NumberStyles style, NumberFormatInfo info, out UInt64 result) {
-
- Byte * numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
+ internal unsafe static Boolean TryParseUInt64(String s, NumberStyles style, NumberFormatInfo info, out UInt64 result)
+ {
+ Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
result = 0;
-
- if (!TryStringToNumber(s, style, ref number, info, false)) {
+
+ if (!TryStringToNumber(s, style, ref number, info, false))
+ {
return false;
}
- if ((style & NumberStyles.AllowHexSpecifier) != 0) {
- if (!HexNumberToUInt64(ref number, ref result)) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ {
+ if (!HexNumberToUInt64(ref number, ref result))
+ {
return false;
}
}
- else {
- if (!NumberToUInt64(ref number, ref result)) {
+ else
+ {
+ if (!NumberToUInt64(ref number, ref result))
+ {
return false;
}
}
- return true;
+ return true;
}
- internal static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, Boolean parseDecimal) {
+ 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) {
-
- if (str == null) {
+ internal unsafe static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal)
+ {
+ if (str == null)
+ {
return false;
}
Debug.Assert(numfmt != null, "");
- fixed (char* stringPointer = str) {
- char * p = stringPointer;
- if (!ParseNumber(ref p, options, ref number, sb, numfmt, parseDecimal)
- || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) {
+ fixed (char* stringPointer = str)
+ {
+ char* p = stringPointer;
+ if (!ParseNumber(ref p, options, ref number, sb, numfmt, parseDecimal)
+ || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer))))
+ {
return false;
}
}
diff --git a/src/mscorlib/src/System/Object.cs b/src/mscorlib/src/System/Object.cs
index 1f47d8cdef..3c304422ac 100644
--- a/src/mscorlib/src/System/Object.cs
+++ b/src/mscorlib/src/System/Object.cs
@@ -25,200 +25,202 @@ namespace System
using FieldInfo = System.Reflection.FieldInfo;
using BindingFlags = System.Reflection.BindingFlags;
-// The Object is the root class for all object in the CLR System. Object
-// is the super class for all other CLR objects and provide a set of methods and low level
-// services to subclasses. These services include object synchronization and support for clone
-// operations.
-//
- //This class contains no data and does not need to be serializable
-[Serializable]
-[ClassInterface(ClassInterfaceType.AutoDual)]
-[System.Runtime.InteropServices.ComVisible(true)]
-public class Object
-{
- // Creates a new instance of an Object.
- [System.Runtime.Versioning.NonVersionable]
- public Object()
- {
- }
-
- // Returns a String which represents the object instance. The default
- // for an object is to return the fully qualified name of the class.
- //
- public virtual String ToString()
- {
- return GetType().ToString();
- }
-
- // Returns a boolean indicating if the passed in object obj is
- // Equal to this. Equality is defined as object equality for reference
- // types and bitwise equality for value types using a loader trick to
- // replace Equals with EqualsValue for value types).
+ // The Object is the root class for all object in the CLR System. Object
+ // is the super class for all other CLR objects and provide a set of methods and low level
+ // services to subclasses. These services include object synchronization and support for clone
+ // operations.
//
-
- public virtual bool Equals(Object obj)
+ //This class contains no data and does not need to be serializable
+ [Serializable]
+ [ClassInterface(ClassInterfaceType.AutoDual)]
+ [System.Runtime.InteropServices.ComVisible(true)]
+ public class Object
{
- return RuntimeHelpers.Equals(this, obj);
- }
-
- public static bool Equals(Object objA, Object objB)
- {
- if (objA==objB) {
- return true;
+ // Creates a new instance of an Object.
+ [System.Runtime.Versioning.NonVersionable]
+ public Object()
+ {
}
- if (objA==null || objB==null) {
- return false;
+
+ // Returns a String which represents the object instance. The default
+ // for an object is to return the fully qualified name of the class.
+ //
+ public virtual String ToString()
+ {
+ return GetType().ToString();
}
- return objA.Equals(objB);
- }
- [System.Runtime.Versioning.NonVersionable]
- public static bool ReferenceEquals (Object objA, Object objB) {
- return objA == objB;
- }
-
- // GetHashCode is intended to serve as a hash function for this object.
- // Based on the contents of the object, the hash function will return a suitable
- // value with a relatively random distribution over the various inputs.
- //
- // The default implementation returns the sync block index for this instance.
- // Calling it on the same object multiple times will return the same value, so
- // it will technically meet the needs of a hash function, but it's less than ideal.
- // Objects (& especially value classes) should override this method.
- //
- public virtual int GetHashCode()
- {
- return RuntimeHelpers.GetHashCode(this);
- }
-
- // Returns a Type object which represent this object instance.
- //
- [Pure]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern Type GetType();
+ // Returns a boolean indicating if the passed in object obj is
+ // Equal to this. Equality is defined as object equality for reference
+ // types and bitwise equality for value types using a loader trick to
+ // replace Equals with EqualsValue for value types).
+ //
- // Allow an object to free resources before the object is reclaimed by the GC.
- //
- [System.Runtime.Versioning.NonVersionable]
- ~Object()
- {
- }
-
- // Returns a new object instance that is a memberwise copy of this
- // object. This is always a shallow copy of the instance. The method is protected
- // so that other object may only call this method on themselves. It is entended to
- // support the ICloneable interface.
- //
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- protected extern Object MemberwiseClone();
-
-
- // Sets the value specified in the variant on the field
- //
- private void FieldSetter(String typeName, String fieldName, Object val)
- {
- Contract.Requires(typeName != null);
- Contract.Requires(fieldName != null);
+ public virtual bool Equals(Object obj)
+ {
+ return RuntimeHelpers.Equals(this, obj);
+ }
- // Extract the field info object
- FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
+ public static bool Equals(Object objA, Object objB)
+ {
+ if (objA == objB)
+ {
+ return true;
+ }
+ if (objA == null || objB == null)
+ {
+ return false;
+ }
+ return objA.Equals(objB);
+ }
- if (fldInfo.IsInitOnly)
- throw new FieldAccessException(Environment.GetResourceString("FieldAccess_InitOnly"));
+ [System.Runtime.Versioning.NonVersionable]
+ public static bool ReferenceEquals(Object objA, Object objB)
+ {
+ return objA == objB;
+ }
- // Make sure that the value is compatible with the type
- // of field
- Type pt=fldInfo.FieldType;
- if (pt.IsByRef)
+ // GetHashCode is intended to serve as a hash function for this object.
+ // Based on the contents of the object, the hash function will return a suitable
+ // value with a relatively random distribution over the various inputs.
+ //
+ // The default implementation returns the sync block index for this instance.
+ // Calling it on the same object multiple times will return the same value, so
+ // it will technically meet the needs of a hash function, but it's less than ideal.
+ // Objects (& especially value classes) should override this method.
+ //
+ public virtual int GetHashCode()
{
- pt = pt.GetElementType();
+ return RuntimeHelpers.GetHashCode(this);
}
- if (!pt.IsInstanceOfType(val))
+ // Returns a Type object which represent this object instance.
+ //
+ [Pure]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public extern Type GetType();
+
+ // Allow an object to free resources before the object is reclaimed by the GC.
+ //
+ [System.Runtime.Versioning.NonVersionable]
+ ~Object()
{
- val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture);
}
- // Set the value
- fldInfo.SetValue(this, val);
- }
+ // Returns a new object instance that is a memberwise copy of this
+ // object. This is always a shallow copy of the instance. The method is protected
+ // so that other object may only call this method on themselves. It is entended to
+ // support the ICloneable interface.
+ //
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ protected extern Object MemberwiseClone();
- // Gets the value specified in the variant on the field
- //
- private void FieldGetter(String typeName, String fieldName, ref Object val)
- {
- Contract.Requires(typeName != null);
- Contract.Requires(fieldName != null);
- // Extract the field info object
- FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
+ // Sets the value specified in the variant on the field
+ //
+ private void FieldSetter(String typeName, String fieldName, Object val)
+ {
+ Contract.Requires(typeName != null);
+ Contract.Requires(fieldName != null);
- // Get the value
- val = fldInfo.GetValue(this);
- }
+ // Extract the field info object
+ FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
- // Gets the field info object given the type name and field name.
- //
- private FieldInfo GetFieldInfo(String typeName, String fieldName)
- {
- Contract.Requires(typeName != null);
- Contract.Requires(fieldName != null);
- Contract.Ensures(Contract.Result<FieldInfo>() != null);
+ if (fldInfo.IsInitOnly)
+ throw new FieldAccessException(SR.FieldAccess_InitOnly);
- Type t = GetType();
- while(null != t)
- {
- if(t.FullName.Equals(typeName))
+ // Make sure that the value is compatible with the type
+ // of field
+ Type pt = fldInfo.FieldType;
+ if (pt.IsByRef)
{
- break;
+ pt = pt.GetElementType();
}
- t = t.BaseType;
- }
-
- if (null == t)
- {
- throw new ArgumentException();
+ if (!pt.IsInstanceOfType(val))
+ {
+ val = Convert.ChangeType(val, pt, CultureInfo.InvariantCulture);
+ }
+
+ // Set the value
+ fldInfo.SetValue(this, val);
}
- FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public |
- BindingFlags.Instance |
- BindingFlags.IgnoreCase);
- if(null == fldInfo)
+ // Gets the value specified in the variant on the field
+ //
+ private void FieldGetter(String typeName, String fieldName, ref Object val)
{
- throw new ArgumentException();
+ Contract.Requires(typeName != null);
+ Contract.Requires(fieldName != null);
+
+ // Extract the field info object
+ FieldInfo fldInfo = GetFieldInfo(typeName, fieldName);
+
+ // Get the value
+ val = fldInfo.GetValue(this);
}
- return fldInfo;
- }
-}
+ // Gets the field info object given the type name and field name.
+ //
+ private FieldInfo GetFieldInfo(String typeName, String fieldName)
+ {
+ Contract.Requires(typeName != null);
+ Contract.Requires(fieldName != null);
+ Contract.Ensures(Contract.Result<FieldInfo>() != null);
+ Type t = GetType();
+ while (null != t)
+ {
+ if (t.FullName.Equals(typeName))
+ {
+ break;
+ }
-// Internal methodtable used to instantiate the "canonical" methodtable for generic instantiations.
-// The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces
-// involving generics so it is kept deliberately short as to avoid being a nuisance.
+ t = t.BaseType;
+ }
-[Serializable]
-[ClassInterface(ClassInterfaceType.AutoDual)]
-[System.Runtime.InteropServices.ComVisible(true)]
-internal class __Canon
-{
-}
+ if (null == t)
+ {
+ throw new ArgumentException();
+ }
-// This class is used to define the name of the base class library
-internal class CoreLib
-{
- public const string Name = "System.Private.CoreLib";
+ FieldInfo fldInfo = t.GetField(fieldName, BindingFlags.Public |
+ BindingFlags.Instance |
+ BindingFlags.IgnoreCase);
+ if (null == fldInfo)
+ {
+ throw new ArgumentException();
+ }
- public static string FixupCoreLibName(string strToFixup)
- {
- if (!String.IsNullOrEmpty(strToFixup))
- {
- strToFixup = strToFixup.Replace("mscorlib", System.CoreLib.Name);
+ return fldInfo;
}
+ }
+
- return strToFixup;
+ // Internal methodtable used to instantiate the "canonical" methodtable for generic instantiations.
+ // The name "__Canon" will never been seen by users but it will appear a lot in debugger stack traces
+ // involving generics so it is kept deliberately short as to avoid being a nuisance.
+
+ [Serializable]
+ [ClassInterface(ClassInterfaceType.AutoDual)]
+ [System.Runtime.InteropServices.ComVisible(true)]
+ internal class __Canon
+ {
}
-}
+ // This class is used to define the name of the base class library
+ internal class CoreLib
+ {
+ public const string Name = "System.Private.CoreLib";
+
+ public static string FixupCoreLibName(string strToFixup)
+ {
+ if (!String.IsNullOrEmpty(strToFixup))
+ {
+ strToFixup = strToFixup.Replace("mscorlib", System.CoreLib.Name);
+ }
+
+ return strToFixup;
+ }
+ }
}
diff --git a/src/mscorlib/src/System/ObjectDisposedException.cs b/src/mscorlib/src/System/ObjectDisposedException.cs
deleted file mode 100644
index 1f77b1f009..0000000000
--- a/src/mscorlib/src/System/ObjectDisposedException.cs
+++ /dev/null
@@ -1,82 +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.Globalization;
-using System.Runtime.Serialization;
-
-namespace System
-{
- /// <devdoc>
- /// <para> The exception that is thrown when accessing an object that was
- /// disposed.</para>
- /// </devdoc>
- [Serializable]
- public class ObjectDisposedException : InvalidOperationException
- {
- private String _objectName;
-
- // This constructor should only be called by the EE (COMPlusThrow)
- private ObjectDisposedException() :
- this(null, SR.ObjectDisposed_Generic)
- {
- }
-
- public ObjectDisposedException(String objectName) :
- this(objectName, SR.ObjectDisposed_Generic)
- {
- }
-
- public ObjectDisposedException(String objectName, String message) : base(message)
- {
- HResult = __HResults.COR_E_OBJECTDISPOSED;
- _objectName = objectName;
- }
-
- public ObjectDisposedException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_OBJECTDISPOSED;
- }
-
- protected ObjectDisposedException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- _objectName = info.GetString("ObjectName");
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
- info.AddValue("ObjectName",ObjectName,typeof(String));
- }
-
- /// <devdoc>
- /// <para>Gets the text for the message for this exception.</para>
- /// </devdoc>
- public override String Message
- {
- get
- {
- String name = ObjectName;
- if (name == null || name.Length == 0)
- return base.Message;
-
- String objectDisposed = SR.Format(SR.ObjectDisposed_ObjectName_Name, name);
- return base.Message + Environment.NewLine + objectDisposed;
- }
- }
-
- public String ObjectName
- {
- get
- {
- if ((_objectName == null)) // && !CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
- {
- return String.Empty;
- }
- return _objectName;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/ObsoleteAttribute.cs b/src/mscorlib/src/System/ObsoleteAttribute.cs
deleted file mode 100644
index f183685998..0000000000
--- a/src/mscorlib/src/System/ObsoleteAttribute.cs
+++ /dev/null
@@ -1,61 +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: Attribute for functions, etc that will be removed.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System
-{
- // This attribute is attached to members that are not to be used any longer.
- // Message is some human readable explanation of what to use
- // Error indicates if the compiler should treat usage of such a method as an
- // error. (this would be used if the actual implementation of the obsolete
- // method's implementation had changed).
- //
- [Serializable]
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum |
- AttributeTargets.Interface | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate
- , Inherited = false)]
- public sealed class ObsoleteAttribute : Attribute
- {
- private String _message;
- private bool _error;
-
- public ObsoleteAttribute()
- {
- _message = null;
- _error = false;
- }
-
- public ObsoleteAttribute(String message)
- {
- _message = message;
- _error = false;
- }
-
- public ObsoleteAttribute(String message, bool error)
- {
- _message = message;
- _error = error;
- }
-
- public String Message
- {
- get { return _message; }
- }
-
- public bool IsError
- {
- get { return _error; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/OleAutBinder.cs b/src/mscorlib/src/System/OleAutBinder.cs
index acae95a214..1db61bb30e 100644
--- a/src/mscorlib/src/System/OleAutBinder.cs
+++ b/src/mscorlib/src/System/OleAutBinder.cs
@@ -6,13 +6,13 @@
// #define DISPLAY_DEBUG_INFO
-namespace System {
-
+namespace System
+{
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using Microsoft.Win32;
- using CultureInfo = System.Globalization.CultureInfo;
+ using CultureInfo = System.Globalization.CultureInfo;
// Made serializable in anticipation of this class eventually having state.
[Serializable]
@@ -25,16 +25,16 @@ namespace System {
Variant myValue = new Variant(value);
if (cultureInfo == null)
cultureInfo = CultureInfo.CurrentCulture;
-
- #if DISPLAY_DEBUG_INFO
+
+#if DISPLAY_DEBUG_INFO
Console.WriteLine("In OleAutBinder::ChangeType converting variant of type: {0} to type: {1}", myValue.VariantType, type.Name);
- #endif
+#endif
if (type.IsByRef)
{
- #if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
Console.WriteLine("Stripping byref from the type to convert to.");
- #endif
+#endif
type = type.GetElementType();
}
@@ -42,9 +42,9 @@ namespace System {
// need the OLEAUT change type, we can just use the normal COM+ mechanisms.
if (!type.IsPrimitive && type.IsInstanceOfType(value))
{
- #if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
Console.WriteLine("Source variant can be assigned to destination type");
- #endif
+#endif
return value;
}
@@ -53,9 +53,9 @@ namespace System {
// Handle converting primitives to enums.
if (type.IsEnum && srcType.IsPrimitive)
{
- #if DISPLAY_DEBUG_INFO
+#if DISPLAY_DEBUG_INFO
Console.WriteLine("Converting primitive to enum");
- #endif
+#endif
return Enum.Parse(type, value.ToString());
}
@@ -78,14 +78,14 @@ namespace System {
#if DISPLAY_DEBUG_INFO
catch(NotSupportedException e)
#else
- catch(NotSupportedException)
+ catch (NotSupportedException)
#endif
{
#if DISPLAY_DEBUG_INFO
Console.Write("Exception thrown: ");
Console.WriteLine(e);
#endif
- throw new COMException(Environment.GetResourceString("Interop.COM_TypeMismatch"), unchecked((int)0x80020005));
+ throw new COMException(SR.Interop_COM_TypeMismatch, unchecked((int)0x80020005));
}
}
}
diff --git a/src/mscorlib/src/System/OperatingSystem.cs b/src/mscorlib/src/System/OperatingSystem.cs
index a388fc6e33..5eb1253fa5 100644
--- a/src/mscorlib/src/System/OperatingSystem.cs
+++ b/src/mscorlib/src/System/OperatingSystem.cs
@@ -10,15 +10,16 @@
**
**
===========================================================*/
-namespace System {
- using System.Runtime.Serialization;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+namespace System
+{
[Serializable]
- internal sealed class OperatingSystem : ICloneable , ISerializable
+ internal sealed class OperatingSystem : ICloneable, ISerializable
{
private Version _version;
private PlatformID _platform;
@@ -28,32 +29,37 @@ namespace System {
private OperatingSystem()
{
}
-
- internal OperatingSystem(PlatformID platform, Version version, string servicePack) {
- if( platform < PlatformID.Win32S || platform > PlatformID.MacOSX) {
+
+ internal OperatingSystem(PlatformID platform, Version version, string servicePack)
+ {
+ if (platform < PlatformID.Win32S || platform > PlatformID.MacOSX)
+ {
throw new ArgumentException(
- Environment.GetResourceString("Arg_EnumIllegalVal", (int)platform),
+ SR.Format(SR.Arg_EnumIllegalVal, (int)platform),
nameof(platform));
}
- if ((Object) version == null)
+ if ((Object)version == null)
throw new ArgumentNullException(nameof(version));
Contract.EndContractBlock();
_platform = platform;
- _version = (Version) version.Clone();
+ _version = (Version)version.Clone();
_servicePack = servicePack;
}
-
- private OperatingSystem(SerializationInfo info, StreamingContext context) {
- SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while( enumerator.MoveNext()) {
- switch( enumerator.Name) {
+
+ private OperatingSystem(SerializationInfo info, StreamingContext context)
+ {
+ SerializationInfoEnumerator enumerator = info.GetEnumerator();
+ while (enumerator.MoveNext())
+ {
+ switch (enumerator.Name)
+ {
case "_version":
- _version = (Version) info.GetValue("_version", typeof(Version));
+ _version = (Version)info.GetValue("_version", typeof(Version));
break;
case "_platform":
- _platform = (PlatformID) info.GetValue("_platform", typeof(PlatformID));
+ _platform = (PlatformID)info.GetValue("_platform", typeof(PlatformID));
break;
case "_servicePack":
_servicePack = info.GetString("_servicePack");
@@ -61,13 +67,16 @@ namespace System {
}
}
- if (_version == null ) {
- throw new SerializationException(Environment.GetResourceString("Serialization_MissField", "_version"));
+ if (_version == null)
+ {
+ throw new SerializationException(SR.Format(SR.Serialization_MissField, "_version"));
}
}
- public void GetObjectData(SerializationInfo info, StreamingContext context) {
- if( info == null ) {
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -75,29 +84,35 @@ namespace System {
info.AddValue("_version", _version);
info.AddValue("_platform", _platform);
info.AddValue("_servicePack", _servicePack);
- }
+ }
- public Version Version {
+ public Version Version
+ {
get { return _version; }
}
-
- public Object Clone() {
+
+ public Object Clone()
+ {
return new OperatingSystem(_platform,
- _version, _servicePack );
+ _version, _servicePack);
}
-
- public override String ToString() {
+
+ public override String ToString()
+ {
return VersionString;
}
- public String VersionString {
- get {
- if(_versionString != null) {
+ public String VersionString
+ {
+ get
+ {
+ if (_versionString != null)
+ {
return _versionString;
}
String os;
- switch(_platform)
+ switch (_platform)
{
case PlatformID.Win32NT:
os = "Microsoft Windows NT ";
@@ -123,14 +138,16 @@ namespace System {
break;
}
- if( String.IsNullOrEmpty(_servicePack)) {
+ if (String.IsNullOrEmpty(_servicePack))
+ {
_versionString = os + _version.ToString();
}
- else {
+ else
+ {
_versionString = os + _version.ToString(3) + " " + _servicePack;
}
- return _versionString;
+ return _versionString;
}
}
}
diff --git a/src/mscorlib/src/System/OperationCanceledException.cs b/src/mscorlib/src/System/OperationCanceledException.cs
index 061201637a..826561776f 100644
--- a/src/mscorlib/src/System/OperationCanceledException.cs
+++ b/src/mscorlib/src/System/OperationCanceledException.cs
@@ -15,43 +15,46 @@ using System;
using System.Runtime.Serialization;
using System.Threading;
-namespace System {
-
+namespace System
+{
[Serializable]
public class OperationCanceledException : SystemException
{
- [NonSerialized]
+ [NonSerialized]
private CancellationToken _cancellationToken;
-
+
public CancellationToken CancellationToken
{
- get { return _cancellationToken;}
- private set { _cancellationToken = value;}
+ get { return _cancellationToken; }
+ private set { _cancellationToken = value; }
}
- public OperationCanceledException()
- : base(Environment.GetResourceString("OperationCanceled")) {
- SetErrorCode(__HResults.COR_E_OPERATIONCANCELED);
+ public OperationCanceledException()
+ : base(SR.OperationCanceled)
+ {
+ HResult = __HResults.COR_E_OPERATIONCANCELED;
}
-
- public OperationCanceledException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_OPERATIONCANCELED);
+
+ public OperationCanceledException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_OPERATIONCANCELED;
}
-
- public OperationCanceledException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_OPERATIONCANCELED);
+
+ public OperationCanceledException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_OPERATIONCANCELED;
}
public OperationCanceledException(CancellationToken token)
- :this()
+ : this()
{
CancellationToken = token;
}
- public OperationCanceledException(String message, CancellationToken token)
+ public OperationCanceledException(String message, CancellationToken token)
: this(message)
{
CancellationToken = token;
@@ -63,7 +66,8 @@ namespace System {
CancellationToken = token;
}
- protected OperationCanceledException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ protected OperationCanceledException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/OutOfMemoryException.cs b/src/mscorlib/src/System/OutOfMemoryException.cs
index 46d5195405..154d0f92e2 100644
--- a/src/mscorlib/src/System/OutOfMemoryException.cs
+++ b/src/mscorlib/src/System/OutOfMemoryException.cs
@@ -11,29 +11,35 @@
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System
+{
[Serializable]
- public class OutOfMemoryException : SystemException {
- public OutOfMemoryException()
- : base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory)) {
- SetErrorCode(__HResults.COR_E_OUTOFMEMORY);
+ public class OutOfMemoryException : SystemException
+ {
+ public OutOfMemoryException()
+ : base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory))
+ {
+ HResult = __HResults.COR_E_OUTOFMEMORY;
}
-
- public OutOfMemoryException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_OUTOFMEMORY);
+
+ public OutOfMemoryException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_OUTOFMEMORY;
}
-
- public OutOfMemoryException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_OUTOFMEMORY);
+
+ public OutOfMemoryException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_OUTOFMEMORY;
}
- protected OutOfMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected OutOfMemoryException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/OverflowException.cs b/src/mscorlib/src/System/OverflowException.cs
deleted file mode 100644
index e28c688dd6..0000000000
--- a/src/mscorlib/src/System/OverflowException.cs
+++ /dev/null
@@ -1,41 +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 class for Arthimatic Overflows.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class OverflowException : ArithmeticException
- {
- public OverflowException()
- : base(SR.Arg_OverflowException)
- {
- HResult = __HResults.COR_E_OVERFLOW;
- }
-
- public OverflowException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_OVERFLOW;
- }
-
- public OverflowException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_OVERFLOW;
- }
-
- protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/ParamArrayAttribute.cs b/src/mscorlib/src/System/ParamArrayAttribute.cs
deleted file mode 100644
index d3c3d46d56..0000000000
--- a/src/mscorlib/src/System/ParamArrayAttribute.cs
+++ /dev/null
@@ -1,21 +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: Attribute for multiple parameters.
-**
-**
-=============================================================================*/
-
-namespace System
-{
- [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
- public sealed class ParamArrayAttribute : Attribute
- {
- public ParamArrayAttribute() { }
- }
-}
diff --git a/src/mscorlib/src/System/ParamsArray.cs b/src/mscorlib/src/System/ParamsArray.cs
deleted file mode 100644
index ed8919c586..0000000000
--- a/src/mscorlib/src/System/ParamsArray.cs
+++ /dev/null
@@ -1,81 +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.
-namespace System
-{
- internal struct ParamsArray
- {
- // Sentinel fixed-length arrays eliminate the need for a "count" field keeping this
- // struct down to just 4 fields. These are only used for their "Length" property,
- // that is, their elements are never set or referenced.
- private static readonly object[] oneArgArray = new object[1];
- private static readonly object[] twoArgArray = new object[2];
- private static readonly object[] threeArgArray = new object[3];
-
- private readonly object arg0;
- private readonly object arg1;
- private readonly object arg2;
-
- // After construction, the first three elements of this array will never be accessed
- // because the indexer will retrieve those values from arg0, arg1, and arg2.
- private readonly object[] args;
-
- public ParamsArray(object arg0)
- {
- this.arg0 = arg0;
- this.arg1 = null;
- this.arg2 = null;
-
- // Always assign this.args to make use of its "Length" property
- this.args = oneArgArray;
- }
-
- public ParamsArray(object arg0, object arg1)
- {
- this.arg0 = arg0;
- this.arg1 = arg1;
- this.arg2 = null;
-
- // Always assign this.args to make use of its "Length" property
- this.args = twoArgArray;
- }
-
- public ParamsArray(object arg0, object arg1, object arg2)
- {
- this.arg0 = arg0;
- this.arg1 = arg1;
- this.arg2 = arg2;
-
- // Always assign this.args to make use of its "Length" property
- this.args = threeArgArray;
- }
-
- public ParamsArray(object[] args)
- {
- int len = args.Length;
- this.arg0 = len > 0 ? args[0] : null;
- this.arg1 = len > 1 ? args[1] : null;
- this.arg2 = len > 2 ? args[2] : null;
- this.args = args;
- }
-
- public int Length
- {
- get { return this.args.Length; }
- }
-
- public object this[int index]
- {
- get { return index == 0 ? this.arg0 : GetAtSlow(index); }
- }
-
- private object GetAtSlow(int index)
- {
- if (index == 1)
- return this.arg1;
- if (index == 2)
- return this.arg2;
- return this.args[index];
- }
- }
-}
diff --git a/src/mscorlib/src/System/ParseNumbers.cs b/src/mscorlib/src/System/ParseNumbers.cs
index 2a375f7584..5287e27669 100644
--- a/src/mscorlib/src/System/ParseNumbers.cs
+++ b/src/mscorlib/src/System/ParseNumbers.cs
@@ -11,52 +11,61 @@
**
**
===========================================================*/
-namespace System {
-
- //This class contains only static members and does not need to be serializable.
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- internal static class ParseNumbers {
- internal const int PrintAsI1=0x40;
- internal const int PrintAsI2=0x80;
- internal const int PrintAsI4=0x100;
- internal const int TreatAsUnsigned=0x200;
- internal const int TreatAsI1=0x400;
- internal const int TreatAsI2=0x800;
- internal const int IsTight=0x1000;
- internal const int NoSpace=0x2000;
-
+//This class contains only static members and does not need to be serializable.
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+
+namespace System
+{
+ internal static class ParseNumbers
+ {
+ internal const int PrintAsI1 = 0x40;
+ internal const int PrintAsI2 = 0x80;
+ internal const int PrintAsI4 = 0x100;
+ internal const int TreatAsUnsigned = 0x200;
+ internal const int TreatAsI1 = 0x400;
+ internal const int TreatAsI2 = 0x800;
+ internal const int IsTight = 0x1000;
+ internal const int NoSpace = 0x2000;
+
//
//
// NATIVE METHODS
// For comments on these methods please see $\src\vm\COMUtilNative.cpp
//
- public unsafe static long StringToLong(System.String s, int radix, int flags) {
- return StringToLong(s,radix,flags, null);
+ public unsafe static long StringToLong(System.String s, int radix, int flags)
+ {
+ return StringToLong(s, radix, flags, null);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public unsafe extern static long StringToLong(System.String s, int radix, int flags, int* currPos);
- public unsafe static long StringToLong(System.String s, int radix, int flags, ref int currPos) {
- fixed(int * ppos = &currPos) {
- return StringToLong( s, radix, flags, ppos);
+ public unsafe static long StringToLong(System.String s, int radix, int flags, ref int currPos)
+ {
+ fixed (int* ppos = &currPos)
+ {
+ return StringToLong(s, radix, flags, ppos);
}
}
-
- public unsafe static int StringToInt(System.String s, int radix, int flags) {
- return StringToInt(s,radix,flags, null);
+
+ public unsafe static int StringToInt(System.String s, int radix, int flags)
+ {
+ return StringToInt(s, radix, flags, null);
}
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public unsafe extern static int StringToInt(System.String s, int radix, int flags, int* currPos);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public unsafe extern static int StringToInt(System.String s, int radix, int flags, int* currPos);
- public unsafe static int StringToInt(System.String s, int radix, int flags, ref int currPos) {
- fixed(int * ppos = &currPos) {
- return StringToInt( s, radix, flags, ppos);
+ public unsafe static int StringToInt(System.String s, int radix, int flags, ref int currPos)
+ {
+ fixed (int* ppos = &currPos)
+ {
+ return StringToInt(s, radix, flags, ppos);
}
- }
-
+ }
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern static String IntToString(int l, int radix, int width, char paddingChar, int flags);
diff --git a/src/mscorlib/src/System/PlatformID.cs b/src/mscorlib/src/System/PlatformID.cs
index 16128079e2..dfab2175ab 100644
--- a/src/mscorlib/src/System/PlatformID.cs
+++ b/src/mscorlib/src/System/PlatformID.cs
@@ -10,18 +10,18 @@
**
**
===========================================================*/
-namespace System {
+namespace System
+{
[Serializable]
internal enum PlatformID
{
- Win32S = 0,
- Win32Windows = 1,
- Win32NT = 2,
- WinCE = 3,
- Unix = 4,
- Xbox = 5,
- MacOSX = 6
+ Win32S = 0,
+ Win32Windows = 1,
+ Win32NT = 2,
+ WinCE = 3,
+ Unix = 4,
+ Xbox = 5,
+ MacOSX = 6
}
-
}
diff --git a/src/mscorlib/src/System/PlatformNotSupportedException.cs b/src/mscorlib/src/System/PlatformNotSupportedException.cs
deleted file mode 100644
index d2370b3924..0000000000
--- a/src/mscorlib/src/System/PlatformNotSupportedException.cs
+++ /dev/null
@@ -1,41 +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: To handle features that don't run on particular platforms
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class PlatformNotSupportedException : NotSupportedException
- {
- public PlatformNotSupportedException()
- : base(SR.Arg_PlatformNotSupported)
- {
- HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
- }
-
- public PlatformNotSupportedException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
- }
-
- public PlatformNotSupportedException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
- }
-
- protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Progress.cs b/src/mscorlib/src/System/Progress.cs
deleted file mode 100644
index 755e7719fe..0000000000
--- a/src/mscorlib/src/System/Progress.cs
+++ /dev/null
@@ -1,105 +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.Threading;
-using System.Diagnostics;
-
-namespace System
-{
- /// <summary>
- /// Provides an IProgress{T} that invokes callbacks for each reported progress value.
- /// </summary>
- /// <typeparam name="T">Specifies the type of the progress report value.</typeparam>
- /// <remarks>
- /// Any handler provided to the constructor or event handlers registered with
- /// the <see cref="ProgressChanged"/> event are invoked through a
- /// <see cref="System.Threading.SynchronizationContext"/> instance captured
- /// when the instance is constructed. If there is no current SynchronizationContext
- /// at the time of construction, the callbacks will be invoked on the ThreadPool.
- /// </remarks>
- public class Progress<T> : IProgress<T>
- {
- /// <summary>The synchronization context captured upon construction. This will never be null.</summary>
- private readonly SynchronizationContext _synchronizationContext;
- /// <summary>The handler specified to the constructor. This may be null.</summary>
- private readonly Action<T> _handler;
- /// <summary>A cached delegate used to post invocation to the synchronization context.</summary>
- private readonly SendOrPostCallback _invokeHandlers;
-
- /// <summary>Initializes the <see cref="Progress{T}"/>.</summary>
- public Progress()
- {
- // Capture the current synchronization context.
- // If there is no current context, we use a default instance targeting the ThreadPool.
- _synchronizationContext = SynchronizationContext.Current ?? ProgressStatics.DefaultContext;
- Debug.Assert(_synchronizationContext != null);
- _invokeHandlers = new SendOrPostCallback(InvokeHandlers);
- }
-
- /// <summary>Initializes the <see cref="Progress{T}"/> with the specified callback.</summary>
- /// <param name="handler">
- /// A handler to invoke for each reported progress value. This handler will be invoked
- /// in addition to any delegates registered with the <see cref="ProgressChanged"/> event.
- /// Depending on the <see cref="System.Threading.SynchronizationContext"/> instance captured by
- /// the <see cref="Progress"/> at construction, it's possible that this handler instance
- /// could be invoked concurrently with itself.
- /// </param>
- /// <exception cref="System.ArgumentNullException">The <paramref name="handler"/> is null (Nothing in Visual Basic).</exception>
- public Progress(Action<T> handler) : this()
- {
- if (handler == null) throw new ArgumentNullException(nameof(handler));
- _handler = handler;
- }
-
- /// <summary>Raised for each reported progress value.</summary>
- /// <remarks>
- /// Handlers registered with this event will be invoked on the
- /// <see cref="System.Threading.SynchronizationContext"/> captured when the instance was constructed.
- /// </remarks>
- public event EventHandler<T> ProgressChanged;
-
- /// <summary>Reports a progress change.</summary>
- /// <param name="value">The value of the updated progress.</param>
- protected virtual void OnReport(T value)
- {
- // If there's no handler, don't bother going through the sync context.
- // Inside the callback, we'll need to check again, in case
- // an event handler is removed between now and then.
- Action<T> handler = _handler;
- EventHandler<T> changedEvent = ProgressChanged;
- if (handler != null || changedEvent != null)
- {
- // Post the processing to the sync context.
- // (If T is a value type, it will get boxed here.)
- _synchronizationContext.Post(_invokeHandlers, value);
- }
- }
-
- /// <summary>Reports a progress change.</summary>
- /// <param name="value">The value of the updated progress.</param>
- void IProgress<T>.Report(T value) { OnReport(value); }
-
- /// <summary>Invokes the action and event callbacks.</summary>
- /// <param name="state">The progress value.</param>
- private void InvokeHandlers(object state)
- {
- T value = (T)state;
-
- Action<T> handler = _handler;
- EventHandler<T> changedEvent = ProgressChanged;
-
- if (handler != null) handler(value);
- if (changedEvent != null) changedEvent(this, value);
- }
- }
-
- /// <summary>Holds static values for <see cref="Progress{T}"/>.</summary>
- /// <remarks>This avoids one static instance per type T.</remarks>
- internal static class ProgressStatics
- {
- /// <summary>A default synchronization context that targets the ThreadPool.</summary>
- internal static readonly SynchronizationContext DefaultContext = new SynchronizationContext();
- }
-}
diff --git a/src/mscorlib/src/System/Random.cs b/src/mscorlib/src/System/Random.cs
deleted file mode 100644
index db6da0ea8b..0000000000
--- a/src/mscorlib/src/System/Random.cs
+++ /dev/null
@@ -1,249 +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: A random number generator.
-**
-**
-===========================================================*/
-namespace System {
-
- using System;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- public class Random {
- //
- // Private Constants
- //
- private const int MBIG = Int32.MaxValue;
- private const int MSEED = 161803398;
- private const int MZ = 0;
-
-
- //
- // Member Variables
- //
- private int inext;
- private int inextp;
- private int[] SeedArray = new int[56];
-
- //
- // Public Constants
- //
-
- //
- // Native Declarations
- //
-
- //
- // Constructors
- //
-
- /*=========================================================================================
- **Action: Initializes a new instance of the Random class, using a default seed value
- ===========================================================================================*/
- public Random()
- : this(GenerateSeed()) {
- }
-
- /*=========================================================================================
- **Action: Initializes a new instance of the Random class, using a specified seed value
- ===========================================================================================*/
- public Random(int Seed) {
- int ii = 0;
- int mj, mk;
-
- //Initialize our Seed array.
- int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
- mj = MSEED - subtraction;
- SeedArray[55]=mj;
- mk=1;
- for (int i=1; i<55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
- if ((ii += 21) >= 55) ii -= 55;
- SeedArray[ii]=mk;
- mk = mj - mk;
- if (mk<0) mk+=MBIG;
- mj=SeedArray[ii];
- }
- for (int k=1; k<5; k++) {
- for (int i=1; i<56; i++) {
- int n = i + 30;
- if (n >= 55) n -= 55;
- SeedArray[i] -= SeedArray[1 + n];
- if (SeedArray[i]<0) SeedArray[i]+=MBIG;
- }
- }
- inext=0;
- inextp = 21;
- Seed = 1;
- }
-
- //
- // Package Private Methods
- //
-
- /*====================================Sample====================================
- **Action: Return a new random number [0..1) and reSeed the Seed array.
- **Returns: A double [0..1)
- **Arguments: None
- **Exceptions: None
- ==============================================================================*/
- protected virtual double Sample() {
- //Including this division at the end gives us significantly improved
- //random number distribution.
- return (InternalSample()*(1.0/MBIG));
- }
-
- private int InternalSample() {
- int retVal;
- int locINext = inext;
- int locINextp = inextp;
-
- if (++locINext >=56) locINext=1;
- if (++locINextp>= 56) locINextp = 1;
-
- retVal = SeedArray[locINext]-SeedArray[locINextp];
-
- if (retVal == MBIG) retVal--;
- if (retVal<0) retVal+=MBIG;
-
- SeedArray[locINext]=retVal;
-
- inext = locINext;
- inextp = locINextp;
-
- return retVal;
- }
-
-
- [ThreadStatic]
- private static Random t_threadRandom;
- private static readonly Random s_globalRandom = new Random(GenerateGlobalSeed());
-
- /*=====================================GenerateSeed=====================================
- **Returns: An integer that can be used as seed values for consecutively
- creating lots of instances on the same thread within a short period of time.
- ========================================================================================*/
- private static int GenerateSeed() {
- Random rnd = t_threadRandom;
- if (rnd == null) {
- int seed;
- lock (s_globalRandom) {
- seed = s_globalRandom.Next();
- }
- rnd = new Random(seed);
- t_threadRandom = rnd;
- }
- return rnd.Next();
- }
-
- /*==================================GenerateGlobalSeed====================================
- **Action: Creates a number to use as global seed.
- **Returns: An integer that is safe to use as seed values for thread-local seed generators.
- ==========================================================================================*/
- private static int GenerateGlobalSeed() {
- return Guid.NewGuid().GetHashCode();
- }
-
- //
- // Public Instance Methods
- //
-
-
- /*=====================================Next=====================================
- **Returns: An int [0..Int32.MaxValue)
- **Arguments: None
- **Exceptions: None.
- ==============================================================================*/
- public virtual int Next() {
- return InternalSample();
- }
-
- private double GetSampleForLargeRange() {
- // The distribution of double value returned by Sample
- // is not distributed well enough for a large range.
- // If we use Sample for a range [Int32.MinValue..Int32.MaxValue)
- // We will end up getting even numbers only.
-
- int result = InternalSample();
- // Note we can't use addition here. The distribution will be bad if we do that.
- bool negative = (InternalSample()%2 == 0) ? true : false; // decide the sign based on second sample
- if( negative) {
- result = -result;
- }
- double d = result;
- d += (Int32.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
- d /= 2*(uint)Int32.MaxValue - 1 ;
- return d;
- }
-
-
- /*=====================================Next=====================================
- **Returns: An int [minvalue..maxvalue)
- **Arguments: minValue -- the least legal value for the Random number.
- ** maxValue -- One greater than the greatest legal return value.
- **Exceptions: None.
- ==============================================================================*/
- public virtual int Next(int minValue, int maxValue) {
- if (minValue>maxValue) {
- throw new ArgumentOutOfRangeException(nameof(minValue),Environment.GetResourceString("Argument_MinMaxValue", nameof(minValue), nameof(maxValue)));
- }
- Contract.EndContractBlock();
-
- long range = (long)maxValue-minValue;
- if( range <= (long)Int32.MaxValue) {
- return ((int)(Sample() * range) + minValue);
- }
- else {
- return (int)((long)(GetSampleForLargeRange() * range) + minValue);
- }
- }
-
-
- /*=====================================Next=====================================
- **Returns: An int [0..maxValue)
- **Arguments: maxValue -- One more than the greatest legal return value.
- **Exceptions: None.
- ==============================================================================*/
- public virtual int Next(int maxValue) {
- if (maxValue<0) {
- throw new ArgumentOutOfRangeException(nameof(maxValue), Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(maxValue)));
- }
- Contract.EndContractBlock();
- return (int)(Sample()*maxValue);
- }
-
-
- /*=====================================Next=====================================
- **Returns: A double [0..1)
- **Arguments: None
- **Exceptions: None
- ==============================================================================*/
- public virtual double NextDouble() {
- return Sample();
- }
-
-
- /*==================================NextBytes===================================
- **Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled.
- **Returns:Void
- **Arugments: buffer -- the array to be filled.
- **Exceptions: None
- ==============================================================================*/
- 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));
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/RankException.cs b/src/mscorlib/src/System/RankException.cs
deleted file mode 100644
index 612d0f086c..0000000000
--- a/src/mscorlib/src/System/RankException.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: For methods that are passed arrays with the wrong number of
-** dimensions.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class RankException : SystemException
- {
- public RankException()
- : base(SR.Arg_RankException)
- {
- HResult = __HResults.COR_E_RANK;
- }
-
- public RankException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_RANK;
- }
-
- public RankException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_RANK;
- }
-
- protected RankException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/ReadOnlySpan.cs b/src/mscorlib/src/System/ReadOnlySpan.cs
index 76c63d5d8b..8d0fbad0fc 100644
--- a/src/mscorlib/src/System/ReadOnlySpan.cs
+++ b/src/mscorlib/src/System/ReadOnlySpan.cs
@@ -103,7 +103,7 @@ namespace System
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe ReadOnlySpan(void* pointer, int length)
{
- if (JitHelpers.ContainsReferences<T>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
@@ -114,28 +114,15 @@ namespace System
/// <summary>
/// Create a new read-only span over a portion of a regular managed object. This can be useful
- /// if part of a managed object represents a "fixed array." This is dangerous because
- /// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object.
+ /// if part of a managed object represents a "fixed array." This is dangerous because neither the
+ /// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
+ /// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <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>
- /// <exception cref="System.ArgumentNullException">
- /// Thrown when the specified object is null.
- /// </exception>
- /// <exception cref="System.ArgumentOutOfRangeException">
- /// Thrown when the specified <paramref name="length"/> is negative.
- /// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length)
- {
- if (obj == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
- if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
-
- return new ReadOnlySpan<T>(ref objectData, length);
- }
+ public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) => new ReadOnlySpan<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -244,9 +231,7 @@ namespace System
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
- ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
- // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value
- return default(bool);
+ throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
@@ -259,9 +244,7 @@ namespace System
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
- ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan();
- // Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value
- return default(int);
+ throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
diff --git a/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs b/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
deleted file mode 100644
index 795a8714d1..0000000000
--- a/src/mscorlib/src/System/Reflection/AmbiguousMatchException.cs
+++ /dev/null
@@ -1,41 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// AmbiguousMatchException is thrown when binding to a method results in more
-//
-// than one method matching the binding criteria. This exception is thrown in
-// general when something is Ambiguous.
-//
-//
-//
-//
-namespace System.Reflection {
- using System;
- using SystemException = System.SystemException;
- using System.Runtime.Serialization;
- [Serializable]
- public sealed class AmbiguousMatchException : SystemException
- {
-
- public AmbiguousMatchException()
- : base(Environment.GetResourceString("RFLCT.Ambiguous")) {
- SetErrorCode(__HResults.COR_E_AMBIGUOUSMATCH);
- }
-
- public AmbiguousMatchException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_AMBIGUOUSMATCH);
- }
-
- public AmbiguousMatchException(String message, Exception inner) : base(message, inner) {
- SetErrorCode(__HResults.COR_E_AMBIGUOUSMATCH);
- }
-
- internal AmbiguousMatchException(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
new file mode 100644
index 0000000000..82966dba60
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
@@ -0,0 +1,211 @@
+// 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.Security.Policy;
+using System.IO;
+using System.Configuration.Assemblies;
+using StackCrawlMark = System.Threading.StackCrawlMark;
+using System.Runtime.Serialization;
+using System.Diagnostics.Contracts;
+using System.Runtime.Loader;
+
+namespace System.Reflection
+{
+ public abstract partial class Assembly : ICustomAttributeProvider, ISerializable
+ {
+ public static Assembly LoadFrom(String assemblyFile)
+ {
+ if (assemblyFile == null)
+ throw new ArgumentNullException(nameof(assemblyFile));
+ string fullPath = Path.GetFullPath(assemblyFile);
+ return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
+ }
+
+ // Evidence is protected in Assembly.Load()
+ [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ internal static Assembly LoadFrom(String assemblyFile,
+ Evidence securityEvidence)
+ {
+ Contract.Ensures(Contract.Result<Assembly>() != null);
+
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+
+ return RuntimeAssembly.InternalLoadFrom(
+ assemblyFile,
+ securityEvidence,
+ null, // hashValue
+ AssemblyHashAlgorithm.None,
+ false,// forIntrospection);
+ ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Assembly LoadFrom(String assemblyFile,
+ byte[] hashValue,
+ AssemblyHashAlgorithm hashAlgorithm)
+ {
+ throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash);
+ }
+
+ // Locate an assembly by the long form of the assembly name.
+ // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Assembly Load(String assemblyString)
+ {
+ Contract.Ensures(Contract.Result<Assembly>() != null);
+ Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
+
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false /*forIntrospection*/);
+ }
+
+ // Returns type from the assembly while keeping compatibility with Assembly.Load(assemblyString).GetType(typeName) for managed types.
+ // Calls Type.GetType for WinRT types.
+ // Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would
+ // break AppCompat.
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ internal static Type GetType_Compat(String assemblyString, String typeName)
+ {
+ // Normally we would get the stackMark only in public APIs. This is internal API, but it is AppCompat replacement of public API
+ // call Assembly.Load(assemblyString).GetType(typeName), therefore we take the stackMark here as well, to be fully compatible with
+ // the call sequence.
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+
+ RuntimeAssembly assembly;
+ AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(
+ assemblyString,
+ false /*forIntrospection*/,
+ out assembly);
+
+ if (assembly == null)
+ {
+ if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime)
+ {
+ return Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, false /*ignoreCase*/);
+ }
+
+ assembly = RuntimeAssembly.InternalLoadAssemblyName(
+ assemblyName, null, null, ref stackMark,
+ true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
+ }
+ return assembly.GetType(typeName, true /*throwOnError*/, false /*ignoreCase*/);
+ }
+
+ // Locate an assembly by its name. The name can be strong or
+ // weak. The assembly is loaded into the domain of the caller.
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Assembly Load(AssemblyName assemblyRef)
+ {
+ Contract.Ensures(Contract.Result<Assembly>() != null);
+ Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
+
+ if (assemblyRef != null && assemblyRef.CodeBase != null)
+ {
+ throw new NotSupportedException(SR.NotSupported_AssemblyLoadCodeBase);
+ }
+
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
+ }
+
+ // Locate an assembly by its name. The name can be strong or
+ // weak. The assembly is loaded into the domain of the caller.
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder)
+ {
+ Contract.Ensures(Contract.Result<Assembly>() != null);
+ Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
+
+ if (assemblyRef != null && assemblyRef.CodeBase != null)
+ {
+ throw new NotSupportedException(SR.NotSupported_AssemblyLoadCodeBase);
+ }
+
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, ptrLoadContextBinder);
+ }
+
+ // Loads the assembly with a COFF based IMAGE containing
+ // an emitted assembly. The assembly is loaded into the domain
+ // of the caller. The second parameter is the raw bytes
+ // representing the symbol store that matches the assembly.
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Assembly Load(byte[] rawAssembly,
+ byte[] rawSymbolStore)
+ {
+ Contract.Ensures(Contract.Result<Assembly>() != null);
+ Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
+
+ AppDomain.CheckLoadByteArraySupported();
+
+ if (rawAssembly == null)
+ throw new ArgumentNullException(nameof(rawAssembly));
+ AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
+ MemoryStream assemblyStream = new MemoryStream(rawAssembly);
+ MemoryStream symbolStream = (rawSymbolStore != null) ? new MemoryStream(rawSymbolStore) : null;
+ return alc.LoadFromStream(assemblyStream, symbolStream);
+ }
+
+ private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
+
+ public static Assembly LoadFile(String path)
+ {
+ Contract.Ensures(Contract.Result<Assembly>() != null);
+ Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
+
+ AppDomain.CheckLoadFileSupported();
+
+ Assembly result = null;
+ if (path == null)
+ throw new ArgumentNullException(nameof(path));
+
+ if (PathInternal.IsPartiallyQualified(path))
+ {
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(path));
+ }
+
+ string normalizedPath = Path.GetFullPath(path);
+
+ lock (s_loadfile)
+ {
+ if (s_loadfile.TryGetValue(normalizedPath, out result))
+ return result;
+ AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
+ result = alc.LoadFromAssemblyPath(normalizedPath);
+ s_loadfile.Add(normalizedPath, result);
+ }
+ return result;
+ }
+
+ /*
+ * Get the assembly that the current code is running from.
+ */
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Assembly GetExecutingAssembly()
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Assembly GetCallingAssembly()
+ {
+ // LookForMyCallersCaller is not guarantee to return the correct stack frame
+ // because of inlining, tail calls, etc. As a result GetCallingAssembly is not
+ // ganranteed to return the correct result. We should document it as such.
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
+ return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
+ }
+
+ public static Assembly GetEntryAssembly()
+ {
+ AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
+ if (domainManager == null)
+ domainManager = new AppDomainManager();
+ return domainManager.EntryAssembly;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs b/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
deleted file mode 100644
index 1e6688d1f4..0000000000
--- a/src/mscorlib/src/System/Reflection/AssemblyAttributes.cs
+++ /dev/null
@@ -1,387 +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: For Assembly-related custom attributes.
-**
-**
-=============================================================================*/
-
-namespace System.Reflection {
-
- using System;
- using System.Configuration.Assemblies;
- using System.Diagnostics.Contracts;
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyCopyrightAttribute : Attribute
- {
- private String m_copyright;
-
- public AssemblyCopyrightAttribute(String copyright)
- {
- m_copyright = copyright;
- }
-
- public String Copyright
- {
- get { return m_copyright; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyTrademarkAttribute : Attribute
- {
- private String m_trademark;
-
- public AssemblyTrademarkAttribute(String trademark)
- {
- m_trademark = trademark;
- }
-
- public String Trademark
- {
- get { return m_trademark; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyProductAttribute : Attribute
- {
- private String m_product;
-
- public AssemblyProductAttribute(String product)
- {
- m_product = product;
- }
-
- public String Product
- {
- get { return m_product; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyCompanyAttribute : Attribute
- {
- private String m_company;
-
- public AssemblyCompanyAttribute(String company)
- {
- m_company = company;
- }
-
- public String Company
- {
- get { return m_company; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyDescriptionAttribute : Attribute
- {
- private String m_description;
-
- public AssemblyDescriptionAttribute(String description)
- {
- m_description = description;
- }
-
- public String Description
- {
- get { return m_description; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyTitleAttribute : Attribute
- {
- private String m_title;
-
- public AssemblyTitleAttribute(String title)
- {
- m_title = title;
- }
-
- public String Title
- {
- get { return m_title; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyConfigurationAttribute : Attribute
- {
- private String m_configuration;
-
- public AssemblyConfigurationAttribute(String configuration)
- {
- m_configuration = configuration;
- }
-
- public String Configuration
- {
- get { return m_configuration; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyDefaultAliasAttribute : Attribute
- {
- private String m_defaultAlias;
-
- public AssemblyDefaultAliasAttribute(String defaultAlias)
- {
- m_defaultAlias = defaultAlias;
- }
-
- public String DefaultAlias
- {
- get { return m_defaultAlias; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyInformationalVersionAttribute : Attribute
- {
- private String m_informationalVersion;
-
- public AssemblyInformationalVersionAttribute(String informationalVersion)
- {
- m_informationalVersion = informationalVersion;
- }
-
- public String InformationalVersion
- {
- get { return m_informationalVersion; }
- }
- }
-
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyFileVersionAttribute : Attribute
- {
- private String _version;
-
- public AssemblyFileVersionAttribute(String version)
- {
- if (version == null)
- throw new ArgumentNullException(nameof(version));
- Contract.EndContractBlock();
- _version = version;
- }
-
- public String Version {
- get { return _version; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public unsafe sealed class AssemblyCultureAttribute : Attribute
- {
- private String m_culture;
-
- public AssemblyCultureAttribute(String culture)
- {
- m_culture = culture;
- }
-
- public String Culture
- {
- get { return m_culture; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public unsafe sealed class AssemblyVersionAttribute : Attribute
- {
- private String m_version;
-
- public AssemblyVersionAttribute(String version)
- {
- m_version = version;
- }
-
- public String Version
- {
- get { return m_version; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyKeyFileAttribute : Attribute
- {
- private String m_keyFile;
-
- public AssemblyKeyFileAttribute(String keyFile)
- {
- m_keyFile = keyFile;
- }
-
- public String KeyFile
- {
- get { return m_keyFile; }
- }
- }
-
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyDelaySignAttribute : Attribute
- {
- private bool m_delaySign;
-
- public AssemblyDelaySignAttribute(bool delaySign)
- {
- m_delaySign = delaySign;
- }
-
- public bool DelaySign
- { get
- { return m_delaySign; }
- }
- }
-
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
- public unsafe sealed class AssemblyAlgorithmIdAttribute : Attribute
- {
- private uint m_algId;
-
- public AssemblyAlgorithmIdAttribute(AssemblyHashAlgorithm algorithmId)
- {
- m_algId = (uint) algorithmId;
- }
-
- [CLSCompliant(false)]
- public AssemblyAlgorithmIdAttribute(uint algorithmId)
- {
- m_algId = algorithmId;
- }
-
- [CLSCompliant(false)]
- public uint AlgorithmId
- {
- get { return m_algId; }
- }
- }
-
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited=false)]
- public unsafe sealed class AssemblyFlagsAttribute : Attribute
- {
- private AssemblyNameFlags m_flags;
-
- [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [CLSCompliant(false)]
- public AssemblyFlagsAttribute(uint flags)
- {
- m_flags = (AssemblyNameFlags)flags;
- }
-
- [Obsolete("This property has been deprecated. Please use AssemblyFlags instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- [CLSCompliant(false)]
- public uint Flags
- {
- get { return (uint)m_flags; }
- }
-
- // This, of course, should be typed as AssemblyNameFlags. The compat police don't allow such changes.
- public int AssemblyFlags
- {
- get { return (int)m_flags; }
- }
-
- [Obsolete("This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public AssemblyFlagsAttribute(int assemblyFlags)
- {
- m_flags = (AssemblyNameFlags)assemblyFlags;
- }
-
-
- public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags)
- {
- m_flags = assemblyFlags;
- }
- }
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
- public sealed class AssemblyMetadataAttribute : Attribute
- {
- private String m_key;
- private String m_value;
-
- public AssemblyMetadataAttribute(string key, string value)
- {
- m_key = key;
- m_value = value;
- }
-
- public string Key
- {
- get { return m_key; }
- }
-
- public string Value
- {
- get { return m_value;}
- }
- }
-
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple=false)]
- public sealed class AssemblySignatureKeyAttribute : Attribute
- {
- private String _publicKey;
- private String _countersignature;
-
- public AssemblySignatureKeyAttribute(String publicKey, String countersignature)
- {
- _publicKey = publicKey;
- _countersignature = countersignature;
- }
-
- public String PublicKey
- {
- get { return _publicKey; }
- }
-
- public String Countersignature
- {
- get { return _countersignature; }
- }
- }
-
- [AttributeUsage (AttributeTargets.Assembly, Inherited=false)]
- public sealed class AssemblyKeyNameAttribute : Attribute
- {
- private String m_keyName;
-
- public AssemblyKeyNameAttribute(String keyName)
- {
- m_keyName = keyName;
- }
-
- public String KeyName
- {
- get { return m_keyName; }
- }
- }
-
-}
-
diff --git a/src/mscorlib/src/System/Reflection/AssemblyName.cs b/src/mscorlib/src/System/Reflection/AssemblyName.cs
index 01be855646..80fdf5d162 100644
--- a/src/mscorlib/src/System/Reflection/AssemblyName.cs
+++ b/src/mscorlib/src/System/Reflection/AssemblyName.cs
@@ -13,7 +13,9 @@
**
**
===========================================================*/
-namespace System.Reflection {
+
+namespace System.Reflection
+{
using System;
using System.IO;
using System.Configuration.Assemblies;
@@ -33,31 +35,31 @@ namespace System.Reflection {
// If you modify any of these fields, you must also update the
// AssemblyBaseObject structure in object.h
//
- private String _Name; // Name
- private byte[] _PublicKey;
- private byte[] _PublicKeyToken;
- private CultureInfo _CultureInfo;
- private String _CodeBase; // Potential location to get the file
- private Version _Version;
-
- private StrongNameKeyPair _StrongNameKeyPair;
+ private String _Name; // Name
+ private byte[] _PublicKey;
+ private byte[] _PublicKeyToken;
+ private CultureInfo _CultureInfo;
+ private String _CodeBase; // Potential location to get the file
+ private Version _Version;
+
+ private StrongNameKeyPair _StrongNameKeyPair;
private SerializationInfo m_siInfo; //A temporary variable which we need during deserialization.
- private byte[] _HashForControl;
+ private byte[] _HashForControl;
private AssemblyHashAlgorithm _HashAlgorithm;
private AssemblyHashAlgorithm _HashAlgorithmForControl;
private AssemblyVersionCompatibility _VersionCompatibility;
- private AssemblyNameFlags _Flags;
-
+ private AssemblyNameFlags _Flags;
+
public AssemblyName()
- {
+ {
_HashAlgorithm = AssemblyHashAlgorithm.None;
_VersionCompatibility = AssemblyVersionCompatibility.SameMachine;
_Flags = AssemblyNameFlags.None;
}
-
+
// Set and get the name of the assembly. If this is a weak Name
// then it optionally contains a site. For strong assembly names,
// the name partitions up the strong name's namespace
@@ -69,10 +71,12 @@ namespace System.Reflection {
public Version Version
{
- get {
+ get
+ {
return _Version;
}
- set {
+ set
+ {
_Version = value;
}
}
@@ -80,30 +84,34 @@ namespace System.Reflection {
// Locales, internally the LCID is used for the match.
public CultureInfo CultureInfo
{
- get {
+ get
+ {
return _CultureInfo;
}
- set {
- _CultureInfo = value;
+ set
+ {
+ _CultureInfo = value;
}
}
public String CultureName
{
- get {
+ get
+ {
return (_CultureInfo == null) ? null : _CultureInfo.Name;
}
- set {
+ set
+ {
_CultureInfo = (value == null) ? null : new CultureInfo(value);
}
}
-
+
public String CodeBase
{
get { return _CodeBase; }
set { _CodeBase = value; }
}
-
+
public String EscapedCodeBase
{
get
@@ -114,18 +122,21 @@ namespace System.Reflection {
return EscapeCodeBase(_CodeBase);
}
}
-
- public ProcessorArchitecture ProcessorArchitecture
+
+ public ProcessorArchitecture ProcessorArchitecture
{
- get {
+ get
+ {
int x = (((int)_Flags) & 0x70) >> 4;
- if(x > 5)
+ if (x > 5)
x = 0;
return (ProcessorArchitecture)x;
}
- set {
+ set
+ {
int x = ((int)value) & 0x07;
- if(x <= 5) {
+ if (x <= 5)
+ {
_Flags = (AssemblyNameFlags)((int)_Flags & 0xFFFFFF0F);
_Flags |= (AssemblyNameFlags)(x << 4);
}
@@ -151,8 +162,8 @@ namespace System.Reflection {
}
}
}
-
-
+
+
// Make a copy of this assembly name.
public Object Clone()
@@ -168,8 +179,8 @@ namespace System.Reflection {
_CodeBase,
_Flags,
_StrongNameKeyPair);
- name._HashForControl=_HashForControl;
- name._HashAlgorithmForControl=_HashAlgorithmForControl;
+ name._HashForControl = _HashForControl;
+ name._HashAlgorithmForControl = _HashAlgorithmForControl;
return name;
}
@@ -180,7 +191,7 @@ namespace System.Reflection {
*/
static public AssemblyName GetAssemblyName(String assemblyFile)
{
- if(assemblyFile == null)
+ if (assemblyFile == null)
throw new ArgumentNullException(nameof(assemblyFile));
Contract.EndContractBlock();
@@ -189,11 +200,11 @@ namespace System.Reflection {
string fullPath = Path.GetFullPath(assemblyFile);
return nGetFileInformation(fullPath);
}
-
+
internal void SetHashControl(byte[] hash, AssemblyHashAlgorithm hashAlgorithm)
{
- _HashForControl=hash;
- _HashAlgorithmForControl=hashAlgorithm;
+ _HashForControl = hash;
+ _HashAlgorithmForControl = hashAlgorithm;
}
// The public key that is used to verify an assemblies
@@ -239,7 +250,8 @@ namespace System.Reflection {
public AssemblyNameFlags Flags
{
get { return (AssemblyNameFlags)((uint)_Flags & 0xFFFFF10F); }
- set {
+ set
+ {
_Flags &= unchecked((AssemblyNameFlags)0x00000EF0);
_Flags |= (value & unchecked((AssemblyNameFlags)0xFFFFF10F));
}
@@ -250,7 +262,7 @@ namespace System.Reflection {
get { return _HashAlgorithm; }
set { _HashAlgorithm = value; }
}
-
+
public AssemblyVersionCompatibility VersionCompatibility
{
get { return _VersionCompatibility; }
@@ -262,21 +274,22 @@ namespace System.Reflection {
get { return _StrongNameKeyPair; }
set { _StrongNameKeyPair = value; }
}
-
+
public String FullName
{
- get {
+ get
+ {
return nToString();
}
}
-
+
// Returns the stringized version of the assembly name.
public override String ToString()
{
String s = FullName;
- if(s == null)
+ if (s == null)
return base.ToString();
- else
+ else
return s;
}
@@ -291,7 +304,7 @@ namespace System.Reflection {
info.AddValue("_PublicKey", _PublicKey, typeof(byte[]));
info.AddValue("_PublicKeyToken", _PublicKeyToken, typeof(byte[]));
#if FEATURE_USE_LCID
- info.AddValue("_CultureInfo", (_CultureInfo == null) ? -1 :_CultureInfo.LCID);
+ info.AddValue("_CultureInfo", (_CultureInfo == null) ? -1 : _CultureInfo.LCID);
#endif
info.AddValue("_CodeBase", _CodeBase);
info.AddValue("_Version", _Version);
@@ -300,8 +313,8 @@ namespace System.Reflection {
info.AddValue("_StrongNameKeyPair", _StrongNameKeyPair, typeof(StrongNameKeyPair));
info.AddValue("_VersionCompatibility", _VersionCompatibility, typeof(AssemblyVersionCompatibility));
info.AddValue("_Flags", _Flags, typeof(AssemblyNameFlags));
- info.AddValue("_HashForControl",_HashForControl,typeof(byte[]));
- }
+ info.AddValue("_HashForControl", _HashForControl, typeof(byte[]));
+ }
public void OnDeserialization(Object sender)
{
@@ -310,8 +323,8 @@ namespace System.Reflection {
return;
_Name = m_siInfo.GetString("_Name");
- _PublicKey = (byte[]) m_siInfo.GetValue("_PublicKey", typeof(byte[]));
- _PublicKeyToken = (byte[]) m_siInfo.GetValue("_PublicKeyToken", typeof(byte[]));
+ _PublicKey = (byte[])m_siInfo.GetValue("_PublicKey", typeof(byte[]));
+ _PublicKeyToken = (byte[])m_siInfo.GetValue("_PublicKeyToken", typeof(byte[]));
#if FEATURE_USE_LCID
int lcid = (int)m_siInfo.GetInt32("_CultureInfo");
if (lcid != -1)
@@ -319,17 +332,19 @@ namespace System.Reflection {
#endif
_CodeBase = m_siInfo.GetString("_CodeBase");
- _Version = (Version) m_siInfo.GetValue("_Version", typeof(Version));
- _HashAlgorithm = (AssemblyHashAlgorithm) m_siInfo.GetValue("_HashAlgorithm", typeof(AssemblyHashAlgorithm));
- _StrongNameKeyPair = (StrongNameKeyPair) m_siInfo.GetValue("_StrongNameKeyPair", typeof(StrongNameKeyPair));
+ _Version = (Version)m_siInfo.GetValue("_Version", typeof(Version));
+ _HashAlgorithm = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithm", typeof(AssemblyHashAlgorithm));
+ _StrongNameKeyPair = (StrongNameKeyPair)m_siInfo.GetValue("_StrongNameKeyPair", typeof(StrongNameKeyPair));
_VersionCompatibility = (AssemblyVersionCompatibility)m_siInfo.GetValue("_VersionCompatibility", typeof(AssemblyVersionCompatibility));
- _Flags = (AssemblyNameFlags) m_siInfo.GetValue("_Flags", typeof(AssemblyNameFlags));
+ _Flags = (AssemblyNameFlags)m_siInfo.GetValue("_Flags", typeof(AssemblyNameFlags));
- try {
- _HashAlgorithmForControl = (AssemblyHashAlgorithm) m_siInfo.GetValue("_HashAlgorithmForControl", typeof(AssemblyHashAlgorithm));
- _HashForControl = (byte[]) m_siInfo.GetValue("_HashForControl", typeof(byte[]));
+ try
+ {
+ _HashAlgorithmForControl = (AssemblyHashAlgorithm)m_siInfo.GetValue("_HashAlgorithmForControl", typeof(AssemblyHashAlgorithm));
+ _HashForControl = (byte[])m_siInfo.GetValue("_HashForControl", typeof(byte[]));
}
- catch (SerializationException) { // RTM did not have these defined
+ catch (SerializationException)
+ { // RTM did not have these defined
_HashAlgorithmForControl = AssemblyHashAlgorithm.None;
_HashForControl = null;
}
@@ -341,7 +356,7 @@ namespace System.Reflection {
internal AssemblyName(SerializationInfo info, StreamingContext context)
{
//The graph is not valid until OnDeserialization() has been called.
- m_siInfo = info;
+ m_siInfo = info;
}
public AssemblyName(String assemblyName)
@@ -351,32 +366,32 @@ namespace System.Reflection {
Contract.EndContractBlock();
if ((assemblyName.Length == 0) ||
(assemblyName[0] == '\0'))
- throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
+ throw new ArgumentException(SR.Format_StringZeroLength);
_Name = assemblyName;
nInit();
}
- static public bool ReferenceMatchesDefinition(AssemblyName reference,
- AssemblyName definition)
+ /// <summary>
+ /// Compares the simple names disregarding Version, Culture and PKT. While this clearly does not
+ /// match the intent of this api, this api has been broken this way since its debut and we cannot
+ /// change its behavior now.
+ /// </summary>
+ public static bool ReferenceMatchesDefinition(AssemblyName reference, AssemblyName definition)
{
- // Optimization for common use case
- if (Object.ReferenceEquals(reference, definition))
- {
+ if (object.ReferenceEquals(reference, definition))
return true;
- }
- return ReferenceMatchesDefinitionInternal(reference, definition, true);
- }
-
- /// "parse" tells us to parse the simple name of the assembly as if it was the full name
- /// almost never the right thing to do, but needed for compat
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern bool ReferenceMatchesDefinitionInternal(AssemblyName reference,
- AssemblyName definition,
- bool parse);
+ if (reference == null)
+ throw new ArgumentNullException(nameof(reference));
+ if (definition == null)
+ throw new ArgumentNullException(nameof(definition));
+ string refName = reference.Name ?? string.Empty;
+ string defName = definition.Name ?? string.Empty;
+ return refName.Equals(defName, StringComparison.OrdinalIgnoreCase);
+ }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void nInit(out RuntimeAssembly assembly, bool forIntrospection, bool raiseResolveEvent);
@@ -431,7 +446,7 @@ namespace System.Reflection {
return ProcessorArchitecture.None;
}
- internal void Init(String name,
+ internal void Init(String name,
byte[] publicKey,
byte[] publicKeyToken,
Version version,
@@ -444,18 +459,20 @@ namespace System.Reflection {
{
_Name = name;
- if (publicKey != null) {
+ if (publicKey != null)
+ {
_PublicKey = new byte[publicKey.Length];
Array.Copy(publicKey, _PublicKey, publicKey.Length);
}
-
- if (publicKeyToken != null) {
+
+ if (publicKeyToken != null)
+ {
_PublicKeyToken = new byte[publicKeyToken.Length];
Array.Copy(publicKeyToken, _PublicKeyToken, publicKeyToken.Length);
}
-
+
if (version != null)
- _Version = (Version) version.Clone();
+ _Version = (Version)version.Clone();
_CultureInfo = cultureInfo;
_HashAlgorithm = hashAlgorithm;
@@ -480,7 +497,7 @@ namespace System.Reflection {
{
if (codebase == null)
return string.Empty;
-
+
int position = 0;
char[] dest = EscapeString(codebase, 0, codebase.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar);
if (dest == null)
@@ -528,7 +545,7 @@ namespace System.Reflection {
{
// Should be a rare case where the app tries to feed an invalid Unicode surrogates pair
if (count == 1 || count == end - i)
- throw new FormatException(Environment.GetResourceString("Arg_FormatException"));
+ throw new FormatException(SR.Arg_FormatException);
// need to grab one more char as a Surrogate except when it's a bogus input
++count;
}
@@ -544,7 +561,7 @@ namespace System.Reflection {
// This is the only exception that built in UriParser can throw after a Uri ctor.
// Should not happen unless the app tries to feed an invalid Unicode String
if (numberOfBytes == 0)
- throw new FormatException(Environment.GetResourceString("Arg_FormatException"));
+ throw new FormatException(SR.Arg_FormatException);
i += (count - 1);
@@ -620,7 +637,7 @@ namespace System.Reflection {
dest[destPos++] = pStr[prevInputPos++];
return dest;
}
-
+
internal static void EscapeAsciiChar(char ch, char[] to, ref int pos)
{
to[pos++] = '%';
@@ -657,7 +674,7 @@ namespace System.Reflection {
? ((int)next - (int)'A')
: ((int)next - (int)'a'))
+ 10)));
- }
+ }
private static unsafe bool IsReservedUnreservedOrHash(char c)
{
@@ -688,7 +705,7 @@ namespace System.Reflection {
{
return IsAsciiLetter(character) || (character >= '0' && character <= '9');
}
-
+
private static readonly char[] s_hexUpperChars = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
@@ -696,7 +713,7 @@ namespace System.Reflection {
private const short c_MaxAsciiCharsReallocate = 40;
private const short c_MaxUnicodeCharsReallocate = 40;
private const short c_MaxUTF_8BytesPerUnicodeChar = 4;
- private const short c_EncodedCharsPerByte = 3;
+ private const short c_EncodedCharsPerByte = 3;
private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;=";
private const string RFC3986UnreservedMarks = @"-._~";
}
diff --git a/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs b/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
deleted file mode 100644
index b86955efa5..0000000000
--- a/src/mscorlib/src/System/Reflection/AssemblyNameFlags.cs
+++ /dev/null
@@ -1,53 +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: Flags controlling how an AssemblyName is used
-** during binding
-**
-**
-===========================================================*/
-namespace System.Reflection {
-
- using System;
- [Serializable]
- [FlagsAttribute()]
- public enum AssemblyNameFlags
- {
- None = 0x0000,
- // Flag used to indicate that an assembly ref contains the full public key, not the compressed token.
- // Must match afPublicKey in CorHdr.h.
- PublicKey = 0x0001,
- //ProcArchMask = 0x00F0, // Bits describing the processor architecture
- // Accessible via AssemblyName.ProcessorArchitecture
- EnableJITcompileOptimizer = 0x4000,
- EnableJITcompileTracking = 0x8000,
- Retargetable = 0x0100,
- //ContentType = 0x0E00, // Bits describing the ContentType are accessible via AssemblyName.ContentType
- }
-
- [Serializable]
- public enum AssemblyContentType
- {
- Default = 0x0000,
- WindowsRuntime = 0x0001
- }
-
- [Serializable]
- public enum ProcessorArchitecture
- {
- None = 0x0000,
- MSIL = 0x0001,
- X86 = 0x0002,
- IA64 = 0x0003,
- Amd64 = 0x0004,
- Arm = 0x0005
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Associates.cs b/src/mscorlib/src/System/Reflection/Associates.cs
index 9eaf74a6e9..ed06cb46fc 100644
--- a/src/mscorlib/src/System/Reflection/Associates.cs
+++ b/src/mscorlib/src/System/Reflection/Associates.cs
@@ -4,22 +4,22 @@
//
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Reflection
{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
internal static class Associates
{
[Flags]
internal enum Attributes
{
ComposedOfAllVirtualMethods = 0x1,
- ComposedOfAllPrivateMethods = 0x2,
- ComposedOfNoPublicMembers = 0x4,
- ComposedOfNoStaticMembers = 0x8,
+ ComposedOfAllPrivateMethods = 0x2,
+ ComposedOfNoPublicMembers = 0x4,
+ ComposedOfNoStaticMembers = 0x8,
}
internal static bool IncludeAccessor(MethodInfo associate, bool nonPublic)
@@ -51,7 +51,7 @@ namespace System.Reflection
IntPtr[] genericArgumentHandles = null;
int genericArgumentCount = 0;
- RuntimeType [] genericArguments = declaredType.GetTypeHandleInternal().GetInstantiationInternal();
+ RuntimeType[] genericArguments = declaredType.GetTypeHandleInternal().GetInstantiationInternal();
if (genericArguments != null)
{
genericArgumentCount = genericArguments.Length;
@@ -85,7 +85,7 @@ namespace System.Reflection
// the same or any property in the derived class.
if ((methAttr & MethodAttributes.Virtual) != 0)
{
- bool declaringTypeIsClass =
+ bool declaringTypeIsClass =
(RuntimeTypeHandle.GetAttributes(declaredType) & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class;
// It makes no sense to search for a virtual override of a method declared on an interface.
@@ -99,7 +99,7 @@ namespace System.Reflection
}
}
- RuntimeMethodInfo associateMethod =
+ RuntimeMethodInfo associateMethod =
RuntimeType.GetMethodBase(reflectedType, associateMethodHandle) as RuntimeMethodInfo;
// suppose a property was mapped to a method not in the derivation hierarchy of the reflectedTypeHandle
@@ -125,13 +125,13 @@ namespace System.Reflection
{
addOn = removeOn = fireOn = getter = setter = null;
- Attributes attributes =
+ Attributes attributes =
Attributes.ComposedOfAllPrivateMethods |
Attributes.ComposedOfAllVirtualMethods |
Attributes.ComposedOfNoPublicMembers |
Attributes.ComposedOfNoStaticMembers;
- while(RuntimeTypeHandle.IsGenericVariable(reflectedType))
+ while (RuntimeTypeHandle.IsGenericVariable(reflectedType))
reflectedType = (RuntimeType)reflectedType.BaseType;
bool isInherited = declaringType != reflectedType;
@@ -156,12 +156,12 @@ namespace System.Reflection
continue;
MethodAttributes methAttr = associateMethod.Attributes;
- bool isPrivate =(methAttr & MethodAttributes.MemberAccessMask) == MethodAttributes.Private;
- bool isVirtual =(methAttr & MethodAttributes.Virtual) != 0;
+ bool isPrivate = (methAttr & MethodAttributes.MemberAccessMask) == MethodAttributes.Private;
+ bool isVirtual = (methAttr & MethodAttributes.Virtual) != 0;
MethodAttributes visibility = methAttr & MethodAttributes.MemberAccessMask;
bool isPublic = visibility == MethodAttributes.Public;
- bool isStatic =(methAttr & MethodAttributes.Static) != 0;
+ bool isStatic = (methAttr & MethodAttributes.Static) != 0;
if (isPublic)
{
@@ -202,10 +202,9 @@ namespace System.Reflection
bool isPseudoStatic = (attributes & Attributes.ComposedOfNoStaticMembers) == 0;
bindingFlags = RuntimeType.FilterPreCalculate(isPseudoPublic, isInherited, isPseudoStatic);
- composedOfAllPrivateMethods =(attributes & Attributes.ComposedOfAllPrivateMethods) != 0;
+ composedOfAllPrivateMethods = (attributes & Attributes.ComposedOfAllPrivateMethods) != 0;
other = (otherList != null) ? otherList.ToArray() : null;
}
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/Binder.cs b/src/mscorlib/src/System/Reflection/Binder.cs
deleted file mode 100644
index bf4545fe81..0000000000
--- a/src/mscorlib/src/System/Reflection/Binder.cs
+++ /dev/null
@@ -1,49 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-//
-//
-// This interface defines a set of methods which interact with reflection
-// during the binding process. This control allows systems to apply language
-// specific semantics to the binding and invocation process.
-//
-//
-namespace System.Reflection {
- using System;
- using System.Runtime.InteropServices;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Serializable]
- public abstract class Binder
- {
- // Given a set of methods that match the basic criteria, select a method to
- // invoke. When this method is finished, we should have
- public abstract MethodBase BindToMethod(BindingFlags bindingAttr,MethodBase[] match,ref Object[] args,
- ParameterModifier[] modifiers,CultureInfo culture,String[] names, out Object state);
-
- // Given a set of methods that match the basic criteria, select a method to
- // invoke. When this method is finished, we should have
- public abstract FieldInfo BindToField(BindingFlags bindingAttr,FieldInfo[] match,
- Object value,CultureInfo culture);
-
- // Given a set of methods that match the base criteria, select a method based
- // upon an array of types. This method should return null if no method matchs
- // the criteria.
- public abstract MethodBase SelectMethod(BindingFlags bindingAttr,MethodBase[] match,
- Type[] types,ParameterModifier[] modifiers);
-
-
- // Given a set of propreties that match the base criteria, select one.
- public abstract PropertyInfo SelectProperty(BindingFlags bindingAttr,PropertyInfo[] match,
- Type returnType,Type[] indexes,ParameterModifier[] modifiers);
-
- // ChangeType
- // This method will convert the value into the property type.
- // It throws a cast exception if this fails.
- public abstract Object ChangeType(Object value,Type type,CultureInfo culture);
-
- public abstract void ReorderArgumentArray(ref Object[] args, Object state);
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/BindingFlags.cs b/src/mscorlib/src/System/Reflection/BindingFlags.cs
deleted file mode 100644
index ae0a6d68d3..0000000000
--- a/src/mscorlib/src/System/Reflection/BindingFlags.cs
+++ /dev/null
@@ -1,63 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// BindingFlags are a set of flags that control the binding and invocation process
-//
-// in Reflection. There are two processes. The first is selection of a Member which
-// is the binding phase. The second, is invocation. These flags control how this
-// process works.
-//
-//
-namespace System.Reflection {
-
- using System;
- [Serializable]
- [Flags]
- public enum BindingFlags
- {
-
- // NOTES: We have lookup masks defined in RuntimeType and Activator. If we
- // change the lookup values then these masks may need to change also.
-
- // a place holder for no flag specifed
- Default = 0x00,
-
- // These flags indicate what to search for when binding
- IgnoreCase = 0x01, // Ignore the case of Names while searching
- DeclaredOnly = 0x02, // Only look at the members declared on the Type
- Instance = 0x04, // Include Instance members in search
- Static = 0x08, // Include Static members in search
- Public = 0x10, // Include Public members in search
- NonPublic = 0x20, // Include Non-Public members in search
- FlattenHierarchy = 0x40, // Rollup the statics into the class.
-
- // These flags are used by InvokeMember to determine
- // what type of member we are trying to Invoke.
- // BindingAccess = 0xFF00;
- InvokeMethod = 0x0100,
- CreateInstance = 0x0200,
- GetField = 0x0400,
- SetField = 0x0800,
- GetProperty = 0x1000,
- SetProperty = 0x2000,
-
- // These flags are also used by InvokeMember but they should only
- // be used when calling InvokeMember on a COM object.
- PutDispProperty = 0x4000,
- PutRefDispProperty = 0x8000,
-
- ExactBinding = 0x010000, // Bind with Exact Type matching, No Change type
- SuppressChangeType = 0x020000,
-
- // DefaultValueBinding will return the set of methods having ArgCount or
- // more parameters. This is used for default values, etc.
- OptionalParamBinding = 0x040000,
-
- // These are a couple of misc attributes used
- IgnoreReturn = 0x01000000, // This is used in COM Interop
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/CallingConventions.cs b/src/mscorlib/src/System/Reflection/CallingConventions.cs
deleted file mode 100644
index 266dd55184..0000000000
--- a/src/mscorlib/src/System/Reflection/CallingConventions.cs
+++ /dev/null
@@ -1,28 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// CallingConventions is a set of Bits representing the calling conventions
-//
-// in the system.
-//
-//
-namespace System.Reflection {
- using System.Runtime.InteropServices;
- using System;
- [Serializable]
- [Flags]
- public enum CallingConventions
- {
- //NOTE: If you change this please update COMMember.cpp. These
- // are defined there.
- Standard = 0x0001,
- VarArgs = 0x0002,
- Any = Standard | VarArgs,
- HasThis = 0x0020,
- ExplicitThis = 0x0040,
- }
-}
diff --git a/src/mscorlib/src/System/MidpointRounding.cs b/src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.cs
index a75de43e65..c96bfb5ac1 100644
--- a/src/mscorlib/src/System/MidpointRounding.cs
+++ b/src/mscorlib/src/System/Reflection/ConstructorInfo.CoreCLR.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.
-namespace System
+namespace System.Reflection
{
- public enum MidpointRounding
+ public abstract partial class ConstructorInfo : MethodBase
{
- ToEven = 0,
- AwayFromZero = 1,
+ internal virtual Type GetReturnType() { throw new NotImplementedException(); }
}
}
diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
index b71c7bbff3..96eb45f3e4 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
@@ -18,7 +18,7 @@ using System.Runtime.ConstrainedExecution;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
-namespace System.Reflection
+namespace System.Reflection
{
[Serializable]
public class CustomAttributeData
@@ -268,7 +268,7 @@ namespace System.Reflection
if (type.IsValueType)
return CustomAttributeEncoding.Undefined;
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidKindOfTypeForCA"), nameof(type));
+ throw new ArgumentException(SR.Argument_InvalidKindOfTypeForCA, nameof(type));
}
private static CustomAttributeType InitCustomAttributeType(RuntimeType parameterType)
{
@@ -300,8 +300,8 @@ namespace System.Reflection
customAttributes[i] = new CustomAttributeData(module, records[i]);
return Array.AsReadOnly(customAttributes);
- }
- #endregion
+ }
+ #endregion
#region Internal Static Members
internal unsafe static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken)
@@ -361,7 +361,7 @@ namespace System.Reflection
m_scope = scope;
m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caRecord.tkCtor);
- ParameterInfo[] parameters = m_ctor.GetParametersNoCopy();
+ ParameterInfo[] parameters = m_ctor.GetParametersNoCopy();
m_ctorParams = new CustomAttributeCtorParameter[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType((RuntimeType)parameters[i].ParameterType));
@@ -417,8 +417,7 @@ namespace System.Reflection
new CustomAttributeNamedArgument(type.GetField("CallingConvention"), dllImport.CallingConvention),
new CustomAttributeNamedArgument(type.GetField("BestFitMapping"), dllImport.BestFitMapping),
new CustomAttributeNamedArgument(type.GetField("ThrowOnUnmappableChar"), dllImport.ThrowOnUnmappableChar)
-
- });
+});
}
private void Init(FieldOffsetAttribute fieldOffset)
{
@@ -491,11 +490,11 @@ namespace System.Reflection
public override string ToString()
{
string ctorArgs = "";
- for (int i = 0; i < ConstructorArguments.Count; i ++)
+ for (int i = 0; i < ConstructorArguments.Count; i++)
ctorArgs += String.Format(CultureInfo.CurrentCulture, i == 0 ? "{0}" : ", {0}", ConstructorArguments[i]);
string namedArgs = "";
- for (int i = 0; i < NamedArguments.Count; i ++)
+ for (int i = 0; i < NamedArguments.Count; i++)
namedArgs += String.Format(CultureInfo.CurrentCulture, i == 0 && ctorArgs.Length == 0 ? "{0}" : ", {0}", NamedArguments[i]);
return String.Format(CultureInfo.CurrentCulture, "[{0}({1}{2})]", Constructor.DeclaringType.FullName, ctorArgs, namedArgs);
@@ -514,7 +513,7 @@ namespace System.Reflection
public Type AttributeType { get { return Constructor.DeclaringType; } }
public virtual ConstructorInfo Constructor { get { return m_ctor; } }
-
+
public virtual IList<CustomAttributeTypedArgument> ConstructorArguments
{
get
@@ -605,7 +604,7 @@ namespace System.Reflection
else if (property != null)
type = property.PropertyType;
else
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMemberForNamedArgument"));
+ throw new ArgumentException(SR.Argument_InvalidMemberForNamedArgument);
m_memberInfo = memberInfo;
m_value = new CustomAttributeTypedArgument(type, value);
@@ -627,7 +626,7 @@ namespace System.Reflection
if (m_memberInfo == null)
return base.ToString();
- return String.Format(CultureInfo.CurrentCulture, "{0} = {1}", MemberInfo.Name, TypedValue.ToString(ArgumentType != typeof(object)));
+ return String.Format(CultureInfo.CurrentCulture, "{0} = {1}", MemberInfo.Name, TypedValue.ToString(ArgumentType != typeof(object)));
}
public override int GetHashCode()
{
@@ -640,14 +639,14 @@ namespace System.Reflection
#endregion
#region Internal Members
- internal Type ArgumentType
- {
- get
- {
- return m_memberInfo is FieldInfo ?
- ((FieldInfo)m_memberInfo).FieldType :
- ((PropertyInfo)m_memberInfo).PropertyType;
- }
+ internal Type ArgumentType
+ {
+ get
+ {
+ return m_memberInfo is FieldInfo ?
+ ((FieldInfo)m_memberInfo).FieldType :
+ ((PropertyInfo)m_memberInfo).PropertyType;
+ }
}
#endregion
@@ -730,8 +729,8 @@ namespace System.Reflection
case (CustomAttributeEncoding.Object):
return typeof(object);
- default :
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)encodedType), nameof(encodedType));
+ default:
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), nameof(encodedType));
}
}
@@ -776,7 +775,7 @@ namespace System.Reflection
unsafe { return *(double*)&val; }
default:
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)val), nameof(val));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)val), nameof(val));
}
}
private static RuntimeType ResolveType(RuntimeModule scope, string typeName)
@@ -785,7 +784,7 @@ namespace System.Reflection
if (type == null)
throw new InvalidOperationException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_CATypeResolutionFailed"), typeName));
+ String.Format(CultureInfo.CurrentUICulture, SR.Arg_CATypeResolutionFailed, typeName));
return type;
}
@@ -848,17 +847,17 @@ namespace System.Reflection
else if (encodedType == CustomAttributeEncoding.Type)
{
m_argumentType = typeof(Type);
-
+
m_value = null;
if (encodedArg.StringValue != null)
m_value = ResolveType(scope, encodedArg.StringValue);
}
else if (encodedType == CustomAttributeEncoding.Array)
- {
+ {
encodedType = encodedArg.CustomAttributeType.EncodedArrayType;
Type elementType;
-
+
if (encodedType == CustomAttributeEncoding.Enum)
{
elementType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName);
@@ -869,10 +868,10 @@ namespace System.Reflection
}
m_argumentType = elementType.MakeArrayType();
-
+
if (encodedArg.ArrayValue == null)
{
- m_value = null;
+ m_value = null;
}
else
{
@@ -949,12 +948,12 @@ namespace System.Reflection
return m_argumentType;
}
}
- public object Value
- {
- get
+ public object Value
+ {
+ get
{
return m_value;
- }
+ }
}
#endregion
}
@@ -994,17 +993,17 @@ namespace System.Reflection
[Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeEncodedArgument
- {
+ {
#region Parser
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void ParseAttributeArguments(
- IntPtr pCa,
- int cCa,
+ IntPtr pCa,
+ int cCa,
ref CustomAttributeCtorParameter[] CustomAttributeCtorParameters,
ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument,
RuntimeAssembly assembly);
- internal static void ParseAttributeArguments(ConstArray attributeBlob,
+ internal static void ParseAttributeArguments(ConstArray attributeBlob,
ref CustomAttributeCtorParameter[] customAttributeCtorParameters,
ref CustomAttributeNamedParameter[] customAttributeNamedParameters,
RuntimeModule customAttributeModule)
@@ -1045,7 +1044,7 @@ namespace System.Reflection
public string StringValue { get { return m_stringValue; } }
#endregion
}
-
+
[Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeNamedParameter
@@ -1077,7 +1076,7 @@ namespace System.Reflection
public CustomAttributeEncodedArgument EncodedArgument { get { return m_encodedArgument; } }
#endregion
}
-
+
[Serializable]
[StructLayout(LayoutKind.Auto)]
internal struct CustomAttributeCtorParameter
@@ -1110,18 +1109,18 @@ namespace System.Reflection
private CustomAttributeEncoding m_encodedType; // ...array
private CustomAttributeEncoding m_encodedEnumType; // ...enum
private CustomAttributeEncoding m_encodedArrayType; // ...enum type
- private CustomAttributeEncoding m_padding;
+ private CustomAttributeEncoding m_padding;
#endregion
#region Constructor
- public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType,
+ public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType,
CustomAttributeEncoding encodedEnumType, string enumName)
{
m_encodedType = encodedType;
m_encodedArrayType = encodedArrayType;
m_encodedEnumType = encodedEnumType;
m_enumName = enumName;
- m_padding = m_encodedType;
+ m_padding = m_encodedType;
}
#endregion
@@ -1145,7 +1144,7 @@ namespace System.Reflection
{
Contract.Requires(type != null);
- if (type.GetElementType() != null)
+ if (type.GetElementType() != null)
return false;
if (PseudoCustomAttribute.IsDefined(type, caType))
@@ -1252,7 +1251,7 @@ namespace System.Reflection
return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType);
}
- internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
+ internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
{
Contract.Requires(assembly != null);
Contract.Requires(caType != null);
@@ -1279,8 +1278,8 @@ namespace System.Reflection
Contract.Requires(type != null);
Contract.Requires(caType != null);
- if (type.GetElementType() != null)
- return (caType.IsValueType) ? EmptyArray<Object>.Value : CreateAttributeArrayHelper(caType, 0);
+ if (type.GetElementType() != null)
+ return (caType.IsValueType) ? Array.Empty<Object>() : CreateAttributeArrayHelper(caType, 0);
if (type.IsGenericType && !type.IsGenericTypeDefinition)
type = type.GetGenericTypeDefinition() as RuntimeType;
@@ -1323,7 +1322,7 @@ namespace System.Reflection
private static bool AllowCriticalCustomAttributes(RuntimeType type)
{
- if (type.IsGenericParameter)
+ if (type.IsGenericParameter)
{
// Generic parameters don't have transparency state, so look at the
// declaring method/type. One of declaringMethod or declaringType
@@ -1331,7 +1330,7 @@ namespace System.Reflection
MethodBase declaringMethod = type.DeclaringMethod;
if (declaringMethod != null)
{
- return AllowCriticalCustomAttributes(declaringMethod);
+ return AllowCriticalCustomAttributes(declaringMethod);
}
else
{
@@ -1394,9 +1393,9 @@ namespace System.Reflection
bool useObjectArray = (caType == null || caType.IsValueType || caType.ContainsGenericParameters);
Type arrayType = useObjectArray ? typeof(object) : caType;
- while (pcaCount > 0)
+ while (pcaCount > 0)
result.Add(pca[--pcaCount]);
-
+
while (method != null)
{
object[] attributes = GetCustomAttributes(method.GetRuntimeModule(), method.MetadataToken, 0, caType, mustBeInheritable, result, !AllowCriticalCustomAttributes(method));
@@ -1478,12 +1477,12 @@ namespace System.Reflection
int pcaCount = 0;
Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(parameter, caType, out pcaCount);
- object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule(), parameter.MetadataToken, pcaCount, caType, !AllowCriticalCustomAttributes(parameter));
+ object[] attributes = GetCustomAttributes(parameter.GetRuntimeModule(), parameter.MetadataToken, pcaCount, caType, !AllowCriticalCustomAttributes(parameter));
if (pcaCount > 0) Array.Copy(pca, 0, attributes, attributes.Length - pcaCount, pcaCount);
return attributes;
}
- internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
+ internal static Object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
{
Contract.Requires(assembly != null);
Contract.Requires(caType != null);
@@ -1497,7 +1496,7 @@ namespace System.Reflection
return attributes;
}
- internal static Object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType)
+ internal static Object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType)
{
Contract.Requires(module != null);
Contract.Requires(caType != null);
@@ -1525,7 +1524,7 @@ namespace System.Reflection
RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable)
{
if (decoratedModule.Assembly.ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyCA"));
+ throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
Contract.EndContractBlock();
CustomAttributeRecord[] car = CustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken);
@@ -1577,11 +1576,11 @@ namespace System.Reflection
}
private unsafe static object[] GetCustomAttributes(
- RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount,
+ RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount,
RuntimeType attributeFilterType, bool mustBeInheritable, IList derivedAttributes, bool isDecoratedTargetSecurityTransparent)
{
if (decoratedModule.Assembly.ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyCA"));
+ throw new InvalidOperationException(SR.Arg_ReflectionOnlyCA);
Contract.EndContractBlock();
MetadataImport scope = decoratedModule.MetadataImport;
@@ -1614,8 +1613,8 @@ namespace System.Reflection
IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length);
int blobLen = (int)((byte*)blobEnd - (byte*)blobStart);
- if (!FilterCustomAttributeRecord(caRecord, scope, ref lastAptcaOkAssembly,
- decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable,
+ if (!FilterCustomAttributeRecord(caRecord, scope, ref lastAptcaOkAssembly,
+ decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable,
attributes, derivedAttributes,
out attributeType, out ctor, out ctorHasParameters, out isVarArg))
continue;
@@ -1628,16 +1627,15 @@ namespace System.Reflection
}
else
{
-
}
// Leverage RuntimeConstructorInfo standard .ctor verfication
- RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, isVarArg);
+ RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, isVarArg);
// Create custom attribute object
if (ctorHasParameters)
{
- attribute = CreateCaObject(decoratedModule, ctor, ref blobStart, blobEnd, out cNamedArgs);
+ attribute = CreateCaObject(decoratedModule, ctor, ref blobStart, blobEnd, out cNamedArgs);
}
else
{
@@ -1674,7 +1672,7 @@ namespace System.Reflection
bool isProperty;
RuntimeType type;
object value;
-
+
IntPtr blobItr = caRecord.blob.Signature;
GetPropertyOrFieldData(decoratedModule, ref blobStart, blobEnd, out name, out isProperty, out type, out value);
@@ -1702,12 +1700,12 @@ namespace System.Reflection
if (property == null)
{
throw new CustomAttributeFormatException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString(
- isProperty ? "RFLCT.InvalidPropFail" : "RFLCT.InvalidFieldFail"), name));
+ String.Format(CultureInfo.CurrentUICulture,
+ isProperty ? SR.RFLCT_InvalidPropFail : SR.RFLCT_InvalidFieldFail, name));
}
RuntimeMethodInfo setMethod = property.GetSetMethod(true) as RuntimeMethodInfo;
-
+
// Public properties may have non-public setter methods
if (!setMethod.IsPublic)
continue;
@@ -1733,8 +1731,8 @@ namespace System.Reflection
catch (Exception e)
{
throw new CustomAttributeFormatException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString(
- isProperty ? "RFLCT.InvalidPropFail" : "RFLCT.InvalidFieldFail"), name), e);
+ String.Format(CultureInfo.CurrentUICulture,
+ isProperty ? SR.RFLCT_InvalidPropFail : SR.RFLCT_InvalidFieldFail, name), e);
}
#endregion
}
@@ -1756,7 +1754,7 @@ namespace System.Reflection
private unsafe static bool FilterCustomAttributeRecord(
CustomAttributeRecord caRecord,
MetadataImport scope,
- ref Assembly lastAptcaOkAssembly,
+ ref Assembly lastAptcaOkAssembly,
RuntimeModule decoratedModule,
MetadataToken decoratedToken,
RuntimeType attributeFilterType,
@@ -1772,7 +1770,7 @@ namespace System.Reflection
attributeType = null;
ctorHasParameters = false;
isVarArg = false;
-
+
IntPtr blobStart = caRecord.blob.Signature;
IntPtr blobEnd = (IntPtr)((byte*)blobStart + caRecord.blob.Length);
@@ -1817,13 +1815,13 @@ namespace System.Reflection
// Visibility checks
MetadataToken tkParent = new MetadataToken();
-
+
if (decoratedToken.IsParamDef)
{
tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
tkParent = new MetadataToken(scope.GetParentToken(tkParent));
- }
- else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef)
+ }
+ else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef)
{
tkParent = new MetadataToken(scope.GetParentToken(decoratedToken));
}
@@ -1842,7 +1840,7 @@ namespace System.Reflection
else
{
// We need to relax this when we add support for other types of decorated tokens.
- Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
+ Debug.Assert(decoratedToken.IsModule || decoratedToken.IsAssembly,
"The decoratedToken must be either an assembly, a module, a type, or a member.");
}
@@ -1907,7 +1905,7 @@ namespace System.Reflection
if (attributeUsageAttribute != null)
throw new FormatException(String.Format(
- CultureInfo.CurrentUICulture, Environment.GetResourceString("Format_AttributeUsage"), attributeType));
+ CultureInfo.CurrentUICulture, SR.Format_AttributeUsage, attributeType));
AttributeTargets targets;
bool inherited, allowMultiple;
@@ -1940,7 +1938,7 @@ namespace System.Reflection
{
byte* pBlob = (byte*)blob;
byte* pBlobEnd = (byte*)blobEnd;
- int cNamedArgs;
+ int cNamedArgs;
object ca = _CreateCaObject(module, ctor, &pBlob, pBlobEnd, &cNamedArgs);
blob = (IntPtr)pBlob;
namedArgs = cNamedArgs;
@@ -2025,9 +2023,9 @@ namespace System.Reflection
//AllowMultiple is true for TypeForwardedToAttribute
//Debug.Assert(usage.AllowMultiple == false, "Pseudo CA Error");
}
-#endregion
+ #endregion
-#region Internal Static
+ #region Internal Static
internal static bool IsSecurityAttribute(RuntimeType type)
{
// TODO: Cleanup
@@ -2083,12 +2081,12 @@ namespace System.Reflection
if (!all && s_pca.GetValueOrDefault(caType) == null && !IsSecurityAttribute(caType))
return false;
- if (all || caType == (RuntimeType)typeof(SerializableAttribute))
- {
+ if (all || caType == (RuntimeType)typeof(SerializableAttribute))
+ {
if (SerializableAttribute.IsDefined(type)) return true;
}
- if (all || caType == (RuntimeType)typeof(ComImportAttribute))
- {
+ if (all || caType == (RuntimeType)typeof(ComImportAttribute))
+ {
if (ComImportAttribute.IsDefined(type)) return true;
}
if (all || IsSecurityAttribute(caType))
@@ -2322,8 +2320,8 @@ namespace System.Reflection
{
if (FieldOffsetAttribute.IsDefined(field)) return true;
}
- if (all || caType == (RuntimeType)typeof(NonSerializedAttribute))
- {
+ if (all || caType == (RuntimeType)typeof(NonSerializedAttribute))
+ {
if (NonSerializedAttribute.IsDefined(field)) return true;
}
@@ -2392,6 +2390,6 @@ namespace System.Reflection
{
return false;
}
-#endregion
+ #endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/CustomAttributeExtensions.cs b/src/mscorlib/src/System/Reflection/CustomAttributeExtensions.cs
index c3287e17d1..24e5055b8d 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttributeExtensions.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttributeExtensions.cs
@@ -1,6 +1,7 @@
// 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;
namespace System.Reflection
diff --git a/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs b/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
deleted file mode 100644
index 9aee911a6c..0000000000
--- a/src/mscorlib/src/System/Reflection/CustomAttributeFormatException.cs
+++ /dev/null
@@ -1,37 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// CustomAttributeFormatException is thrown when the binary format of a
-//
-// custom attribute is invalid.
-//
-//
-namespace System.Reflection {
- using System;
- using ApplicationException = System.ApplicationException;
- using System.Runtime.Serialization;
- [Serializable]
- public class CustomAttributeFormatException : FormatException {
-
- public CustomAttributeFormatException()
- : base(Environment.GetResourceString("Arg_CustomAttributeFormatException")) {
- SetErrorCode(__HResults.COR_E_CUSTOMATTRIBUTEFORMAT);
- }
-
- public CustomAttributeFormatException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_CUSTOMATTRIBUTEFORMAT);
- }
-
- public CustomAttributeFormatException(String message, Exception inner) : base(message, inner) {
- SetErrorCode(__HResults.COR_E_CUSTOMATTRIBUTEFORMAT);
- }
-
- protected CustomAttributeFormatException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs b/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
deleted file mode 100644
index 4232fcd2a1..0000000000
--- a/src/mscorlib/src/System/Reflection/DefaultMemberAttribute.cs
+++ /dev/null
@@ -1,39 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// DefaultMemberAttribute is defines the Member of a Type that is the "default"
-//
-// member used by Type.InvokeMember. The default member is simply a name given
-// to a type.
-//
-//
-//
-//
-namespace System.Reflection {
-
- using System;
-
-[Serializable]
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)]
- public sealed class DefaultMemberAttribute : Attribute
- {
- // The name of the member
- private String m_memberName;
-
- // You must provide the name of the member, this is required
- public DefaultMemberAttribute(String memberName) {
- m_memberName = memberName;
- }
-
- // A get accessor to return the name from the attribute.
- // NOTE: There is no setter because the name must be provided
- // to the constructor. The name is not optional.
- public String MemberName {
- get {return m_memberName;}
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
index fb9324902a..e7499e57f0 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AQNBuilder.cs
@@ -20,7 +20,7 @@ namespace System.Reflection.Emit
FullName,
AssemblyQualifiedName,
}
-
+
#region QCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
@@ -76,7 +76,7 @@ namespace System.Reflection.Emit
if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
return null;
}
-
+
TypeNameBuilder tnb = new TypeNameBuilder(CreateTypeNameBuilder());
tnb.Clear();
tnb.ConstructAssemblyQualifiedNameWorker(type, format);
@@ -100,20 +100,20 @@ namespace System.Reflection.Emit
{
if (elementType.HasElementType)
AddElementType(elementType.GetElementType());
-
+
if (elementType.IsPointer)
AddPointer();
else if (elementType.IsByRef)
AddByRef();
- else if (elementType.IsSzArray)
+ else if (elementType.IsSZArray)
AddSzArray();
else if (elementType.IsArray)
AddArray(elementType.GetArrayRank());
}
-
+
private void ConstructAssemblyQualifiedNameWorker(Type type, Format format)
{
Type rootType = type;
@@ -125,13 +125,13 @@ namespace System.Reflection.Emit
List<Type> nestings = new List<Type>();
for (Type t = rootType; t != null; t = t.IsGenericParameter ? null : t.DeclaringType)
nestings.Add(t);
-
+
for (int i = nestings.Count - 1; i >= 0; i--)
{
Type enclosingType = nestings[i];
string name = enclosingType.Name;
- if (i == nestings.Count - 1 && enclosingType.Namespace != null && enclosingType.Namespace.Length != 0)
+ if (i == nestings.Count - 1 && enclosingType.Namespace != null && enclosingType.Namespace.Length != 0)
name = enclosingType.Namespace + "." + name;
AddName(name);
@@ -146,7 +146,7 @@ namespace System.Reflection.Emit
for (int i = 0; i < genericArguments.Length; i++)
{
Format genericArgumentsFormat = format == Format.FullName ? Format.AssemblyQualifiedName : format;
-
+
OpenGenericArgument();
ConstructAssemblyQualifiedNameWorker(genericArguments[i], genericArgumentsFormat);
CloseGenericArgument();
@@ -160,7 +160,7 @@ namespace System.Reflection.Emit
if (format == Format.AssemblyQualifiedName)
AddAssemblySpec(type.Module.Assembly.FullName);
}
-
+
private void OpenGenericArguments() { OpenGenericArguments(m_typeNameBuilder); }
private void CloseGenericArguments() { CloseGenericArguments(m_typeNameBuilder); }
private void OpenGenericArgument() { OpenGenericArgument(m_typeNameBuilder); }
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
index 5575e28917..6d9cb0db2f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
@@ -48,11 +48,11 @@ namespace System.Reflection.Emit
None = 0x00000000,
// Security attributes which affect the module security descriptor
- AllCritical = 0x00000001,
- Aptca = 0x00000002,
- Critical = 0x00000004,
- Transparent = 0x00000008,
- TreatAsSafe = 0x00000010,
+ AllCritical = 0x00000001,
+ Aptca = 0x00000002,
+ Critical = 0x00000004,
+ Transparent = 0x00000008,
+ TreatAsSafe = 0x00000010,
}
// When the user calls AppDomain.DefineDynamicAssembly the loader creates a new InternalAssemblyBuilder.
@@ -61,7 +61,7 @@ namespace System.Reflection.Emit
// 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
// because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder.
-
+
// Only the caller of DefineDynamicAssembly will get an AssemblyBuilder.
// There is a 1-1 relationship between InternalAssemblyBuilder and AssemblyBuilder.
// AssemblyBuilder is composed of its InternalAssemblyBuilder.
@@ -94,39 +94,39 @@ namespace System.Reflection.Emit
#region Methods inherited from Assembly
public override String[] GetManifestResourceNames()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override FileStream GetFile(String name)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override FileStream[] GetFiles(bool getResourceModules)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override Stream GetManifestResourceStream(Type type, String name)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override Stream GetManifestResourceStream(String name)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override String Location
{
get
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
}
@@ -134,13 +134,13 @@ namespace System.Reflection.Emit
{
get
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
}
public override Type[] GetExportedTypes()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicAssembly"));
+ throw new NotSupportedException(SR.NotSupported_DynamicAssembly);
}
public override String ImageRuntimeVersion
@@ -177,16 +177,12 @@ namespace System.Reflection.Emit
private bool m_fManifestModuleUsedAsDefinedModule;
internal const string MANIFEST_MODULE_NAME = "RefEmit_InMemoryManifestModule";
-#if FEATURE_APPX
- private bool m_profileAPICheck;
-#endif
-
internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module)
{
Contract.Requires(module != null);
Debug.Assert(this.InternalAssembly == module.Assembly);
- lock(SyncRoot)
+ lock (SyncRoot)
{
// in CoreCLR there is only one module in each dynamic assembly, the manifest module
if (m_manifestModuleBuilder.InternalModule == module)
@@ -216,16 +212,6 @@ namespace System.Reflection.Emit
{
return InternalAssembly.GetNativeHandle();
}
-
-#if FEATURE_APPX
- internal bool ProfileAPICheck
- {
- get
- {
- return m_profileAPICheck;
- }
- }
-#endif
#endregion
#region Constructor
@@ -242,13 +228,10 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(name));
if (access != AssemblyBuilderAccess.Run
-#if FEATURE_REFLECTION_ONLY_LOAD
- && access != AssemblyBuilderAccess.ReflectionOnly
-#endif // FEATURE_REFLECTION_ONLY_LOAD
&& access != AssemblyBuilderAccess.RunAndCollect
)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access), nameof(access));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), nameof(access));
}
if (securityContextSource < SecurityContextSource.CurrentAppDomain ||
@@ -304,14 +287,7 @@ namespace System.Reflection.Emit
name.Name,
access,
dir);
-#if FEATURE_APPX
- if (AppDomain.ProfileAPICheck)
- {
- RuntimeAssembly creator = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (creator != null && !creator.IsFrameworkAssembly())
- m_profileAPICheck = true;
- }
-#endif
+
// Make sure that ManifestModule is properly initialized
// We need to do this before setting any CustomAttribute
InitManifestModule();
@@ -331,7 +307,7 @@ namespace System.Reflection.Emit
// because it hasn't been initialized.
// However, it can be used to set the custom attribute on the Assembly
m_manifestModuleBuilder = new ModuleBuilder(this, modBuilder);
-
+
// We are only setting the name in the managed ModuleBuilderData here.
// The name in the underlying metadata will be set when the
// manifest module is created during nCreateDynamicAssembly.
@@ -351,7 +327,7 @@ namespace System.Reflection.Emit
* to have a strong name and a hash will be computed when the assembly
* is saved.
**********************************************/
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access)
@@ -363,7 +339,7 @@ namespace System.Reflection.Emit
null, ref stackMark, null, SecurityContextSource.CurrentAssembly);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static AssemblyBuilder DefineDynamicAssembly(
AssemblyName name,
AssemblyBuilderAccess access,
@@ -425,9 +401,9 @@ namespace System.Reflection.Emit
* a transient module.
*
**********************************************/
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ModuleBuilder DefineDynamicModule(
- String name)
+ String name)
{
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
@@ -435,39 +411,39 @@ namespace System.Reflection.Emit
return DefineDynamicModuleInternal(name, false, ref stackMark);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ModuleBuilder DefineDynamicModule(
- String name,
- bool emitSymbolInfo) // specify if emit symbol info or not
+ String name,
+ bool emitSymbolInfo) // specify if emit symbol info or not
{
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return DefineDynamicModuleInternal( name, emitSymbolInfo, ref stackMark );
+ return DefineDynamicModuleInternal(name, emitSymbolInfo, ref stackMark);
}
private ModuleBuilder DefineDynamicModuleInternal(
- String name,
- bool emitSymbolInfo, // specify if emit symbol info or not
+ String name,
+ bool emitSymbolInfo, // specify if emit symbol info or not
ref StackCrawlMark stackMark)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineDynamicModuleInternalNoLock(name, emitSymbolInfo, ref stackMark);
}
}
private ModuleBuilder DefineDynamicModuleInternalNoLock(
- String name,
- bool emitSymbolInfo, // specify if emit symbol info or not
+ String name,
+ bool emitSymbolInfo, // specify if emit symbol info or not
ref StackCrawlMark stackMark)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidName"), nameof(name));
+ throw new ArgumentException(SR.Argument_InvalidName, nameof(name));
Contract.Ensures(Contract.Result<ModuleBuilder>() != null);
Contract.EndContractBlock();
@@ -481,7 +457,7 @@ namespace System.Reflection.Emit
// create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created
if (m_fManifestModuleUsedAsDefinedModule == true)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoMultiModuleAssembly"));
+ throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly);
// Init(...) has already been called on m_manifestModuleBuilder in InitManifestModule()
dynModule = m_manifestModuleBuilder;
@@ -492,7 +468,7 @@ namespace System.Reflection.Emit
writer = SymWrapperCore.SymWriter.CreateSymWriter();
String fileName = "Unused"; // this symfile is never written to disk so filename does not matter.
-
+
// Pass the "real" module to the VM
pInternalSymWriter = ModuleBuilder.nCreateISymWriterForDynamicModule(dynModule.InternalModule, fileName);
@@ -512,14 +488,14 @@ namespace System.Reflection.Emit
return dynModule;
} // DefineDynamicModuleInternalNoLock
-#endregion
+ #endregion
internal void CheckContext(params Type[][] typess)
{
if (typess == null)
return;
-
- foreach(Type[] types in typess)
+
+ foreach (Type[] types in typess)
if (types != null)
CheckContext(types);
}
@@ -528,23 +504,23 @@ namespace System.Reflection.Emit
{
if (types == null)
return;
-
+
foreach (Type type in types)
{
if (type == null)
continue;
if (type.Module == null || type.Module.Assembly == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotValid"));
+ throw new ArgumentException(SR.Argument_TypeNotValid);
if (type.Module.Assembly == typeof(object).Module.Assembly)
continue;
if (type.Module.Assembly.ReflectionOnly && !ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext1", type.AssemblyQualifiedName));
+ throw new InvalidOperationException(SR.Format(SR.Arugment_EmitMixedContext1, type.AssemblyQualifiedName));
if (!type.Module.Assembly.ReflectionOnly && ReflectionOnly)
- throw new InvalidOperationException(Environment.GetResourceString("Arugment_EmitMixedContext2", type.AssemblyQualifiedName));
+ throw new InvalidOperationException(SR.Format(SR.Arugment_EmitMixedContext2, type.AssemblyQualifiedName));
}
}
@@ -585,27 +561,27 @@ namespace System.Reflection.Emit
{
return InternalAssembly.GetManifestResourceNames();
}
-
+
public override FileStream GetFile(String name)
{
return InternalAssembly.GetFile(name);
}
-
+
public override FileStream[] GetFiles(bool getResourceModules)
{
return InternalAssembly.GetFiles(getResourceModules);
}
-
+
public override Stream GetManifestResourceStream(Type type, String name)
{
return InternalAssembly.GetManifestResourceStream(type, name);
}
-
+
public override Stream GetManifestResourceStream(String name)
{
return InternalAssembly.GetManifestResourceStream(name);
}
-
+
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
return InternalAssembly.GetManifestResourceInfo(resourceName);
@@ -626,7 +602,7 @@ namespace System.Reflection.Emit
return InternalAssembly.ImageRuntimeVersion;
}
}
-
+
public override String CodeBase
{
get
@@ -637,9 +613,9 @@ namespace System.Reflection.Emit
// Override the EntryPoint method on Assembly.
// This doesn't need to be synchronized because it is simple enough
- public override MethodInfo EntryPoint
+ public override MethodInfo EntryPoint
{
- get
+ get
{
return m_assemblyData.m_entryPointMethod;
}
@@ -721,7 +697,7 @@ namespace System.Reflection.Emit
return InternalAssembly.GetLoadedModules(getResourceModules);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -729,7 +705,7 @@ namespace System.Reflection.Emit
}
// Useful for binding to a very specific version of a satellite assembly
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -738,7 +714,8 @@ namespace System.Reflection.Emit
public override bool IsDynamic
{
- get {
+ get
+ {
return true;
}
}
@@ -751,28 +728,28 @@ namespace System.Reflection.Emit
*
**********************************************/
public ModuleBuilder GetDynamicModule(
- String name) // the name of module for the look up
+ String name) // the name of module for the look up
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetDynamicModuleNoLock(name);
}
}
private ModuleBuilder GetDynamicModuleNoLock(
- String name) // the name of module for the look up
+ String name) // the name of module for the look up
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
Contract.EndContractBlock();
BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilder.GetDynamicModule( " + name + " )");
int size = m_assemblyData.m_moduleBuilderList.Count;
for (int i = 0; i < size; i++)
{
- ModuleBuilder moduleBuilder = (ModuleBuilder) m_assemblyData.m_moduleBuilderList[i];
+ ModuleBuilder moduleBuilder = (ModuleBuilder)m_assemblyData.m_moduleBuilderList[i];
if (moduleBuilder.m_moduleData.m_strModuleName.Equals(name))
{
return moduleBuilder;
@@ -792,8 +769,8 @@ namespace System.Reflection.Emit
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
-
- lock(SyncRoot)
+
+ lock (SyncRoot)
{
SetCustomAttributeNoLock(con, binaryAttribute);
}
@@ -828,7 +805,7 @@ namespace System.Reflection.Emit
}
Contract.EndContractBlock();
- lock(SyncRoot)
+ lock (SyncRoot)
{
SetCustomAttributeNoLock(customBuilder);
}
@@ -837,7 +814,7 @@ namespace System.Reflection.Emit
private void SetCustomAttributeNoLock(CustomAttributeBuilder customBuilder)
{
customBuilder.CreateCustomAttribute(
- m_manifestModuleBuilder,
+ m_manifestModuleBuilder,
AssemblyBuilderData.m_tkAssembly); // This is the AssemblyDef token
// Track the CA for persistence
@@ -852,11 +829,11 @@ namespace System.Reflection.Emit
* Private methods
*
**********************************************/
-
+
/**********************************************
* Make a private constructor so these cannot be constructed externally.
* @internonly
**********************************************/
- private AssemblyBuilder() {}
+ private AssemblyBuilder() { }
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
index b3d1711307..ead2fafcef 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderAccess.cs
@@ -7,16 +7,13 @@ using System;
// This enumeration defines the access modes for a dynamic assembly.
// EE uses these enum values..look for m_dwDynamicAssemblyAccess in Assembly.hpp
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
[Serializable]
[Flags]
public enum AssemblyBuilderAccess
{
Run = 1,
-#if FEATURE_REFLECTION_ONLY_LOAD
- ReflectionOnly = 6, // 4 | Save,
-#endif // FEATURE_REFLECTION_ONLY_LOAD
RunAndCollect = 8 | Run
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
index 7ac9daeac0..529ba54514 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilderData.cs
@@ -6,7 +6,8 @@
////////////////////////////////////////////////////////////////////////////////
//
-namespace System.Reflection.Emit {
+namespace System.Reflection.Emit
+{
using System;
using IList = System.Collections.IList;
using System.Collections.Generic;
@@ -25,10 +26,10 @@ namespace System.Reflection.Emit {
internal class AssemblyBuilderData
{
internal AssemblyBuilderData(
- InternalAssemblyBuilder assembly,
- String strAssemblyName,
- AssemblyBuilderAccess access,
- String dir)
+ InternalAssemblyBuilder assembly,
+ String strAssemblyName,
+ AssemblyBuilderAccess access,
+ String dir)
{
m_assembly = assembly;
m_strAssemblyName = strAssemblyName;
@@ -44,8 +45,8 @@ namespace System.Reflection.Emit {
m_strDir = dir;
m_peFileKind = PEFileKinds.Dll;
- }
-
+ }
+
// Helper to add a dynamic module into the tracking list
internal void AddModule(ModuleBuilder dynModule)
{
@@ -56,7 +57,6 @@ namespace System.Reflection.Emit {
// Helper to track CAs to persist onto disk
internal void AddCustomAttribute(CustomAttributeBuilder customBuilder)
{
-
// make sure we have room for this CA
if (m_CABuilders == null)
{
@@ -64,31 +64,30 @@ namespace System.Reflection.Emit {
}
if (m_iCABuilder == m_CABuilders.Length)
{
- CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2];
+ CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2];
Array.Copy(m_CABuilders, 0, tempCABuilders, 0, m_iCABuilder);
- m_CABuilders = tempCABuilders;
+ m_CABuilders = tempCABuilders;
}
m_CABuilders[m_iCABuilder] = customBuilder;
-
+
m_iCABuilder++;
}
// Helper to track CAs to persist onto disk
internal void AddCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
-
// make sure we have room for this CA
if (m_CABytes == null)
{
m_CABytes = new byte[m_iInitialSize][];
- m_CACons = new ConstructorInfo[m_iInitialSize];
+ m_CACons = new ConstructorInfo[m_iInitialSize];
}
if (m_iCAs == m_CABytes.Length)
{
// enlarge the arrays
- byte[][] temp = new byte[m_iCAs * 2][];
+ byte[][] temp = new byte[m_iCAs * 2][];
ConstructorInfo[] tempCon = new ConstructorInfo[m_iCAs * 2];
- for (int i=0; i < m_iCAs; i++)
+ for (int i = 0; i < m_iCAs; i++)
{
temp[i] = m_CABytes[i];
tempCon[i] = m_CACons[i];
@@ -103,12 +102,12 @@ namespace System.Reflection.Emit {
m_CACons[m_iCAs] = con;
m_iCAs++;
}
-
+
// Helper to ensure the type name is unique underneath assemblyBuilder
internal void CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType)
{
- BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.CheckTypeNameConflict( " + strTypeName + " )");
- for (int i = 0; i < m_moduleBuilderList.Count; i++)
+ BCLDebug.Log("DYNIL", "## DYNIL LOGGING: AssemblyBuilderData.CheckTypeNameConflict( " + strTypeName + " )");
+ for (int i = 0; i < m_moduleBuilderList.Count; i++)
{
ModuleBuilder curModule = m_moduleBuilderList[i];
curModule.CheckTypeNameConflict(strTypeName, enclosingType);
@@ -121,60 +120,59 @@ namespace System.Reflection.Emit {
// if (enclosingType == null && m_assembly.GetType(strTypeName, false, false) != null)
// {
// // Cannot have two types with the same name
- // throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName"));
+ // throw new ArgumentException(SR.Argument_DuplicateTypeName);
// }
}
-
- internal List<ModuleBuilder> m_moduleBuilderList;
- internal List<ResWriterData> m_resWriterList;
- internal String m_strAssemblyName;
- internal AssemblyBuilderAccess m_access;
+
+ internal List<ModuleBuilder> m_moduleBuilderList;
+ internal List<ResWriterData> m_resWriterList;
+ internal String m_strAssemblyName;
+ internal AssemblyBuilderAccess m_access;
private InternalAssemblyBuilder m_assembly;
-
- internal Type[] m_publicComTypeList;
- internal int m_iPublicComTypeCount;
-
- internal bool m_isSaved;
- internal const int m_iInitialSize = 16;
- internal String m_strDir;
+
+ internal Type[] m_publicComTypeList;
+ internal int m_iPublicComTypeCount;
+
+ internal bool m_isSaved;
+ internal const int m_iInitialSize = 16;
+ internal String m_strDir;
// hard coding the assembly def token
- internal const int m_tkAssembly = 0x20000001;
-
+ internal const int m_tkAssembly = 0x20000001;
+
// tracking AssemblyDef's CAs for persistence to disk
internal CustomAttributeBuilder[] m_CABuilders;
- internal int m_iCABuilder;
- internal byte[][] m_CABytes;
- internal ConstructorInfo[] m_CACons;
- internal int m_iCAs;
- internal PEFileKinds m_peFileKind; // assembly file kind
- internal MethodInfo m_entryPointMethod;
- internal Assembly m_ISymWrapperAssembly;
+ internal int m_iCABuilder;
+ internal byte[][] m_CABytes;
+ internal ConstructorInfo[] m_CACons;
+ internal int m_iCAs;
+ internal PEFileKinds m_peFileKind; // assembly file kind
+ internal MethodInfo m_entryPointMethod;
+ internal Assembly m_ISymWrapperAssembly;
// For unmanaged resources
- internal String m_strResourceFileName;
- internal byte[] m_resourceBytes;
- internal NativeVersionInfo m_nativeVersion;
- internal bool m_hasUnmanagedVersionInfo;
- internal bool m_OverrideUnmanagedVersionInfo;
-
+ internal String m_strResourceFileName;
+ internal byte[] m_resourceBytes;
+ internal NativeVersionInfo m_nativeVersion;
+ internal bool m_hasUnmanagedVersionInfo;
+ internal bool m_OverrideUnmanagedVersionInfo;
}
-
+
/**********************************************
*
* Internal structure to track the list of ResourceWriter for
* AssemblyBuilder & ModuleBuilder.
*
**********************************************/
- internal class ResWriterData
+ internal class ResWriterData
{
- internal String m_strName;
- internal String m_strFileName;
- internal String m_strFullFileName;
- internal Stream m_memoryStream;
- internal ResWriterData m_nextResWriter;
- internal ResourceAttributes m_attribute;
+ internal String m_strName;
+ internal String m_strFileName;
+ internal String m_strFullFileName;
+ internal Stream m_memoryStream;
+ internal ResWriterData m_nextResWriter;
+ internal ResourceAttributes m_attribute;
}
internal class NativeVersionInfo
@@ -191,15 +189,15 @@ namespace System.Reflection.Emit {
m_strFileVersion = null;
m_lcid = -1;
}
-
- internal String m_strDescription;
- internal String m_strCompany;
- internal String m_strTitle;
- internal String m_strCopyright;
- internal String m_strTrademark;
- internal String m_strProduct;
- internal String m_strProductVersion;
- internal String m_strFileVersion;
- internal int m_lcid;
+
+ internal String m_strDescription;
+ internal String m_strCompany;
+ internal String m_strTitle;
+ internal String m_strCopyright;
+ internal String m_strTrademark;
+ internal String m_strProduct;
+ internal String m_strProductVersion;
+ internal String m_strFileVersion;
+ internal int m_lcid;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
index 3bc02860a1..3ca9b2eb9d 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ConstructorBuilder.cs
@@ -4,8 +4,8 @@
//
-namespace System.Reflection.Emit
-{
+namespace System.Reflection.Emit
+{
using System;
using System.Reflection;
using CultureInfo = System.Globalization.CultureInfo;
@@ -14,9 +14,9 @@ namespace System.Reflection.Emit
using System.Security;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
-
+
public sealed class ConstructorBuilder : ConstructorInfo
- {
+ {
private readonly MethodBuilder m_methodBuilder;
internal bool m_isDefaultConstructor;
@@ -25,7 +25,7 @@ namespace System.Reflection.Emit
private ConstructorBuilder()
{
}
-
+
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, TypeBuilder type)
{
@@ -33,18 +33,18 @@ namespace System.Reflection.Emit
byte[] sigBytes;
MethodToken token;
- m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null,
+ m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null,
parameterTypes, requiredCustomModifiers, optionalCustomModifiers, mod, type, false);
type.m_listMethods.Add(m_methodBuilder);
-
+
sigBytes = m_methodBuilder.GetMethodSignature().InternalGetSignature(out sigLength);
-
+
token = m_methodBuilder.GetToken();
}
internal ConstructorBuilder(String name, MethodAttributes attributes, CallingConventions callingConvention,
- Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
+ Type[] parameterTypes, ModuleBuilder mod, TypeBuilder type) :
this(name, attributes, callingConvention, parameterTypes, null, null, mod, type)
{
}
@@ -68,7 +68,7 @@ namespace System.Reflection.Emit
{
return m_methodBuilder.ToString();
}
-
+
#endregion
#region MemberInfo Overrides
@@ -76,12 +76,12 @@ namespace System.Reflection.Emit
{
get { return m_methodBuilder.MetadataTokenInternal; }
}
-
+
public override Module Module
{
get { return m_methodBuilder.Module; }
}
-
+
public override Type ReflectedType
{
get { return m_methodBuilder.ReflectedType; }
@@ -91,8 +91,8 @@ namespace System.Reflection.Emit
{
get { return m_methodBuilder.DeclaringType; }
}
-
- public override String Name
+
+ public override String Name
{
get { return m_methodBuilder.Name; }
}
@@ -100,9 +100,9 @@ namespace System.Reflection.Emit
#endregion
#region MethodBase Overrides
- public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
+ public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
[Pure]
@@ -111,7 +111,7 @@ namespace System.Reflection.Emit
ConstructorInfo rci = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes);
return rci.GetParameters();
}
-
+
public override MethodAttributes Attributes
{
get { return m_methodBuilder.Attributes; }
@@ -121,20 +121,20 @@ namespace System.Reflection.Emit
{
return m_methodBuilder.GetMethodImplementationFlags();
}
-
- public override RuntimeMethodHandle MethodHandle
+
+ public override RuntimeMethodHandle MethodHandle
{
get { return m_methodBuilder.MethodHandle; }
}
-
+
#endregion
#region ConstructorInfo Overrides
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
-
+
#endregion
#region ICustomAttributeProvider Implementation
@@ -147,8 +147,8 @@ namespace System.Reflection.Emit
{
return m_methodBuilder.GetCustomAttributes(attributeType, inherit);
}
-
- public override bool IsDefined (Type attributeType, bool inherit)
+
+ public override bool IsDefined(Type attributeType, bool inherit)
{
return m_methodBuilder.IsDefined(attributeType, inherit);
}
@@ -160,7 +160,7 @@ namespace System.Reflection.Emit
{
return m_methodBuilder.GetToken();
}
-
+
public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, String strParamName)
{
// Theoretically we shouldn't allow iSequence to be 0 because in reflection ctors don't have
@@ -171,50 +171,50 @@ namespace System.Reflection.Emit
attributes = attributes & ~ParameterAttributes.ReservedMask;
return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName);
}
-
- public ILGenerator GetILGenerator()
+
+ public ILGenerator GetILGenerator()
{
if (m_isDefaultConstructor)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
+ throw new InvalidOperationException(SR.InvalidOperation_DefaultConstructorILGen);
return m_methodBuilder.GetILGenerator();
}
-
+
public ILGenerator GetILGenerator(int streamSize)
{
if (m_isDefaultConstructor)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_DefaultConstructorILGen"));
+ throw new InvalidOperationException(SR.InvalidOperation_DefaultConstructorILGen);
return m_methodBuilder.GetILGenerator(streamSize);
}
- public override CallingConventions CallingConvention
- {
- get
- {
+ public override CallingConventions CallingConvention
+ {
+ get
+ {
if (DeclaringType.IsGenericType)
return CallingConventions.HasThis;
-
- return CallingConventions.Standard;
- }
+
+ return CallingConventions.Standard;
+ }
}
-
+
public Module GetModule()
{
return m_methodBuilder.GetModule();
}
-
+
// This always returns null. Is that what we want?
- internal override Type GetReturnType()
+ internal override Type GetReturnType()
{
return m_methodBuilder.ReturnType;
}
-
- public String Signature
+
+ public String Signature
{
get { return m_methodBuilder.Signature; }
}
-
+
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_methodBuilder.SetCustomAttribute(con, binaryAttribute);
@@ -225,12 +225,12 @@ namespace System.Reflection.Emit
m_methodBuilder.SetCustomAttribute(customBuilder);
}
- public void SetImplementationFlags(MethodImplAttributes attributes)
+ public void SetImplementationFlags(MethodImplAttributes attributes)
{
m_methodBuilder.SetImplementationFlags(attributes);
}
-
- public bool InitLocals
+
+ public bool InitLocals
{
get { return m_methodBuilder.InitLocals; }
set { m_methodBuilder.InitLocals = value; }
diff --git a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
index 5d08ca08f0..cf5bd11de6 100644
--- a/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/CustomAttributeBuilder.cs
@@ -12,18 +12,19 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
-
- using System;
- using System.Reflection;
- using System.IO;
- using System.Text;
- using System.Runtime.InteropServices;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
+
+
+using System;
+using System.Reflection;
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection.Emit
+{
public class CustomAttributeBuilder
{
// public constructor to form the custom attribute with constructor and constructor
@@ -31,17 +32,17 @@ namespace System.Reflection.Emit {
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs)
{
InitCustomAttributeBuilder(con, constructorArgs,
- new PropertyInfo[]{}, new Object[]{},
- new FieldInfo[]{}, new Object[]{});
+ new PropertyInfo[] { }, new Object[] { },
+ new FieldInfo[] { }, new Object[] { });
}
-
+
// public constructor to form the custom attribute with constructor, constructor
// parameters and named properties.
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
PropertyInfo[] namedProperties, Object[] propertyValues)
{
InitCustomAttributeBuilder(con, constructorArgs, namedProperties,
- propertyValues, new FieldInfo[]{}, new Object[]{});
+ propertyValues, new FieldInfo[] { }, new Object[] { });
}
// public constructor to form the custom attribute with constructor and constructor
@@ -49,8 +50,8 @@ namespace System.Reflection.Emit {
public CustomAttributeBuilder(ConstructorInfo con, Object[] constructorArgs,
FieldInfo[] namedFields, Object[] fieldValues)
{
- InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[]{},
- new Object[]{}, namedFields, fieldValues);
+ InitCustomAttributeBuilder(con, constructorArgs, new PropertyInfo[] { },
+ new Object[] { }, namedFields, fieldValues);
}
// public constructor to form the custom attribute with constructor and constructor
@@ -117,17 +118,17 @@ namespace System.Reflection.Emit {
if (fieldValues == null)
throw new ArgumentNullException(nameof(fieldValues));
if (namedProperties.Length != propertyValues.Length)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedProperties, propertyValues");
+ throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedProperties, propertyValues");
if (namedFields.Length != fieldValues.Length)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayLengthsDiffer"), "namedFields, fieldValues");
+ throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedFields, fieldValues");
Contract.EndContractBlock();
if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static ||
(con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructor"));
+ throw new ArgumentException(SR.Argument_BadConstructor);
if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadConstructorCallConv"));
+ throw new ArgumentException(SR.Argument_BadConstructorCallConv);
// Cache information used elsewhere.
m_con = con;
@@ -142,12 +143,12 @@ namespace System.Reflection.Emit {
// Since we're guaranteed a non-var calling convention, the number of arguments must equal the number of parameters.
if (paramTypes.Length != constructorArgs.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterCountsForConstructor"));
+ throw new ArgumentException(SR.Argument_BadParameterCountsForConstructor);
// Verify that the constructor has a valid signature (custom attributes only support a subset of our type system).
for (i = 0; i < paramTypes.Length; i++)
if (!ValidateType(paramTypes[i]))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
+ throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute);
// Now verify that the types of the actual parameters are compatible with the types of the formal parameters.
for (i = 0; i < paramTypes.Length; i++)
@@ -194,11 +195,11 @@ namespace System.Reflection.Emit {
// Validate property type.
if (!ValidateType(propType))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
+ throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute);
// Property has to be writable.
if (!property.CanWrite)
- throw new ArgumentException(Environment.GetResourceString("Argument_NotAWritableProperty"));
+ throw new ArgumentException(SR.Argument_NotAWritableProperty);
// Property has to be from the same class or base class as ConstructorInfo.
if (property.DeclaringType != con.DeclaringType
@@ -216,7 +217,7 @@ namespace System.Reflection.Emit {
// type is one.
if (!(property.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)property.DeclaringType).BakedRuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadPropertyForConstructorBuilder"));
+ throw new ArgumentException(SR.Argument_BadPropertyForConstructorBuilder);
}
}
@@ -252,7 +253,7 @@ namespace System.Reflection.Emit {
// Validate field type.
if (!ValidateType(fldType))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeInCustomAttribute"));
+ throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute);
// Field has to be from the same class or base class as ConstructorInfo.
if (namedField.DeclaringType != con.DeclaringType
@@ -270,7 +271,7 @@ namespace System.Reflection.Emit {
// type is one.
if (!(namedField.DeclaringType is TypeBuilder) ||
!con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldForConstructorBuilder"));
+ throw new ArgumentException(SR.Argument_BadFieldForConstructorBuilder);
}
}
@@ -280,7 +281,7 @@ namespace System.Reflection.Emit {
{
VerifyTypeAndPassedObjectType(fldType, fieldValue.GetType(), $"{nameof(fieldValues)}[{i}]");
}
-
+
// First a byte indicating that this is a field.
writer.Write((byte)CustomAttributeEncoding.Field);
@@ -298,11 +299,11 @@ namespace System.Reflection.Emit {
{
if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB"), paramName);
+ throw new ArgumentException(SR.Argument_BadParameterTypeForCAB, paramName);
}
}
@@ -452,8 +453,7 @@ namespace System.Reflection.Emit {
{
String typeName = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName);
if (typeName == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForCA",
- value.GetType()));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeForCA, value.GetType()));
EmitString(writer, typeName);
}
}
@@ -526,8 +526,8 @@ namespace System.Reflection.Emit {
// value cannot be a "System.Object" object.
// If we allow this we will get into an infinite recursion
if (ot == typeof(object))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", ot.ToString()));
-
+ throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, ot.ToString()));
+
EmitType(writer, ot);
EmitValue(writer, ot, value);
}
@@ -537,13 +537,13 @@ namespace System.Reflection.Emit {
if (value != null)
typename = value.GetType().ToString();
-
- throw new ArgumentException(Environment.GetResourceString("Argument_BadParameterTypeForCAB", typename));
+
+ throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, typename));
}
}
-
-
+
+
// return the byte interpretation of the custom attribute
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner)
@@ -556,12 +556,12 @@ namespace System.Reflection.Emit {
//*************************************************
internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner, int tkAttrib, bool toDisk)
{
- TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk,
+ TypeBuilder.DefineCustomAttribute(mod, tkOwner, tkAttrib, m_blob, toDisk,
typeof(System.Diagnostics.DebuggableAttribute) == m_con.DeclaringType);
}
- internal ConstructorInfo m_con;
- internal Object[] m_constructorArgs;
- internal byte[] m_blob;
+ internal ConstructorInfo m_con;
+ internal Object[] m_constructorArgs;
+ internal byte[] m_blob;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
index cb2667a104..b592053f9f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicILGenerator.cs
@@ -6,7 +6,6 @@
namespace System.Reflection.Emit
{
-
using System;
using System.Globalization;
using System.Diagnostics.SymbolStore;
@@ -22,7 +21,6 @@ namespace System.Reflection.Emit
internal class DynamicILGenerator : ILGenerator
{
-
internal DynamicScope m_scope;
private int m_methodSigToken;
@@ -44,16 +42,6 @@ namespace System.Reflection.Emit
new DynamicResolver(this));
}
-#if FEATURE_APPX
- private bool ProfileAPICheck
- {
- get
- {
- return ((DynamicMethod)m_methodBuilder).ProfileAPICheck;
- }
- }
-#endif // FEATURE_APPX
-
// *** ILGenerator api ***
public override LocalBuilder DeclareLocal(Type localType, bool pinned)
@@ -66,12 +54,7 @@ namespace System.Reflection.Emit
RuntimeType rtType = localType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
-
-#if FEATURE_APPX
- if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
-#endif
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType);
localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder);
// add the localType to local signature
@@ -98,7 +81,7 @@ namespace System.Reflection.Emit
{
RuntimeMethodInfo rtMeth = meth as RuntimeMethodInfo;
if (rtMeth == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(meth));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(meth));
RuntimeType declaringType = rtMeth.GetRuntimeType();
if (declaringType != null && (declaringType.IsGenericType || declaringType.IsArray))
@@ -111,7 +94,7 @@ namespace System.Reflection.Emit
// rule out not allowed operations on DynamicMethods
if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOpCodeOnDynamicMethod"));
+ throw new ArgumentException(SR.Argument_InvalidOpCodeOnDynamicMethod);
}
token = GetTokenFor(dynMeth);
}
@@ -149,7 +132,7 @@ namespace System.Reflection.Emit
RuntimeConstructorInfo rtConstructor = con as RuntimeConstructorInfo;
if (rtConstructor == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(con));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(con));
RuntimeType declaringType = rtConstructor.GetRuntimeType();
int token;
@@ -178,7 +161,7 @@ namespace System.Reflection.Emit
RuntimeType rtType = type as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType);
int token = GetTokenFor(rtType);
EnsureCapacity(7);
@@ -194,7 +177,7 @@ namespace System.Reflection.Emit
RuntimeFieldInfo runtimeField = field as RuntimeFieldInfo;
if (runtimeField == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(field));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(field));
int token;
if (field.DeclaringType == null)
@@ -235,7 +218,7 @@ namespace System.Reflection.Emit
if (optionalParameterTypes != null)
if ((callingConvention & CallingConventions.VarArgs) == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention);
sig = GetMemberRefSignature(callingConvention,
returnType,
@@ -271,13 +254,13 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(methodInfo));
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));
+ throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode));
if (methodInfo.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
+ throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(methodInfo));
if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(methodInfo));
+ throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(methodInfo));
Contract.EndContractBlock();
int tk;
@@ -345,7 +328,7 @@ namespace System.Reflection.Emit
// Begins an exception filter block. Emits a branch instruction to the end of the current exception block.
if (CurrExcStackCount == 0)
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
@@ -359,7 +342,7 @@ namespace System.Reflection.Emit
public override void BeginCatchBlock(Type exceptionType)
{
if (CurrExcStackCount == 0)
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
Contract.EndContractBlock();
__ExceptionInfo current = CurrExcStack[CurrExcStackCount - 1];
@@ -370,7 +353,7 @@ namespace System.Reflection.Emit
{
if (exceptionType != null)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
+ throw new ArgumentException(SR.Argument_ShouldNotSpecifyExceptionType);
}
this.Emit(OpCodes.Endfilter);
@@ -384,7 +367,7 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(exceptionType));
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType);
Label endLabel = current.GetEndLabel();
this.Emit(OpCodes.Leave, endLabel);
@@ -409,7 +392,7 @@ namespace System.Reflection.Emit
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
public override void UsingNamespace(String ns)
{
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
+ throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod);
}
[SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems.
@@ -419,17 +402,17 @@ namespace System.Reflection.Emit
int endLine,
int endColumn)
{
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
+ throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod);
}
public override void BeginScope()
{
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
+ throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod);
}
public override void EndScope()
{
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"));
+ throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod);
}
private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes)
@@ -437,13 +420,13 @@ namespace System.Reflection.Emit
Type[] parameterTypes;
if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention);
RuntimeMethodInfo rtMeth = methodInfo as RuntimeMethodInfo;
DynamicMethod dm = methodInfo as DynamicMethod;
if (rtMeth == null && dm == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), nameof(methodInfo));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, nameof(methodInfo));
ParameterInfo[] paramInfo = methodInfo.GetParametersNoCopy();
if (paramInfo != null && paramInfo.Length != 0)
@@ -498,94 +481,36 @@ namespace System.Reflection.Emit
#region GetTokenFor helpers
private int GetTokenFor(RuntimeType rtType)
{
-#if FEATURE_APPX
- if (ProfileAPICheck && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
-#endif
-
return m_scope.GetTokenFor(rtType.TypeHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField)
{
-#if FEATURE_APPX
- if (ProfileAPICheck)
- {
- RtFieldInfo rtField = runtimeField as RtFieldInfo;
- if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
- }
-#endif
-
return m_scope.GetTokenFor(runtimeField.FieldHandle);
}
private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType)
{
-#if FEATURE_APPX
- if (ProfileAPICheck)
- {
- RtFieldInfo rtField = runtimeField as RtFieldInfo;
- if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
-
- if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
- }
-#endif
-
return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth)
{
-#if FEATURE_APPX
- if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
-#endif
-
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType)
{
-#if FEATURE_APPX
- if (ProfileAPICheck)
- {
- if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
-
- if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
- }
-#endif
-
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth)
{
-#if FEATURE_APPX
- if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
-#endif
-
return m_scope.GetTokenFor(rtMeth.MethodHandle);
}
private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType)
{
-#if FEATURE_APPX
- if (ProfileAPICheck)
- {
- if ((rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
-
- if ((rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
- }
-#endif
-
return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle);
}
@@ -596,10 +521,6 @@ namespace System.Reflection.Emit
private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig)
{
-#if FEATURE_APPX
- if (ProfileAPICheck && (rtMeth.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtMeth.FullName));
-#endif
VarArgMethod varArgMeth = new VarArgMethod(rtMeth, sig);
return m_scope.GetTokenFor(varArgMeth);
}
@@ -962,8 +883,8 @@ namespace System.Reflection.Emit
public DynamicMethod DynamicMethod { get { return m_method; } }
internal DynamicScope DynamicScope { get { return m_scope; } }
-#endregion
-#region Public Scope Methods
+ #endregion
+ #region Public Scope Methods
#endregion
}
@@ -1032,7 +953,7 @@ namespace System.Reflection.Emit
Type t = m.DeclaringType.GetGenericTypeDefinition();
throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGenericLcg"), m, t));
+ CultureInfo.CurrentCulture, SR.Argument_MethodDeclaringTypeGenericLcg, m, t));
}
}
@@ -1119,5 +1040,4 @@ namespace System.Reflection.Emit
m_signature = signature;
}
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
index f1d99d3c2c..2d2d3097a1 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
@@ -42,13 +42,6 @@ namespace System.Reflection.Emit
// assigned by the DynamicResolver ctor
internal DynamicResolver m_resolver;
- // Always false unless we are in an immersive (non dev mode) process.
-#if FEATURE_APPX
- private bool m_profileAPICheck;
-
- private RuntimeAssembly m_creatorAssembly;
-#endif
-
internal bool m_restrictedSkipVisibility;
// The context when the method was created. We use this to do the RestrictedMemberAccess checks.
// These checks are done when the method is compiled. This can happen at an arbitrary time,
@@ -58,40 +51,33 @@ namespace System.Reflection.Emit
// it is ready for use since there is not API which indictates that IL generation has completed.
private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule;
private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object();
-
+
//
// class initialization (ctor and init)
//
private DynamicMethod() { }
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- Init(name,
- MethodAttributes.Public | MethodAttributes.Static,
- CallingConventions.Standard,
- returnType,
+ Init(name,
+ MethodAttributes.Public | MethodAttributes.Static,
+ CallingConventions.Standard,
+ returnType,
parameterTypes,
null, // owner
null, // m
false, // skipVisibility
- true,
- ref stackMark); // transparentMethod
+ true);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
public DynamicMethod(string name,
Type returnType,
Type[] parameterTypes,
bool restrictedSkipVisibility)
{
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@@ -100,17 +86,17 @@ namespace System.Reflection.Emit
null, // owner
null, // m
restrictedSkipVisibility,
- true,
- ref stackMark); // transparentMethod
+ true);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Module m) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PerformSecurityCheck(m, ref stackMark, false);
+ public DynamicMethod(string name,
+ Type returnType,
+ Type[] parameterTypes,
+ Module m)
+ {
+ if (m == null)
+ throw new ArgumentNullException(nameof(m));
+
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@@ -119,18 +105,18 @@ namespace System.Reflection.Emit
null, // owner
m, // m
false, // skipVisibility
- false,
- ref stackMark); // transparentMethod
+ false);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Module m,
- bool skipVisibility) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PerformSecurityCheck(m, ref stackMark, skipVisibility);
+ public DynamicMethod(string name,
+ Type returnType,
+ Type[] parameterTypes,
+ Module m,
+ bool skipVisibility)
+ {
+ if (m == null)
+ throw new ArgumentNullException(nameof(m));
+
Init(name,
MethodAttributes.Public | MethodAttributes.Static,
CallingConventions.Standard,
@@ -139,20 +125,20 @@ namespace System.Reflection.Emit
null, // owner
m, // m
skipVisibility,
- false,
- ref stackMark); // transparentMethod
+ false);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public DynamicMethod(string name,
- MethodAttributes attributes,
- CallingConventions callingConvention,
- Type returnType,
- Type[] parameterTypes,
- Module m,
- bool skipVisibility) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PerformSecurityCheck(m, ref stackMark, skipVisibility);
+ public DynamicMethod(string name,
+ MethodAttributes attributes,
+ CallingConventions callingConvention,
+ Type returnType,
+ Type[] parameterTypes,
+ Module m,
+ bool skipVisibility)
+ {
+ if (m == null)
+ throw new ArgumentNullException(nameof(m));
+
Init(name,
attributes,
callingConvention,
@@ -161,93 +147,93 @@ namespace System.Reflection.Emit
null, // owner
m, // m
skipVisibility,
- false,
- ref stackMark); // transparentMethod
+ false);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Type owner) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PerformSecurityCheck(owner, ref stackMark, false);
- Init(name,
- MethodAttributes.Public | MethodAttributes.Static,
- CallingConventions.Standard,
- returnType,
+ public DynamicMethod(string name,
+ Type returnType,
+ Type[] parameterTypes,
+ Type owner)
+ {
+ if (owner == null)
+ throw new ArgumentNullException(nameof(owner));
+
+ Init(name,
+ MethodAttributes.Public | MethodAttributes.Static,
+ CallingConventions.Standard,
+ returnType,
parameterTypes,
owner, // owner
null, // m
false, // skipVisibility
- false,
- ref stackMark); // transparentMethod
+ false);
}
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public DynamicMethod(string name,
- Type returnType,
- Type[] parameterTypes,
- Type owner,
- bool skipVisibility) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PerformSecurityCheck(owner, ref stackMark, skipVisibility);
- Init(name,
- MethodAttributes.Public | MethodAttributes.Static,
- CallingConventions.Standard,
- returnType,
- parameterTypes,
+
+ public DynamicMethod(string name,
+ Type returnType,
+ Type[] parameterTypes,
+ Type owner,
+ bool skipVisibility)
+ {
+ if (owner == null)
+ throw new ArgumentNullException(nameof(owner));
+
+ Init(name,
+ MethodAttributes.Public | MethodAttributes.Static,
+ CallingConventions.Standard,
+ returnType,
+ parameterTypes,
owner, // owner
null, // m
skipVisibility,
- false,
- ref stackMark); // transparentMethod
+ false);
}
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public DynamicMethod(string name,
- MethodAttributes attributes,
- CallingConventions callingConvention,
- Type returnType,
- Type[] parameterTypes,
- Type owner,
- bool skipVisibility) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- PerformSecurityCheck(owner, ref stackMark, skipVisibility);
- Init(name,
- attributes,
- callingConvention,
- returnType,
- parameterTypes,
+
+ public DynamicMethod(string name,
+ MethodAttributes attributes,
+ CallingConventions callingConvention,
+ Type returnType,
+ Type[] parameterTypes,
+ Type owner,
+ bool skipVisibility)
+ {
+ if (owner == null)
+ throw new ArgumentNullException(nameof(owner));
+
+ Init(name,
+ attributes,
+ callingConvention,
+ returnType,
+ parameterTypes,
owner, // owner
null, // m
- skipVisibility,
- false,
- ref stackMark); // transparentMethod
+ skipVisibility,
+ false);
}
// helpers for intialization
- static private void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention) {
+ static private void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention)
+ {
// only static public for method attributes
if ((attributes & ~MethodAttributes.MemberAccessMask) != MethodAttributes.Static)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
+ throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags);
if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
+ throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags);
Contract.EndContractBlock();
// only standard or varargs supported
if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
-
+ throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags);
+
// vararg is not supported at the moment
if (callingConvention == CallingConventions.VarArgs)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicMethodFlags"));
+ throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags);
}
// We create a transparent assembly to host DynamicMethods. Since the assembly does not have any
// non-public fields (or any fields at all), it is a safe anonymous assembly to host DynamicMethods
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
private static RuntimeModule GetDynamicMethodsModule()
{
if (s_anonymouslyHostedDynamicMethodsModule != null)
@@ -259,7 +245,7 @@ namespace System.Reflection.Emit
return s_anonymouslyHostedDynamicMethodsModule;
ConstructorInfo transparencyCtor = typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes);
- CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, EmptyArray<Object>.Value);
+ CustomAttributeBuilder transparencyAttribute = new CustomAttributeBuilder(transparencyCtor, Array.Empty<Object>());
List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
assemblyAttributes.Add(transparencyAttribute);
@@ -283,38 +269,40 @@ namespace System.Reflection.Emit
return s_anonymouslyHostedDynamicMethodsModule;
}
- private unsafe void Init(String name,
- MethodAttributes attributes,
- CallingConventions callingConvention,
- Type returnType,
- Type[] signature,
- Type owner,
- Module m,
+ private unsafe void Init(String name,
+ MethodAttributes attributes,
+ CallingConventions callingConvention,
+ Type returnType,
+ Type[] signature,
+ Type owner,
+ Module m,
bool skipVisibility,
- bool transparentMethod,
- ref StackCrawlMark stackMark)
+ bool transparentMethod)
{
DynamicMethod.CheckConsistency(attributes, callingConvention);
// check and store the signature
- if (signature != null) {
+ if (signature != null)
+ {
m_parameterTypes = new RuntimeType[signature.Length];
- for (int i = 0; i < signature.Length; i++) {
- if (signature[i] == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature"));
+ for (int i = 0; i < signature.Length; i++)
+ {
+ if (signature[i] == null)
+ throw new ArgumentException(SR.Arg_InvalidTypeInSignature);
m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType;
- if ( m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void) )
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidTypeInSignature"));
+ if (m_parameterTypes[i] == null || !(m_parameterTypes[i] is RuntimeType) || m_parameterTypes[i] == (RuntimeType)typeof(void))
+ throw new ArgumentException(SR.Arg_InvalidTypeInSignature);
}
}
- else {
+ else
+ {
m_parameterTypes = Array.Empty<RuntimeType>();
}
-
+
// check and store the return value
m_returnType = (returnType == null) ? (RuntimeType)typeof(void) : returnType.UnderlyingSystemType as RuntimeType;
- if ( (m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef )
- throw new NotSupportedException(Environment.GetResourceString("Arg_InvalidTypeInRetType"));
+ if ((m_returnType == null) || !(m_returnType is RuntimeType) || m_returnType.IsByRef)
+ throw new NotSupportedException(SR.Arg_InvalidTypeInRetType);
if (transparentMethod)
{
@@ -324,11 +312,10 @@ namespace System.Reflection.Emit
{
m_restrictedSkipVisibility = true;
}
-
}
else
{
- Debug.Assert(m != null || owner != null, "PerformSecurityCheck should ensure that either m or owner is set");
+ Debug.Assert(m != null || owner != null, "Constructor should ensure that either m or owner is set");
Debug.Assert(m == null || !m.Equals(s_anonymouslyHostedDynamicMethodsModule), "The user cannot explicitly use this assembly");
Debug.Assert(m == null || owner == null, "m and owner cannot both be set");
@@ -344,7 +331,7 @@ namespace System.Reflection.Emit
{
if (rtOwner.HasElementType || rtOwner.ContainsGenericParameters
|| rtOwner.IsGenericParameter || rtOwner.IsInterface)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeForDynamicMethod"));
+ throw new ArgumentException(SR.Argument_InvalidTypeForDynamicMethod);
m_typeOwner = rtOwner;
m_module = rtOwner.GetRuntimeModule();
@@ -359,41 +346,18 @@ namespace System.Reflection.Emit
m_fInitLocals = true;
m_methodHandle = null;
- if (name == null)
+ if (name == null)
throw new ArgumentNullException(nameof(name));
-#if FEATURE_APPX
- if (AppDomain.ProfileAPICheck)
- {
- if (m_creatorAssembly == null)
- m_creatorAssembly = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
-
- if (m_creatorAssembly != null && !m_creatorAssembly.IsFrameworkAssembly())
- m_profileAPICheck = true;
- }
-#endif // FEATURE_APPX
-
m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention);
}
- private void PerformSecurityCheck(Module m, ref StackCrawlMark stackMark, bool skipVisibility)
- {
- if (m == null)
- throw new ArgumentNullException(nameof(m));
- Contract.EndContractBlock();
- }
-
- private void PerformSecurityCheck(Type owner, ref StackCrawlMark stackMark, bool skipVisibility)
- {
- if (owner == null)
- throw new ArgumentNullException(nameof(owner));
- }
-
//
// Delegate and method creation
//
- public sealed override Delegate CreateDelegate(Type delegateType) {
+ public sealed override Delegate CreateDelegate(Type delegateType)
+ {
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation.
@@ -407,7 +371,8 @@ namespace System.Reflection.Emit
return d;
}
- public sealed override Delegate CreateDelegate(Type delegateType, Object target) {
+ public sealed override Delegate CreateDelegate(Type delegateType, Object target)
+ {
if (m_restrictedSkipVisibility)
{
// Compile the method since accessibility checks are done as part of compilation
@@ -421,33 +386,22 @@ namespace System.Reflection.Emit
return d;
}
-#if FEATURE_APPX
- internal bool ProfileAPICheck
+ // This is guaranteed to return a valid handle
+ internal unsafe RuntimeMethodHandle GetMethodDescriptor()
{
- get
- {
- return m_profileAPICheck;
- }
-
- [FriendAccessAllowed]
- set
+ if (m_methodHandle == null)
{
- m_profileAPICheck = value;
- }
- }
-#endif
-
- // This is guaranteed to return a valid handle
- internal unsafe RuntimeMethodHandle GetMethodDescriptor() {
- if (m_methodHandle == null) {
- lock (this) {
- if (m_methodHandle == null) {
+ lock (this)
+ {
+ if (m_methodHandle == null)
+ {
if (m_DynamicILInfo != null)
m_DynamicILInfo.GetCallableMethod(m_module, this);
- else {
+ else
+ {
if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", Name));
-
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadEmptyMethodBody, Name));
+
m_ilGenerator.GetCallableMethod(m_module, this);
}
}
@@ -471,7 +425,7 @@ namespace System.Reflection.Emit
public override Module Module { get { return m_dynMethod.Module; } }
// we cannot return a MethodHandle because we cannot track it via GC so this method is off limits
- public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); } }
+ public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInDynamicMethod); } }
public override MethodAttributes Attributes { get { return m_dynMethod.Attributes; } }
@@ -508,9 +462,10 @@ namespace System.Reflection.Emit
get { return false; }
}
- public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
+ public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
+ {
if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CallToVarArg"));
+ throw new NotSupportedException(SR.NotSupported_CallToVarArg);
Contract.EndContractBlock();
//
@@ -531,7 +486,7 @@ namespace System.Reflection.Emit
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
- throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
+ throw new TargetParameterCountException(SR.Arg_ParmCnt);
// if we are here we passed all the previous checks. Time to look at the arguments
Object retValue = null;
@@ -554,7 +509,7 @@ namespace System.Reflection.Emit
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
- return m_dynMethod.GetCustomAttributes(attributeType, inherit);
+ return m_dynMethod.GetCustomAttributes(attributeType, inherit);
}
public override Object[] GetCustomAttributes(bool inherit) { return m_dynMethod.GetCustomAttributes(inherit); }
@@ -571,24 +526,27 @@ namespace System.Reflection.Emit
// DynamicMethod specific methods
//
- public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String parameterName) {
+ public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String parameterName)
+ {
if (position < 0 || position > m_parameterTypes.Length)
- throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
+ throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
position--; // it's 1 based. 0 is the return value
-
- if (position >= 0) {
- ParameterInfo[] parameters = m_dynMethod.LoadParameters();
+
+ if (position >= 0)
+ {
+ RuntimeParameterInfo[] parameters = m_dynMethod.LoadParameters();
parameters[position].SetName(parameterName);
parameters[position].SetAttributes(attributes);
}
return null;
}
- public ILGenerator GetILGenerator() {
+ public ILGenerator GetILGenerator()
+ {
return GetILGenerator(64);
}
- public ILGenerator GetILGenerator(int streamSize)
+ public ILGenerator GetILGenerator(int streamSize)
{
if (m_ilGenerator == null)
{
@@ -599,16 +557,18 @@ namespace System.Reflection.Emit
return m_ilGenerator;
}
- public bool InitLocals {
- get {return m_fInitLocals;}
- set {m_fInitLocals = value;}
+ public bool InitLocals
+ {
+ get { return m_fInitLocals; }
+ set { m_fInitLocals = value; }
}
//
// Internal API
//
-
- internal MethodInfo GetMethodInfo() {
+
+ internal MethodInfo GetMethodInfo()
+ {
return m_dynMethod;
}
@@ -620,109 +580,125 @@ 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 class RTDynamicMethod : MethodInfo
+ {
internal DynamicMethod m_owner;
- ParameterInfo[] m_parameters;
- String m_name;
- MethodAttributes m_attributes;
- CallingConventions m_callingConvention;
+ private RuntimeParameterInfo[] m_parameters;
+ private String m_name;
+ private MethodAttributes m_attributes;
+ private CallingConventions m_callingConvention;
//
// ctors
//
- private RTDynamicMethod() {}
+ private RTDynamicMethod() { }
- internal RTDynamicMethod(DynamicMethod owner, String name, MethodAttributes attributes, CallingConventions callingConvention) {
+ internal RTDynamicMethod(DynamicMethod owner, String name, MethodAttributes attributes, CallingConventions callingConvention)
+ {
m_owner = owner;
m_name = name;
m_attributes = attributes;
m_callingConvention = callingConvention;
}
-
+
//
// MethodInfo api
//
- public override String ToString() {
+ public override String ToString()
+ {
return ReturnType.FormatTypeName() + " " + FormatNameAndSig();
}
- public override String Name {
+ public override String Name
+ {
get { return m_name; }
}
- public override Type DeclaringType {
+ public override Type DeclaringType
+ {
get { return null; }
}
- public override Type ReflectedType {
+ public override Type ReflectedType
+ {
get { return null; }
}
- public override Module Module {
+ public override Module Module
+ {
get { return m_owner.m_module; }
}
- public override RuntimeMethodHandle MethodHandle {
- get { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInDynamicMethod")); }
+ public override RuntimeMethodHandle MethodHandle
+ {
+ get { throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInDynamicMethod); }
}
- public override MethodAttributes Attributes {
+ public override MethodAttributes Attributes
+ {
get { return m_attributes; }
- }
+ }
- public override CallingConventions CallingConvention {
+ public override CallingConventions CallingConvention
+ {
get { return m_callingConvention; }
}
-
- public override MethodInfo GetBaseDefinition() {
+
+ public override MethodInfo GetBaseDefinition()
+ {
return this;
}
-
+
[Pure]
- public override ParameterInfo[] GetParameters() {
+ public override ParameterInfo[] GetParameters()
+ {
ParameterInfo[] privateParameters = LoadParameters();
ParameterInfo[] parameters = new ParameterInfo[privateParameters.Length];
Array.Copy(privateParameters, 0, parameters, 0, privateParameters.Length);
return parameters;
}
-
- public override MethodImplAttributes GetMethodImplementationFlags() {
+
+ public override MethodImplAttributes GetMethodImplementationFlags()
+ {
return MethodImplAttributes.IL | MethodImplAttributes.NoInlining;
}
- public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) {
+ public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
+ {
// We want the creator of the DynamicMethod to control who has access to the
// DynamicMethod (just like we do for delegates). However, a user can get to
// the corresponding RTDynamicMethod using Exception.TargetSite, StackFrame.GetMethod, etc.
// If we allowed use of RTDynamicMethod, the creator of the DynamicMethod would
// not be able to bound access to the DynamicMethod. Hence, we do not allow
// direct use of RTDynamicMethod.
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"), "this");
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "this");
}
- public override Object[] GetCustomAttributes(Type attributeType, bool inherit) {
+ public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
+ {
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
- if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
+ if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
else
- return EmptyArray<Object>.Value;
+ return Array.Empty<Object>();
}
- public override Object[] GetCustomAttributes(bool inherit) {
+ public override Object[] GetCustomAttributes(bool inherit)
+ {
// support for MethodImplAttribute PCA
return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
}
-
- public override bool IsDefined(Type attributeType, bool inherit) {
+
+ public override bool IsDefined(Type attributeType, bool inherit)
+ {
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
- if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
+ if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
return true;
else
return false;
@@ -751,11 +727,13 @@ namespace System.Reflection.Emit
}
}
- public override ParameterInfo ReturnParameter {
- get { return null; }
+ public override ParameterInfo ReturnParameter
+ {
+ get { return null; }
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes {
+ public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ {
get { return GetEmptyCAHolder(); }
}
@@ -763,45 +741,49 @@ namespace System.Reflection.Emit
// private implementation
//
- internal ParameterInfo[] LoadParameters() {
- if (m_parameters == null) {
+ internal RuntimeParameterInfo[] LoadParameters()
+ {
+ if (m_parameters == null)
+ {
Type[] parameterTypes = m_owner.m_parameterTypes;
- ParameterInfo[] parameters = new ParameterInfo[parameterTypes.Length];
- for (int i = 0; i < parameterTypes.Length; i++)
+ RuntimeParameterInfo[] parameters = new RuntimeParameterInfo[parameterTypes.Length];
+ for (int i = 0; i < parameterTypes.Length; i++)
parameters[i] = new RuntimeParameterInfo(this, null, parameterTypes[i], i);
- if (m_parameters == null)
+ if (m_parameters == null)
// should we interlockexchange?
m_parameters = parameters;
}
return m_parameters;
}
-
+
// private implementation of CA for the return type
- private ICustomAttributeProvider GetEmptyCAHolder() {
+ private ICustomAttributeProvider GetEmptyCAHolder()
+ {
return new EmptyCAHolder();
}
///////////////////////////////////////////////////
// EmptyCAHolder
- private class EmptyCAHolder : ICustomAttributeProvider {
- internal EmptyCAHolder() {}
+ private class EmptyCAHolder : ICustomAttributeProvider
+ {
+ internal EmptyCAHolder() { }
- Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit) {
- return EmptyArray<Object>.Value;
+ Object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit)
+ {
+ return Array.Empty<Object>();
}
- Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) {
- return EmptyArray<Object>.Value;
+ Object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit)
+ {
+ return Array.Empty<Object>();
}
- bool ICustomAttributeProvider.IsDefined (Type attributeType, bool inherit) {
+ bool ICustomAttributeProvider.IsDefined(Type attributeType, bool inherit)
+ {
return false;
}
}
-
}
-
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
index 96564d537b..55aa5c5a8f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EnumBuilder.cs
@@ -12,8 +12,9 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
+
+namespace System.Reflection.Emit
+{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
@@ -23,21 +24,22 @@ namespace System.Reflection.Emit {
sealed public class EnumBuilder : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ {
+ if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
// Define literal for enum
public FieldBuilder DefineLiteral(String literalName, Object literalValue)
- {
- BCLDebug.Log("DYNIL","## DYNIL LOGGING: EnumBuilder.DefineLiteral( " + literalName + " )");
+ {
+ BCLDebug.Log("DYNIL", "## DYNIL LOGGING: EnumBuilder.DefineLiteral( " + literalName + " )");
// Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
FieldBuilder fieldBuilder = m_typeBuilder.DefineField(
- literalName,
- this,
+ literalName,
+ this,
FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
fieldBuilder.SetConstant(literalValue);
return fieldBuilder;
@@ -50,143 +52,156 @@ namespace System.Reflection.Emit {
}
// CreateType cause EnumBuilder to be baked.
- public Type CreateType()
+ public Type CreateType()
{
- BCLDebug.Log("DYNIL","## DYNIL LOGGING: EnumBuilder.CreateType() ");
+ BCLDebug.Log("DYNIL", "## DYNIL LOGGING: EnumBuilder.CreateType() ");
return m_typeBuilder.CreateType();
}
-
+
// Get the internal metadata token for this class.
- public TypeToken TypeToken {
- get {return m_typeBuilder.TypeToken; }
+ public TypeToken TypeToken
+ {
+ get { return m_typeBuilder.TypeToken; }
}
-
+
// return the underlying field for the enum
- public FieldBuilder UnderlyingField {
- get {return m_underlyingField; }
+ public FieldBuilder UnderlyingField
+ {
+ get { return m_underlyingField; }
}
- public override String Name {
+ public override String Name
+ {
get { return m_typeBuilder.Name; }
}
-
+
/****************************************************
*
* abstract methods defined in the base class
*
*/
- public override Guid GUID {
- get {
+ public override Guid GUID
+ {
+ get
+ {
return m_typeBuilder.GUID;
}
}
public override Object InvokeMember(
- String name,
+ String name,
BindingFlags invokeAttr,
- Binder binder,
- Object target,
- Object[] args,
- ParameterModifier[] modifiers,
+ Binder binder,
+ Object target,
+ Object[] args,
+ ParameterModifier[] modifiers,
CultureInfo culture,
- String[] namedParameters)
+ String[] namedParameters)
{
return m_typeBuilder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
-
- public override Module Module {
- get {return m_typeBuilder.Module;}
+
+ public override Module Module
+ {
+ get { return m_typeBuilder.Module; }
}
-
- public override Assembly Assembly {
- get {return m_typeBuilder.Assembly;}
+
+ public override Assembly Assembly
+ {
+ get { return m_typeBuilder.Assembly; }
}
- public override RuntimeTypeHandle TypeHandle {
- get {return m_typeBuilder.TypeHandle;}
+ public override RuntimeTypeHandle TypeHandle
+ {
+ get { return m_typeBuilder.TypeHandle; }
}
-
- public override String FullName {
- get { return m_typeBuilder.FullName;}
+
+ public override String FullName
+ {
+ get { return m_typeBuilder.FullName; }
}
-
- public override String AssemblyQualifiedName {
- get {
+
+ public override String AssemblyQualifiedName
+ {
+ get
+ {
return m_typeBuilder.AssemblyQualifiedName;
}
}
-
- public override String Namespace {
- get { return m_typeBuilder.Namespace;}
+
+ public override String Namespace
+ {
+ get { return m_typeBuilder.Namespace; }
}
-
- public override Type BaseType {
- get{return m_typeBuilder.BaseType;}
+
+ public override Type BaseType
+ {
+ get { return m_typeBuilder.BaseType; }
}
-
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
+
+ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
return m_typeBuilder.GetConstructor(bindingAttr, binder, callConvention,
types, modifiers);
}
-
+
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return m_typeBuilder.GetConstructors(bindingAttr);
}
-
- protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
+
+ protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (types == null)
return m_typeBuilder.GetMethod(name, bindingAttr);
else
return m_typeBuilder.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
}
-
+
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return m_typeBuilder.GetMethods(bindingAttr);
}
-
+
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetField(name, bindingAttr);
}
-
+
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return m_typeBuilder.GetFields(bindingAttr);
}
-
+
public override Type GetInterface(String name, bool ignoreCase)
{
return m_typeBuilder.GetInterface(name, ignoreCase);
}
-
+
public override Type[] GetInterfaces()
{
return m_typeBuilder.GetInterfaces();
}
-
+
public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
return m_typeBuilder.GetEvent(name, bindingAttr);
}
-
+
public override EventInfo[] GetEvents()
{
return m_typeBuilder.GetEvents();
}
-
- protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
+
+ protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
-
+
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return m_typeBuilder.GetProperties(bindingAttr);
@@ -199,14 +214,14 @@ namespace System.Reflection.Emit {
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
- return m_typeBuilder.GetNestedType(name,bindingAttr);
+ return m_typeBuilder.GetNestedType(name, bindingAttr);
}
-
- public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
+
+ public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
return m_typeBuilder.GetMember(name, type, bindingAttr);
}
-
+
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return m_typeBuilder.GetMembers(bindingAttr);
@@ -221,12 +236,14 @@ namespace System.Reflection.Emit {
{
return m_typeBuilder.GetEvents(bindingAttr);
}
-
+
protected override TypeAttributes GetAttributeFlagsImpl()
{
return m_typeBuilder.Attributes;
}
-
+
+ public override bool IsSZArray => false;
+
protected override bool IsArrayImpl()
{
return false;
@@ -236,7 +253,7 @@ namespace System.Reflection.Emit {
return false;
}
- protected override bool IsValueTypeImpl()
+ protected override bool IsValueTypeImpl()
{
return true;
}
@@ -250,7 +267,7 @@ namespace System.Reflection.Emit {
{
return false;
}
-
+
protected override bool IsCOMObjectImpl()
{
return false;
@@ -290,7 +307,7 @@ namespace System.Reflection.Emit {
return GetEnumUnderlyingType();
}
}
-
+
//ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
@@ -303,64 +320,66 @@ namespace System.Reflection.Emit {
return m_typeBuilder.GetCustomAttributes(attributeType, inherit);
}
- // Use this function if client decides to form the custom attribute blob themselves
+ // Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
- m_typeBuilder.SetCustomAttribute(con, binaryAttribute);
+ m_typeBuilder.SetCustomAttribute(con, binaryAttribute);
}
- // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
+ // Use this function if client wishes to build CustomAttribute using CustomAttributeBuilder
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_typeBuilder.SetCustomAttribute(customBuilder);
}
// Return the class that declared this Field.
- public override Type DeclaringType {
- get {return m_typeBuilder.DeclaringType;}
+ public override Type DeclaringType
+ {
+ get { return m_typeBuilder.DeclaringType; }
}
// Return the class that was used to obtain this field.
-
- public override Type ReflectedType {
- get {return m_typeBuilder.ReflectedType;}
+
+ public override Type ReflectedType
+ {
+ get { return m_typeBuilder.ReflectedType; }
}
- // Returns true if one or more instance of attributeType is defined on this member.
- public override bool IsDefined (Type attributeType, bool inherit)
+ // Returns true if one or more instance of attributeType is defined on this member.
+ public override bool IsDefined(Type attributeType, bool inherit)
{
return m_typeBuilder.IsDefined(attributeType, inherit);
}
-
+
/*****************************************************
*
* private/protected functions
*
*/
-
+
//*******************************
// Make a private constructor so these cannot be constructed externally.
//*******************************
- private EnumBuilder() {}
-
- public override Type MakePointerType()
- {
- return SymbolType.FormCompoundType("*", this, 0);
+ private EnumBuilder() { }
+
+ public override Type MakePointerType()
+ {
+ return SymbolType.FormCompoundType("*", this, 0);
}
- public override Type MakeByRefType()
+ public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
- public override Type MakeArrayType()
+ public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
- public override Type MakeArrayType(int rank)
+ public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
@@ -370,9 +389,9 @@ namespace System.Reflection.Emit {
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -380,18 +399,18 @@ namespace System.Reflection.Emit {
return SymbolType.FormCompoundType(s, this, 0);
}
-
+
// Constructs a EnumBuilder.
// EnumBuilder can only be a top-level (not nested) enum type.
internal EnumBuilder(
- String name, // name of type
- Type underlyingType, // underlying type for an Enum
+ String name, // name of type
+ Type underlyingType, // underlying type for an Enum
TypeAttributes visibility, // any bits on TypeAttributes.VisibilityMask)
- ModuleBuilder module) // module containing this type
+ ModuleBuilder module) // module containing this type
{
// Client should not set any bits other than the visibility bits.
if ((visibility & ~TypeAttributes.VisibilityMask) != 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_ShouldOnlySetVisibilityFlags"), nameof(name));
+ throw new ArgumentException(SR.Argument_ShouldOnlySetVisibilityFlags, nameof(name));
m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(System.Enum), null, module, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize, null);
// Define the underlying field for the enum. It will be a non-static, private field with special name bit set.
@@ -403,7 +422,7 @@ namespace System.Reflection.Emit {
* private data members
*
*/
- internal TypeBuilder m_typeBuilder;
- private FieldBuilder m_underlyingField;
+ internal TypeBuilder m_typeBuilder;
+ private FieldBuilder m_underlyingField;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
index 34c76b93d1..ef60d05172 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EventBuilder.cs
@@ -12,40 +12,40 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
-
+
+using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection.Emit
+{
//
// A EventBuilder is always associated with a TypeBuilder. The TypeBuilder.DefineEvent
// method will return a new EventBuilder to a client.
//
public sealed class EventBuilder
- {
-
+ {
// Make a private constructor so these cannot be constructed externally.
- private EventBuilder() {}
-
+ private EventBuilder() { }
+
// Constructs a EventBuilder.
//
internal EventBuilder(
- ModuleBuilder mod, // the module containing this EventBuilder
- String name, // Event name
+ ModuleBuilder mod, // the module containing this EventBuilder
+ String name, // Event name
EventAttributes attr, // event attribute such as Public, Private, and Protected defined above
- //int eventType, // event type
- TypeBuilder type, // containing type
- EventToken evToken)
- {
+ //int eventType, // event type
+ TypeBuilder type, // containing type
+ EventToken evToken)
+ {
m_name = name;
m_module = mod;
m_attributes = attr;
m_evToken = evToken;
m_type = type;
}
-
+
// Return the Token for this event within the TypeBuilder that the
// event is defined within.
public EventToken GetEventToken()
@@ -73,22 +73,22 @@ namespace System.Reflection.Emit {
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.AddOn);
}
-
+
public void SetRemoveOnMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.RemoveOn);
}
-
+
public void SetRaiseMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Fire);
}
-
+
public void AddOtherMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
}
-
+
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
@@ -121,10 +121,10 @@ namespace System.Reflection.Emit {
}
// These are package private so that TypeBuilder can access them.
- private String m_name; // The name of the event
- private EventToken m_evToken; // The token of this event
- private ModuleBuilder m_module;
- private EventAttributes m_attributes;
- private TypeBuilder m_type;
+ private String m_name; // The name of the event
+ private EventToken m_evToken; // The token of this event
+ private ModuleBuilder m_module;
+ private EventAttributes m_attributes;
+ private TypeBuilder m_type;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
index 8ffdce9732..18ec630b5f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/EventToken.cs
@@ -12,30 +12,34 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
+
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
[Serializable]
public struct EventToken
{
public static readonly EventToken Empty = new EventToken();
-
+
internal int m_event;
- internal EventToken(int str) {
- m_event=str;
+ internal EventToken(int str)
+ {
+ m_event = str;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_event; }
}
-
+
public override int GetHashCode()
{
return m_event;
}
-
+
public override bool Equals(Object obj)
{
if (obj is EventToken)
@@ -43,25 +47,20 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(EventToken obj)
{
return obj.m_event == m_event;
}
-
+
public static bool operator ==(EventToken a, EventToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(EventToken a, EventToken b)
{
return !(a == b);
}
-
}
-
-
-
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
index 5953b67173..d0e9d3483c 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FieldBuilder.cs
@@ -4,14 +4,14 @@
//
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
using CultureInfo = System.Globalization.CultureInfo;
using System.Reflection;
using System.Diagnostics.Contracts;
-
+
public sealed class FieldBuilder : FieldInfo
{
#region Private Data Members
@@ -24,36 +24,36 @@ namespace System.Reflection.Emit
#endregion
#region Constructor
- internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type,
+ internal FieldBuilder(TypeBuilder typeBuilder, String fieldName, Type type,
Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes)
{
if (fieldName == null)
throw new ArgumentNullException(nameof(fieldName));
if (fieldName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fieldName));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(fieldName));
if (fieldName[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fieldName));
+ throw new ArgumentException(SR.Argument_IllegalName, nameof(fieldName));
if (type == null)
throw new ArgumentNullException(nameof(type));
if (type == typeof(void))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldType"));
+ throw new ArgumentException(SR.Argument_BadFieldType);
Contract.EndContractBlock();
m_fieldName = fieldName;
m_typeBuilder = typeBuilder;
m_fieldType = type;
m_Attributes = attributes & ~FieldAttributes.ReservedMask;
-
+
SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(m_typeBuilder.Module);
sigHelp.AddArgument(type, requiredCustomModifiers, optionalCustomModifiers);
int sigLength;
byte[] signature = sigHelp.InternalGetSignature(out sigLength);
-
+
m_fieldTok = TypeBuilder.DefineField(m_typeBuilder.GetModuleBuilder().GetNativeHandle(),
typeBuilder.TypeToken.Token, fieldName, signature, sigLength, m_Attributes);
@@ -74,20 +74,20 @@ namespace System.Reflection.Emit
{
get { return m_fieldTok; }
}
-
+
public override Module Module
{
get { return m_typeBuilder.Module; }
}
- public override String Name
+ public override String Name
{
- get {return m_fieldName; }
+ get { return m_fieldName; }
}
- public override Type DeclaringType
+ public override Type DeclaringType
{
- get
+ get
{
if (m_typeBuilder.m_isHiddenGlobalType == true)
return null;
@@ -95,10 +95,10 @@ namespace System.Reflection.Emit
return m_typeBuilder;
}
}
-
- public override Type ReflectedType
+
+ public override Type ReflectedType
{
- get
+ get
{
if (m_typeBuilder.m_isHiddenGlobalType == true)
return null;
@@ -110,35 +110,35 @@ namespace System.Reflection.Emit
#endregion
#region FieldInfo Overrides
- public override Type FieldType
+ public override Type FieldType
{
get { return m_fieldType; }
}
public override Object GetValue(Object obj)
- {
+ {
// NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
// Otherwise, it could cause the .cctor to be executed.
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override void SetValue(Object obj,Object val,BindingFlags invokeAttr,Binder binder,CultureInfo culture)
- {
+ public override void SetValue(Object obj, Object val, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ {
// NOTE!! If this is implemented, make sure that this throws
// a NotSupportedException for Save-only dynamic assemblies.
// Otherwise, it could cause the .cctor to be executed.
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override RuntimeFieldHandle FieldHandle
+ public override RuntimeFieldHandle FieldHandle
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
+ get { throw new NotSupportedException(SR.NotSupported_DynamicModule); }
}
- public override FieldAttributes Attributes
+ public override FieldAttributes Attributes
{
get { return m_Attributes; }
}
@@ -148,44 +148,41 @@ namespace System.Reflection.Emit
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
-
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
-
+
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
-
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
-
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
#endregion
#region Public Members
- public FieldToken GetToken()
+ public FieldToken GetToken()
{
return m_tkField;
}
- public void SetOffset(int iOffset)
+ public void SetOffset(int iOffset)
{
- m_typeBuilder.ThrowIfCreated();
-
+ m_typeBuilder.ThrowIfCreated();
+
TypeBuilder.SetFieldLayoutOffset(m_typeBuilder.GetModuleBuilder().GetNativeHandle(), GetToken().Token, iOffset);
}
- public void SetConstant(Object defaultValue)
+ public void SetConstant(Object defaultValue)
{
- m_typeBuilder.ThrowIfCreated();
-
+ m_typeBuilder.ThrowIfCreated();
+
TypeBuilder.SetConstantValue(m_typeBuilder.GetModuleBuilder(), GetToken().Token, m_fieldType, defaultValue);
}
-
+
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
index add428f96e..6c5d778d8f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FieldToken.cs
@@ -12,11 +12,12 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
// The FieldToken class is an opaque representation of the Token returned
// by the Metadata to represent the field. FieldTokens are generated by
// Module.GetFieldToken(). There are no meaningful accessors on this class,
@@ -28,7 +29,7 @@ namespace System.Reflection.Emit {
internal int m_fieldTok;
internal Object m_class;
-
+
// Creates an empty FieldToken. A publicly visible constructor so that
// it can be created on the stack.
//public FieldToken() {
@@ -38,23 +39,25 @@ namespace System.Reflection.Emit {
//}
// The actual constructor. Sets the field, attributes and class
// variables
-
- internal FieldToken (int field, Type fieldClass) {
- m_fieldTok=field;
+
+ internal FieldToken(int field, Type fieldClass)
+ {
+ m_fieldTok = field;
m_class = fieldClass;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_fieldTok; }
}
-
-
+
+
// Generates the hash code for this field.
public override int GetHashCode()
{
return (m_fieldTok);
}
-
+
// Returns true if obj is an instance of FieldToken and is
// equal to this instance.
public override bool Equals(Object obj)
@@ -69,16 +72,15 @@ namespace System.Reflection.Emit {
{
return obj.m_fieldTok == m_fieldTok && obj.m_class == m_class;
}
-
+
public static bool operator ==(FieldToken a, FieldToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(FieldToken a, FieldToken b)
{
return !(a == b);
}
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
index 9e528b2551..fb8564652f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/FlowControl.cs
@@ -11,23 +11,23 @@
** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND!
** See clrsrcincopcodegen.pl for more information.**
============================================================*/
-namespace System.Reflection.Emit {
using System;
-[Serializable]
-public enum FlowControl
+namespace System.Reflection.Emit
{
-
- Branch = 0,
- Break = 1,
- Call = 2,
- Cond_Branch = 3,
- Meta = 4,
- Next = 5,
- [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- Phi = 6,
- Return = 7,
- Throw = 8,
-}
+ [Serializable]
+ public enum FlowControl
+ {
+ Branch = 0,
+ Break = 1,
+ Call = 2,
+ Cond_Branch = 3,
+ Meta = 4,
+ Next = 5,
+ [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
+ Phi = 6,
+ Return = 7,
+ Throw = 8,
+ }
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
index 894f57d49c..dd5ffa92a9 100644
--- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
@@ -4,19 +4,20 @@
//
+using System;
+using System.Reflection;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- public sealed class GenericTypeParameterBuilder: TypeInfo
+ public sealed class GenericTypeParameterBuilder : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ {
+ if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
@@ -32,14 +33,14 @@ namespace System.Reflection.Emit
#endregion
#region Object Overrides
- public override String ToString()
- {
+ public override String ToString()
+ {
return m_type.Name;
}
- public override bool Equals(object o)
- {
+ public override bool Equals(object o)
+ {
GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
-
+
if (g == null)
return false;
@@ -62,22 +63,22 @@ namespace System.Reflection.Emit
#region Type Overrides
- public override Type MakePointerType()
- {
- return SymbolType.FormCompoundType("*", this, 0);
+ public override Type MakePointerType()
+ {
+ return SymbolType.FormCompoundType("*", this, 0);
}
- public override Type MakeByRefType()
+ public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
- public override Type MakeArrayType()
+ public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
- public override Type MakeArrayType(int rank)
+ public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
@@ -88,9 +89,9 @@ namespace System.Reflection.Emit
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -113,7 +114,7 @@ namespace System.Reflection.Emit
public override String AssemblyQualifiedName { get { return null; } }
- public override Type BaseType { get { return m_type.BaseType; } }
+ public override Type BaseType { get { return m_type.BaseType; } }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
@@ -153,6 +154,8 @@ namespace System.Reflection.Emit
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
+ public override bool IsSZArray => false;
+
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
@@ -189,7 +192,7 @@ namespace System.Reflection.Emit
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
- public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
+ public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); }
protected override bool IsValueTypeImpl() { return false; }
@@ -209,7 +212,7 @@ namespace System.Reflection.Emit
#region Public Members
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
- {
+ {
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
index 2cee63ff2e..4021410a33 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
@@ -4,16 +4,16 @@
//
-namespace System.Reflection.Emit
+using System;
+using System.Diagnostics.SymbolStore;
+using System.Runtime.InteropServices;
+using System.Reflection;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection.Emit
{
- using System;
- using System.Diagnostics.SymbolStore;
- using System.Runtime.InteropServices;
- using System.Reflection;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
public class ILGenerator
{
#region Const Members
@@ -28,18 +28,18 @@ namespace System.Reflection.Emit
{
return EnlargeArray(incoming, incoming.Length * 2);
}
-
+
internal static T[] EnlargeArray<T>(T[] incoming, int requiredSize)
{
Contract.Requires(incoming != null);
Contract.Ensures(Contract.Result<T[]>() != null);
Contract.Ensures(Contract.Result<T[]>().Length == requiredSize);
-
+
T[] temp = new T[requiredSize];
Array.Copy(incoming, 0, temp, 0, incoming.Length);
return temp;
}
-
+
private static byte[] EnlargeArray(byte[] incoming)
{
return EnlargeArray(incoming, incoming.Length * 2);
@@ -50,7 +50,7 @@ namespace System.Reflection.Emit
Contract.Requires(incoming != null);
Contract.Ensures(Contract.Result<byte[]>() != null);
Contract.Ensures(Contract.Result<byte[]>().Length == requiredSize);
-
+
byte[] temp = new byte[requiredSize];
Buffer.BlockCopy(incoming, 0, temp, 0, incoming.Length);
return temp;
@@ -58,35 +58,35 @@ namespace System.Reflection.Emit
#endregion
#region Internal Data Members
- private int m_length;
- private byte[] m_ILStream;
+ private int m_length;
+ private byte[] m_ILStream;
+
+ private int[] m_labelList;
+ private int m_labelCount;
- private int[] m_labelList;
- private int m_labelCount;
+ private __FixupData[] m_fixupData;
- private __FixupData[] m_fixupData;
-
- private int m_fixupCount;
+ private int m_fixupCount;
- private int[] m_RelocFixupList;
- private int m_RelocFixupCount;
+ private int[] m_RelocFixupList;
+ private int m_RelocFixupCount;
- private int m_exceptionCount;
- private int m_currExcStackCount;
- private __ExceptionInfo[] m_exceptions; //This is the list of all of the exceptions in this ILStream.
- private __ExceptionInfo[] m_currExcStack; //This is the stack of exceptions which we're currently in.
+ private int m_exceptionCount;
+ private int m_currExcStackCount;
+ private __ExceptionInfo[] m_exceptions; //This is the list of all of the exceptions in this ILStream.
+ private __ExceptionInfo[] m_currExcStack; //This is the stack of exceptions which we're currently in.
- internal ScopeTree m_ScopeTree; // this variable tracks all debugging scope information
- internal LineNumberInfo m_LineNumberInfo; // this variable tracks all line number information
+ internal ScopeTree m_ScopeTree; // this variable tracks all debugging scope information
+ internal LineNumberInfo m_LineNumberInfo; // this variable tracks all line number information
- internal MethodInfo m_methodBuilder;
- internal int m_localCount;
- internal SignatureHelper m_localSignature;
+ internal MethodInfo m_methodBuilder;
+ internal int m_localCount;
+ internal SignatureHelper m_localSignature;
- private int m_maxStackSize = 0; // Maximum stack size not counting the exceptions.
+ private int m_maxStackSize = 0; // Maximum stack size not counting the exceptions.
- private int m_maxMidStack = 0; // Maximum stack size for a given basic block.
- private int m_maxMidStackCur = 0; // Running count of the maximum stack size for the current basic block.
+ private int m_maxMidStack = 0; // Maximum stack size for a given basic block.
+ private int m_maxMidStackCur = 0; // Running count of the maximum stack size for the current basic block.
internal int CurrExcStackCount
{
@@ -128,9 +128,9 @@ namespace System.Reflection.Emit
m_fixupData = null;
- m_exceptions = null;
+ m_exceptions = null;
m_exceptionCount = 0;
- m_currExcStack = null;
+ m_currExcStack = null;
m_currExcStackCount = 0;
m_RelocFixupList = null;
@@ -144,7 +144,7 @@ namespace System.Reflection.Emit
// initialize local signature
m_localCount = 0;
MethodBuilder mb = m_methodBuilder as MethodBuilder;
- if (mb == null)
+ if (mb == null)
m_localSignature = SignatureHelper.GetLocalVarSigHelper(null);
else
m_localSignature = SignatureHelper.GetLocalVarSigHelper(mb.GetTypeBuilder().Module);
@@ -173,7 +173,6 @@ namespace System.Reflection.Emit
m_ILStream[m_length++] = (byte)opcode.Value;
UpdateStackSize(opcode, opcode.StackChange());
-
}
internal void UpdateStackSize(OpCode opcode, int stackchange)
@@ -211,13 +210,13 @@ namespace System.Reflection.Emit
return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef);
}
- internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
+ internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
Type[] parameterTypes, Type[] optionalParameterTypes)
{
return GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, 0);
}
- private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
+ private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
Type[] parameterTypes, Type[] optionalParameterTypes, int cGenericParameters)
{
return ((ModuleBuilder)m_methodBuilder.Module).GetMemberRefSignature(call, returnType, parameterTypes, optionalParameterTypes, cGenericParameters);
@@ -234,7 +233,7 @@ namespace System.Reflection.Emit
if (m_currExcStackCount != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_UnclosedExceptionBlock"));
+ throw new ArgumentException(SR.Argument_UnclosedExceptionBlock);
}
if (m_length == 0)
return null;
@@ -251,7 +250,7 @@ namespace System.Reflection.Emit
//Do the fixups.
//This involves iterating over all of the labels and
//replacing them with their proper values.
- for (int i =0; i < m_fixupCount; i++)
+ for (int i = 0; i < m_fixupCount; i++)
{
updateAddr = GetLabelPos(m_fixupData[i].m_fixupLabel) - (m_fixupData[i].m_fixupPos + m_fixupData[i].m_fixupInstSize);
@@ -259,11 +258,10 @@ namespace System.Reflection.Emit
//Throw an exception if they're trying to store a jump in a single byte instruction that doesn't fit.
if (m_fixupData[i].m_fixupInstSize == 1)
{
-
//Verify that our one-byte arg will fit into a Signed Byte.
if (updateAddr < SByte.MinValue || updateAddr > SByte.MaxValue)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_IllegalOneByteBranch",m_fixupData[i].m_fixupPos, updateAddr));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_IllegalOneByteBranch, m_fixupData[i].m_fixupPos, updateAddr));
}
//Place the one-byte arg
@@ -287,17 +285,17 @@ namespace System.Reflection.Emit
internal __ExceptionInfo[] GetExceptions()
{
- __ExceptionInfo []temp;
+ __ExceptionInfo[] temp;
if (m_currExcStackCount != 0)
{
- throw new NotSupportedException(Environment.GetResourceString(ResId.Argument_UnclosedExceptionBlock));
+ throw new NotSupportedException(SR.GetResourceString(ResId.Argument_UnclosedExceptionBlock));
}
-
+
if (m_exceptionCount == 0)
{
return null;
}
-
+
temp = new __ExceptionInfo[m_exceptionCount];
Array.Copy(m_exceptions, 0, temp, 0, m_exceptionCount);
SortExceptions(temp);
@@ -325,14 +323,14 @@ namespace System.Reflection.Emit
m_length = PutInteger4InArray(value, m_length, m_ILStream);
}
- private static int PutInteger4InArray(int value, int startPos, byte []array)
+ private static int PutInteger4InArray(int value, int startPos, byte[] array)
{
// Puts an Int32 onto the stream. This is an internal routine, so it does not do any error checking.
array[startPos++] = (byte)value;
- array[startPos++] = (byte)(value >>8);
- array[startPos++] = (byte)(value >>16);
- array[startPos++] = (byte)(value >>24);
+ array[startPos++] = (byte)(value >> 8);
+ array[startPos++] = (byte)(value >> 16);
+ array[startPos++] = (byte)(value >> 24);
return startPos;
}
@@ -342,12 +340,12 @@ namespace System.Reflection.Emit
// Verifies that the label exists and that it has been given a value.
int index = lbl.GetLabelValue();
-
+
if (index < 0 || index >= m_labelCount)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadLabel"));
+ throw new ArgumentException(SR.Argument_BadLabel);
if (m_labelList[index] < 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadLabelContent"));
+ throw new ArgumentException(SR.Argument_BadLabelContent);
return m_labelList[index];
}
@@ -378,7 +376,7 @@ namespace System.Reflection.Emit
return m_maxStackSize;
}
- private static void SortExceptions(__ExceptionInfo []exceptions)
+ private static void SortExceptions(__ExceptionInfo[] exceptions)
{
// In order to call exceptions properly we have to sort them in ascending order by their end position.
// Just a cheap insertion sort. We don't expect many exceptions (<10), where InsertionSort beats QuickSort.
@@ -421,40 +419,42 @@ namespace System.Reflection.Emit
{
EnsureCapacity(3);
InternalEmit(opcode);
-
}
- public virtual void Emit(OpCode opcode, byte arg)
+ public virtual void Emit(OpCode opcode, byte arg)
{
EnsureCapacity(4);
InternalEmit(opcode);
- m_ILStream[m_length++]=arg;
+ m_ILStream[m_length++] = arg;
}
[CLSCompliant(false)]
- public void Emit(OpCode opcode, sbyte arg)
+ public void Emit(OpCode opcode, sbyte arg)
{
// Puts opcode onto the stream of instructions followed by arg
EnsureCapacity(4);
InternalEmit(opcode);
- if (arg<0) {
- m_ILStream[m_length++]=(byte)(256+arg);
- } else {
- m_ILStream[m_length++]=(byte) arg;
+ if (arg < 0)
+ {
+ m_ILStream[m_length++] = (byte)(256 + arg);
+ }
+ else
+ {
+ m_ILStream[m_length++] = (byte)arg;
}
}
- public virtual void Emit(OpCode opcode, short arg)
+ public virtual void Emit(OpCode opcode, short arg)
{
// Puts opcode onto the stream of instructions followed by arg
EnsureCapacity(5);
InternalEmit(opcode);
- m_ILStream[m_length++]=(byte) arg;
- m_ILStream[m_length++]=(byte) (arg>>8);
+ m_ILStream[m_length++] = (byte)arg;
+ m_ILStream[m_length++] = (byte)(arg >> 8);
}
- public virtual void Emit(OpCode opcode, int arg)
+ public virtual void Emit(OpCode opcode, int arg)
{
// Puts opcode onto the stream of instructions followed by arg
EnsureCapacity(7);
@@ -488,26 +488,26 @@ namespace System.Reflection.Emit
UpdateStackSize(opcode, stackchange);
RecordTokenFixup();
- PutInteger4(tk);
+ PutInteger4(tk);
}
}
- public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention,
+ public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes)
{
int stackchange = 0;
- SignatureHelper sig;
+ SignatureHelper sig;
if (optionalParameterTypes != null)
{
if ((callingConvention & CallingConventions.VarArgs) == 0)
{
// Client should not supply optional parameter in default calling convention
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention);
}
}
- ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
+ ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
sig = GetMemberRefSignature(callingConvention,
returnType,
parameterTypes,
@@ -542,7 +542,7 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(methodInfo));
if (!(opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)))
- throw new ArgumentException(Environment.GetResourceString("Argument_NotMethodCallOpcode"), nameof(opcode));
+ throw new ArgumentException(SR.Argument_NotMethodCallOpcode, nameof(opcode));
Contract.EndContractBlock();
@@ -657,11 +657,11 @@ namespace System.Reflection.Emit
// patched if necessary when persisting the module to a PE.
int tempVal = 0;
- ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
+ ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
if (opcode == OpCodes.Ldtoken && cls != null && cls.IsGenericTypeDefinition)
{
// This gets the token for the generic type definition if cls is one.
- tempVal = modBuilder.GetTypeToken( cls ).Token;
+ tempVal = modBuilder.GetTypeToken(cls).Token;
}
else
{
@@ -676,44 +676,47 @@ namespace System.Reflection.Emit
PutInteger4(tempVal);
}
- public virtual void Emit(OpCode opcode, long arg) {
+ public virtual void Emit(OpCode opcode, long arg)
+ {
EnsureCapacity(11);
InternalEmit(opcode);
- m_ILStream[m_length++] = (byte) arg;
- m_ILStream[m_length++] = (byte) (arg>>8);
- m_ILStream[m_length++] = (byte) (arg>>16);
- m_ILStream[m_length++] = (byte) (arg>>24);
- m_ILStream[m_length++] = (byte) (arg>>32);
- m_ILStream[m_length++] = (byte) (arg>>40);
- m_ILStream[m_length++] = (byte) (arg>>48);
- m_ILStream[m_length++] = (byte) (arg>>56);
+ m_ILStream[m_length++] = (byte)arg;
+ m_ILStream[m_length++] = (byte)(arg >> 8);
+ m_ILStream[m_length++] = (byte)(arg >> 16);
+ m_ILStream[m_length++] = (byte)(arg >> 24);
+ m_ILStream[m_length++] = (byte)(arg >> 32);
+ m_ILStream[m_length++] = (byte)(arg >> 40);
+ m_ILStream[m_length++] = (byte)(arg >> 48);
+ m_ILStream[m_length++] = (byte)(arg >> 56);
}
- unsafe public virtual void Emit(OpCode opcode, float arg) {
+ unsafe public virtual void Emit(OpCode opcode, float arg)
+ {
EnsureCapacity(7);
InternalEmit(opcode);
uint tempVal = *(uint*)&arg;
- m_ILStream[m_length++] = (byte) tempVal;
- m_ILStream[m_length++] = (byte) (tempVal>>8);
- m_ILStream[m_length++] = (byte) (tempVal>>16);
- m_ILStream[m_length++] = (byte) (tempVal>>24);
+ m_ILStream[m_length++] = (byte)tempVal;
+ m_ILStream[m_length++] = (byte)(tempVal >> 8);
+ m_ILStream[m_length++] = (byte)(tempVal >> 16);
+ m_ILStream[m_length++] = (byte)(tempVal >> 24);
}
- unsafe public virtual void Emit(OpCode opcode, double arg) {
+ unsafe public virtual void Emit(OpCode opcode, double arg)
+ {
EnsureCapacity(11);
InternalEmit(opcode);
- ulong tempVal = *(ulong*)&arg;
- m_ILStream[m_length++] = (byte) tempVal;
- m_ILStream[m_length++] = (byte) (tempVal>>8);
- m_ILStream[m_length++] = (byte) (tempVal>>16);
- m_ILStream[m_length++] = (byte) (tempVal>>24);
- m_ILStream[m_length++] = (byte) (tempVal>>32);
- m_ILStream[m_length++] = (byte) (tempVal>>40);
- m_ILStream[m_length++] = (byte) (tempVal>>48);
- m_ILStream[m_length++] = (byte) (tempVal>>56);
+ ulong tempVal = *(ulong*)&arg;
+ m_ILStream[m_length++] = (byte)tempVal;
+ m_ILStream[m_length++] = (byte)(tempVal >> 8);
+ m_ILStream[m_length++] = (byte)(tempVal >> 16);
+ m_ILStream[m_length++] = (byte)(tempVal >> 24);
+ m_ILStream[m_length++] = (byte)(tempVal >> 32);
+ m_ILStream[m_length++] = (byte)(tempVal >> 40);
+ m_ILStream[m_length++] = (byte)(tempVal >> 48);
+ m_ILStream[m_length++] = (byte)(tempVal >> 56);
}
- public virtual void Emit(OpCode opcode, Label label)
+ public virtual void Emit(OpCode opcode, Label label)
{
// Puts opcode onto the stream and leaves space to include label
// when fixups are done. Labels are created using ILGenerator.DefineLabel and
@@ -724,18 +727,21 @@ namespace System.Reflection.Emit
// opcode must represent a branch instruction (although we don't explicitly
// verify this). Since branches are relative instructions, label will be replaced with the
// correct offset to branch during the fixup process.
-
+
int tempVal = label.GetLabelValue();
EnsureCapacity(7);
-
+
InternalEmit(opcode);
- if (OpCodes.TakesSingleByteArgument(opcode)) {
+ if (OpCodes.TakesSingleByteArgument(opcode))
+ {
AddFixup(label, m_length, 1);
m_length++;
- } else {
+ }
+ else
+ {
AddFixup(label, m_length, 4);
- m_length+=4;
+ m_length += 4;
}
}
@@ -753,32 +759,33 @@ namespace System.Reflection.Emit
int count = labels.Length;
- EnsureCapacity( count * 4 + 7 );
+ EnsureCapacity(count * 4 + 7);
InternalEmit(opcode);
PutInteger4(count);
- for ( remaining = count * 4, i = 0; remaining > 0; remaining -= 4, i++ ) {
- AddFixup( labels[i], m_length, remaining );
+ for (remaining = count * 4, i = 0; remaining > 0; remaining -= 4, i++)
+ {
+ AddFixup(labels[i], m_length, remaining);
m_length += 4;
}
}
public virtual void Emit(OpCode opcode, FieldInfo field)
{
- ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
- int tempVal = modBuilder.GetFieldToken( field ).Token;
+ ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
+ int tempVal = modBuilder.GetFieldToken(field).Token;
EnsureCapacity(7);
InternalEmit(opcode);
RecordTokenFixup();
PutInteger4(tempVal);
}
- public virtual void Emit(OpCode opcode, String str)
+ public virtual void Emit(OpCode opcode, String str)
{
// Puts the opcode onto the IL stream followed by the metadata token
// represented by str. The location of str is recorded for future
// fixups if the module is persisted to a PE.
- ModuleBuilder modBuilder = (ModuleBuilder) m_methodBuilder.Module;
+ ModuleBuilder modBuilder = (ModuleBuilder)m_methodBuilder.Module;
int tempVal = modBuilder.GetStringConstant(str).Token;
EnsureCapacity(7);
InternalEmit(opcode);
@@ -797,12 +804,12 @@ namespace System.Reflection.Emit
int tempVal = local.GetLocalIndex();
if (local.GetMethodBuilder() != m_methodBuilder)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchedMethodForLocal"), nameof(local));
+ throw new ArgumentException(SR.Argument_UnmatchedMethodForLocal, nameof(local));
}
// If the instruction is a ldloc, ldloca a stloc, morph it to the optimal form.
if (opcode.Equals(OpCodes.Ldloc))
{
- switch(tempVal)
+ switch (tempVal)
{
case 0:
opcode = OpCodes.Ldloc_0;
@@ -824,7 +831,7 @@ namespace System.Reflection.Emit
}
else if (opcode.Equals(OpCodes.Stloc))
{
- switch(tempVal)
+ switch (tempVal)
{
case 0:
opcode = OpCodes.Stloc_0;
@@ -852,28 +859,28 @@ namespace System.Reflection.Emit
EnsureCapacity(7);
InternalEmit(opcode);
-
+
if (opcode.OperandType == OperandType.InlineNone)
return;
else if (!OpCodes.TakesSingleByteArgument(opcode))
{
- m_ILStream[m_length++]=(byte) tempVal;
- m_ILStream[m_length++]=(byte) (tempVal>>8);
+ m_ILStream[m_length++] = (byte)tempVal;
+ m_ILStream[m_length++] = (byte)(tempVal >> 8);
}
else
{
//Handle stloc_1, ldloc_1
if (tempVal > Byte.MaxValue)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadInstructionOrIndexOutOfBound"));
+ throw new InvalidOperationException(SR.InvalidOperation_BadInstructionOrIndexOutOfBound);
}
- m_ILStream[m_length++]=(byte)tempVal;
+ m_ILStream[m_length++] = (byte)tempVal;
}
}
#endregion
#region Exceptions
- public virtual Label BeginExceptionBlock()
+ public virtual Label BeginExceptionBlock()
{
// Begin an Exception block. Creating an Exception block records some information,
// but does not actually emit any IL onto the stream. Exceptions should be created and
@@ -898,11 +905,13 @@ namespace System.Reflection.Emit
m_currExcStack = new __ExceptionInfo[DefaultExceptionArraySize];
}
- if (m_exceptionCount>=m_exceptions.Length) {
- m_exceptions=EnlargeArray(m_exceptions);
+ if (m_exceptionCount >= m_exceptions.Length)
+ {
+ m_exceptions = EnlargeArray(m_exceptions);
}
- if (m_currExcStackCount>=m_currExcStack.Length) {
+ if (m_currExcStackCount >= m_currExcStack.Length)
+ {
m_currExcStack = EnlargeArray(m_currExcStack);
}
@@ -917,14 +926,16 @@ namespace System.Reflection.Emit
return endLabel;
}
- public virtual void EndExceptionBlock() {
- if (m_currExcStackCount==0) {
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ public virtual void EndExceptionBlock()
+ {
+ if (m_currExcStackCount == 0)
+ {
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
}
- // Pop the current exception block
- __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
- m_currExcStack[m_currExcStackCount-1] = null;
+ // Pop the current exception block
+ __ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1];
+ m_currExcStack[m_currExcStackCount - 1] = null;
m_currExcStackCount--;
Label endLabel = current.GetEndLabel();
@@ -933,36 +944,40 @@ namespace System.Reflection.Emit
if (state == __ExceptionInfo.State_Filter ||
state == __ExceptionInfo.State_Try)
{
-
-
- throw new InvalidOperationException(Environment.GetResourceString("Argument_BadExceptionCodeGen"));
+ throw new InvalidOperationException(SR.Argument_BadExceptionCodeGen);
}
- if (state == __ExceptionInfo.State_Catch) {
+ if (state == __ExceptionInfo.State_Catch)
+ {
this.Emit(OpCodes.Leave, endLabel);
- } else if (state == __ExceptionInfo.State_Finally || state == __ExceptionInfo.State_Fault) {
+ }
+ else if (state == __ExceptionInfo.State_Finally || state == __ExceptionInfo.State_Fault)
+ {
this.Emit(OpCodes.Endfinally);
}
//Check if we've alredy set this label.
//The only reason why we might have set this is if we have a finally block.
- if (m_labelList[endLabel.GetLabelValue()]==-1) {
+ if (m_labelList[endLabel.GetLabelValue()] == -1)
+ {
MarkLabel(endLabel);
- } else {
+ }
+ else
+ {
MarkLabel(current.GetFinallyEndLabel());
}
current.Done(m_length);
}
- public virtual void BeginExceptFilterBlock()
+ public virtual void BeginExceptFilterBlock()
{
// Begins an exception filter block. Emits a branch instruction to the end of the current exception block.
if (m_currExcStackCount == 0)
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
- __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
+ __ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1];
Label endLabel = current.GetEndLabel();
this.Emit(OpCodes.Leave, endLabel);
@@ -970,30 +985,35 @@ namespace System.Reflection.Emit
current.MarkFilterAddr(m_length);
}
- public virtual void BeginCatchBlock(Type exceptionType)
+ public virtual void BeginCatchBlock(Type exceptionType)
{
// Begins a catch block. Emits a branch instruction to the end of the current exception block.
- if (m_currExcStackCount==0) {
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ if (m_currExcStackCount == 0)
+ {
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
}
- __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
+ __ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1];
- if (current.GetCurrentState() == __ExceptionInfo.State_Filter) {
- if (exceptionType != null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType"));
+ if (current.GetCurrentState() == __ExceptionInfo.State_Filter)
+ {
+ if (exceptionType != null)
+ {
+ throw new ArgumentException(SR.Argument_ShouldNotSpecifyExceptionType);
}
this.Emit(OpCodes.Endfilter);
- } else {
+ }
+ else
+ {
// execute this branch if previous clause is Catch or Fault
- if (exceptionType==null) {
+ if (exceptionType == null)
+ {
throw new ArgumentNullException(nameof(exceptionType));
}
Label endLabel = current.GetEndLabel();
this.Emit(OpCodes.Leave, endLabel);
-
}
current.MarkCatchAddr(m_length, exceptionType);
@@ -1001,10 +1021,11 @@ namespace System.Reflection.Emit
public virtual void BeginFaultBlock()
{
- if (m_currExcStackCount==0) {
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ if (m_currExcStackCount == 0)
+ {
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
}
- __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
+ __ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1];
// emit the leave for the clause before this one.
Label endLabel = current.GetEndLabel();
@@ -1013,28 +1034,29 @@ namespace System.Reflection.Emit
current.MarkFaultAddr(m_length);
}
- public virtual void BeginFinallyBlock()
+ public virtual void BeginFinallyBlock()
{
- if (m_currExcStackCount==0) {
- throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock"));
+ if (m_currExcStackCount == 0)
+ {
+ throw new NotSupportedException(SR.Argument_NotInExceptionBlock);
}
- __ExceptionInfo current = m_currExcStack[m_currExcStackCount-1];
- int state = current.GetCurrentState();
- Label endLabel = current.GetEndLabel();
- int catchEndAddr = 0;
+ __ExceptionInfo current = m_currExcStack[m_currExcStackCount - 1];
+ int state = current.GetCurrentState();
+ Label endLabel = current.GetEndLabel();
+ int catchEndAddr = 0;
if (state != __ExceptionInfo.State_Try)
{
// generate leave for any preceeding catch clause
- this.Emit(OpCodes.Leave, endLabel);
+ this.Emit(OpCodes.Leave, endLabel);
catchEndAddr = m_length;
}
-
+
MarkLabel(endLabel);
Label finallyEndLabel = this.DefineLabel();
current.SetFinallyEndLabel(finallyEndLabel);
-
+
// generate leave for try clause
this.Emit(OpCodes.Leave, finallyEndLabel);
if (catchEndAddr == 0)
@@ -1045,25 +1067,27 @@ namespace System.Reflection.Emit
#endregion
#region Labels
- public virtual Label DefineLabel()
+ public virtual Label DefineLabel()
{
// Declares a new Label. This is just a token and does not yet represent any particular location
// within the stream. In order to set the position of the label within the stream, you must call
// Mark Label.
// Delay init the lable array in case we dont use it
- if (m_labelList == null){
+ if (m_labelList == null)
+ {
m_labelList = new int[DefaultLabelArraySize];
}
- if (m_labelCount>=m_labelList.Length) {
+ if (m_labelCount >= m_labelList.Length)
+ {
m_labelList = EnlargeArray(m_labelList);
}
- m_labelList[m_labelCount]=-1;
+ m_labelList[m_labelCount] = -1;
return new Label(m_labelCount++);
}
- public virtual void MarkLabel(Label loc)
+ public virtual void MarkLabel(Label loc)
{
// Defines a label by setting the position where that label is found within the stream.
// Does not allow a label to be defined more than once.
@@ -1071,15 +1095,17 @@ namespace System.Reflection.Emit
int labelIndex = loc.GetLabelValue();
//This should never happen.
- if (labelIndex<0 || labelIndex>=m_labelList.Length) {
- throw new ArgumentException (Environment.GetResourceString("Argument_InvalidLabel"));
+ if (labelIndex < 0 || labelIndex >= m_labelList.Length)
+ {
+ throw new ArgumentException(SR.Argument_InvalidLabel);
}
- if (m_labelList[labelIndex]!=-1) {
- throw new ArgumentException (Environment.GetResourceString("Argument_RedefinedLabel"));
+ if (m_labelList[labelIndex] != -1)
+ {
+ throw new ArgumentException(SR.Argument_RedefinedLabel);
}
- m_labelList[labelIndex]=m_length;
+ m_labelList[labelIndex] = m_length;
}
#endregion
@@ -1089,17 +1115,20 @@ namespace System.Reflection.Emit
{
// Emits the il to throw an exception
- if (excType==null) {
+ if (excType == null)
+ {
throw new ArgumentNullException(nameof(excType));
}
- if (!excType.IsSubclassOf(typeof(Exception)) && excType!=typeof(Exception)) {
- throw new ArgumentException(Environment.GetResourceString("Argument_NotExceptionType"));
+ if (!excType.IsSubclassOf(typeof(Exception)) && excType != typeof(Exception))
+ {
+ throw new ArgumentException(SR.Argument_NotExceptionType);
}
Contract.EndContractBlock();
ConstructorInfo con = excType.GetConstructor(Type.EmptyTypes);
- if (con==null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_MissingDefaultConstructor"));
+ if (con == null)
+ {
+ throw new ArgumentException(SR.Argument_MissingDefaultConstructor);
}
this.Emit(OpCodes.Newobj, con);
this.Emit(OpCodes.Throw);
@@ -1108,7 +1137,7 @@ namespace System.Reflection.Emit
private static Type GetConsoleType()
{
return Type.GetType(
- "System.Console, System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
+ "System.Console, System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=" + AssemblyRef.MicrosoftPublicKeyToken,
throwOnError: true);
}
@@ -1123,17 +1152,17 @@ namespace System.Reflection.Emit
Emit(OpCodes.Call, mi);
}
- public virtual void EmitWriteLine(LocalBuilder localBuilder)
+ public virtual void EmitWriteLine(LocalBuilder localBuilder)
{
// Emits the IL necessary to call WriteLine with lcl. It is
// an error to call EmitWriteLine with a lcl which is not of
// one of the types for which Console.WriteLine implements overloads. (e.g.
// we do *not* call ToString on the locals.
- Object cls;
- if (m_methodBuilder==null)
+ Object cls;
+ if (m_methodBuilder == null)
{
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
+ throw new ArgumentException(SR.InvalidOperation_BadILGeneratorUsage);
}
MethodInfo prop = GetConsoleType().GetMethod("get_Out");
@@ -1141,13 +1170,15 @@ namespace System.Reflection.Emit
Emit(OpCodes.Ldloc, localBuilder);
Type[] parameterTypes = new Type[1];
cls = localBuilder.LocalType;
- if (cls is TypeBuilder || cls is EnumBuilder) {
- throw new ArgumentException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
+ if (cls is TypeBuilder || cls is EnumBuilder)
+ {
+ throw new ArgumentException(SR.NotSupported_OutputStreamUsingTypeBuilder);
}
parameterTypes[0] = (Type)cls;
MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
- if (mi==null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(localBuilder));
+ if (mi == null)
+ {
+ throw new ArgumentException(SR.Argument_EmitWriteLineType, nameof(localBuilder));
}
Emit(OpCodes.Callvirt, mi);
@@ -1167,25 +1198,30 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(fld));
}
Contract.EndContractBlock();
-
+
MethodInfo prop = GetConsoleType().GetMethod("get_Out");
Emit(OpCodes.Call, prop);
- if ((fld.Attributes & FieldAttributes.Static)!=0) {
+ if ((fld.Attributes & FieldAttributes.Static) != 0)
+ {
Emit(OpCodes.Ldsfld, fld);
- } else {
+ }
+ else
+ {
Emit(OpCodes.Ldarg, (short)0); //Load the this ref.
Emit(OpCodes.Ldfld, fld);
}
Type[] parameterTypes = new Type[1];
cls = fld.FieldType;
- if (cls is TypeBuilder || cls is EnumBuilder) {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"));
+ if (cls is TypeBuilder || cls is EnumBuilder)
+ {
+ throw new NotSupportedException(SR.NotSupported_OutputStreamUsingTypeBuilder);
}
parameterTypes[0] = (Type)cls;
MethodInfo mi = prop.ReturnType.GetMethod("WriteLine", parameterTypes);
- if (mi==null) {
- throw new ArgumentException(Environment.GetResourceString("Argument_EmitWriteLineType"), nameof(fld));
+ if (mi == null)
+ {
+ throw new ArgumentException(SR.Argument_EmitWriteLineType, nameof(fld));
}
Emit(OpCodes.Callvirt, mi);
}
@@ -1203,24 +1239,26 @@ namespace System.Reflection.Emit
// Declare a local of type "local". The current active lexical scope
// will be the scope that local will live.
- LocalBuilder localBuilder;
+ LocalBuilder localBuilder;
MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
- if (methodBuilder == null)
+ if (methodBuilder == null)
throw new NotSupportedException();
if (methodBuilder.IsTypeCreated())
{
// cannot change method after its containing type has been created
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
+ throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated);
}
- if (localType==null) {
+ if (localType == null)
+ {
throw new ArgumentNullException(nameof(localType));
}
- if (methodBuilder.m_bIsBaked) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBaked"));
+ if (methodBuilder.m_bIsBaked)
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_MethodBaked);
}
// add the localType to local signature
@@ -1240,12 +1278,12 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(usingNamespace));
if (usingNamespace.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(usingNamespace));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(usingNamespace));
Contract.EndContractBlock();
int index;
MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
- if (methodBuilder == null)
+ if (methodBuilder == null)
throw new NotSupportedException();
index = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex();
@@ -1301,43 +1339,44 @@ namespace System.Reflection.Emit
{
internal Label m_fixupLabel;
internal int m_fixupPos;
-
+
internal int m_fixupInstSize;
}
- internal sealed class __ExceptionInfo {
-
- internal const int None = 0x0000; //COR_ILEXCEPTION_CLAUSE_NONE
- internal const int Filter = 0x0001; //COR_ILEXCEPTION_CLAUSE_FILTER
- internal const int Finally = 0x0002; //COR_ILEXCEPTION_CLAUSE_FINALLY
- internal const int Fault = 0x0004; //COR_ILEXCEPTION_CLAUSE_FAULT
- internal const int PreserveStack = 0x0004; //COR_ILEXCEPTION_CLAUSE_PRESERVESTACK
+ internal sealed class __ExceptionInfo
+ {
+ internal const int None = 0x0000; //COR_ILEXCEPTION_CLAUSE_NONE
+ internal const int Filter = 0x0001; //COR_ILEXCEPTION_CLAUSE_FILTER
+ internal const int Finally = 0x0002; //COR_ILEXCEPTION_CLAUSE_FINALLY
+ internal const int Fault = 0x0004; //COR_ILEXCEPTION_CLAUSE_FAULT
+ internal const int PreserveStack = 0x0004; //COR_ILEXCEPTION_CLAUSE_PRESERVESTACK
internal const int State_Try = 0;
- internal const int State_Filter =1;
+ internal const int State_Filter = 1;
internal const int State_Catch = 2;
internal const int State_Finally = 3;
internal const int State_Fault = 4;
internal const int State_Done = 5;
internal int m_startAddr;
- internal int []m_filterAddr;
- internal int []m_catchAddr;
- internal int []m_catchEndAddr;
- internal int []m_type;
- internal Type []m_catchClass;
+ internal int[] m_filterAddr;
+ internal int[] m_catchAddr;
+ internal int[] m_catchEndAddr;
+ internal int[] m_type;
+ internal Type[] m_catchClass;
internal Label m_endLabel;
internal Label m_finallyEndLabel;
internal int m_endAddr;
internal int m_endFinally;
internal int m_currentCatch;
- int m_currentState;
+ private int m_currentState;
//This will never get called. The values exist merely to keep the
//compiler happy.
- private __ExceptionInfo() {
+ private __ExceptionInfo()
+ {
m_startAddr = 0;
m_filterAddr = null;
m_catchAddr = null;
@@ -1349,68 +1388,70 @@ namespace System.Reflection.Emit
m_currentState = State_Try;
}
- internal __ExceptionInfo(int startAddr, Label endLabel) {
- m_startAddr=startAddr;
- m_endAddr=-1;
- m_filterAddr=new int[4];
- m_catchAddr=new int[4];
- m_catchEndAddr=new int[4];
- m_catchClass=new Type[4];
- m_currentCatch=0;
- m_endLabel=endLabel;
- m_type=new int[4];
- m_endFinally=-1;
+ internal __ExceptionInfo(int startAddr, Label endLabel)
+ {
+ m_startAddr = startAddr;
+ m_endAddr = -1;
+ m_filterAddr = new int[4];
+ m_catchAddr = new int[4];
+ m_catchEndAddr = new int[4];
+ m_catchClass = new Type[4];
+ m_currentCatch = 0;
+ m_endLabel = endLabel;
+ m_type = new int[4];
+ m_endFinally = -1;
m_currentState = State_Try;
}
private void MarkHelper(
- int catchorfilterAddr, // the starting address of a clause
- int catchEndAddr, // the end address of a previous catch clause. Only use when finally is following a catch
- Type catchClass, // catch exception type
- int type) // kind of clause
- {
- if (m_currentCatch>=m_catchAddr.Length) {
- m_filterAddr=ILGenerator.EnlargeArray(m_filterAddr);
- m_catchAddr=ILGenerator.EnlargeArray(m_catchAddr);
- m_catchEndAddr=ILGenerator.EnlargeArray(m_catchEndAddr);
- m_catchClass=ILGenerator.EnlargeArray(m_catchClass);
+ int catchorfilterAddr, // the starting address of a clause
+ int catchEndAddr, // the end address of a previous catch clause. Only use when finally is following a catch
+ Type catchClass, // catch exception type
+ int type) // kind of clause
+ {
+ if (m_currentCatch >= m_catchAddr.Length)
+ {
+ m_filterAddr = ILGenerator.EnlargeArray(m_filterAddr);
+ m_catchAddr = ILGenerator.EnlargeArray(m_catchAddr);
+ m_catchEndAddr = ILGenerator.EnlargeArray(m_catchEndAddr);
+ m_catchClass = ILGenerator.EnlargeArray(m_catchClass);
m_type = ILGenerator.EnlargeArray(m_type);
}
if (type == Filter)
{
- m_type[m_currentCatch]=type;
+ m_type[m_currentCatch] = type;
m_filterAddr[m_currentCatch] = catchorfilterAddr;
m_catchAddr[m_currentCatch] = -1;
if (m_currentCatch > 0)
{
- Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
- m_catchEndAddr[m_currentCatch-1] = catchorfilterAddr;
+ Debug.Assert(m_catchEndAddr[m_currentCatch - 1] == -1, "m_catchEndAddr[m_currentCatch-1] == -1");
+ m_catchEndAddr[m_currentCatch - 1] = catchorfilterAddr;
}
}
else
{
// catch or Fault clause
- m_catchClass[m_currentCatch]=catchClass;
+ m_catchClass[m_currentCatch] = catchClass;
if (m_type[m_currentCatch] != Filter)
{
- m_type[m_currentCatch]=type;
+ m_type[m_currentCatch] = type;
}
- m_catchAddr[m_currentCatch]=catchorfilterAddr;
+ m_catchAddr[m_currentCatch] = catchorfilterAddr;
if (m_currentCatch > 0)
{
- if (m_type[m_currentCatch] != Filter)
- {
- Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
- m_catchEndAddr[m_currentCatch-1] = catchEndAddr;
- }
+ if (m_type[m_currentCatch] != Filter)
+ {
+ Debug.Assert(m_catchEndAddr[m_currentCatch - 1] == -1, "m_catchEndAddr[m_currentCatch-1] == -1");
+ m_catchEndAddr[m_currentCatch - 1] = catchEndAddr;
+ }
}
- m_catchEndAddr[m_currentCatch]=-1;
+ m_catchEndAddr[m_currentCatch] = -1;
m_currentCatch++;
}
- if (m_endAddr==-1)
+ if (m_endAddr == -1)
{
- m_endAddr=catchorfilterAddr;
+ m_endAddr = catchorfilterAddr;
}
}
@@ -1426,74 +1467,92 @@ namespace System.Reflection.Emit
MarkHelper(faultAddr, faultAddr, null, Fault);
}
- internal void MarkCatchAddr(int catchAddr, Type catchException) {
+ internal void MarkCatchAddr(int catchAddr, Type catchException)
+ {
m_currentState = State_Catch;
MarkHelper(catchAddr, catchAddr, catchException, None);
}
- internal void MarkFinallyAddr(int finallyAddr, int endCatchAddr) {
- if (m_endFinally!=-1) {
- throw new ArgumentException(Environment.GetResourceString("Argument_TooManyFinallyClause"));
- } else {
+ internal void MarkFinallyAddr(int finallyAddr, int endCatchAddr)
+ {
+ if (m_endFinally != -1)
+ {
+ throw new ArgumentException(SR.Argument_TooManyFinallyClause);
+ }
+ else
+ {
m_currentState = State_Finally;
- m_endFinally=finallyAddr;
+ m_endFinally = finallyAddr;
}
MarkHelper(finallyAddr, endCatchAddr, null, Finally);
}
- internal void Done(int endAddr) {
- Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
- Debug.Assert(m_catchAddr[m_currentCatch-1] > 0,"m_catchAddr[m_currentCatch-1] > 0");
- Debug.Assert(m_catchEndAddr[m_currentCatch-1] == -1,"m_catchEndAddr[m_currentCatch-1] == -1");
- m_catchEndAddr[m_currentCatch-1] = endAddr;
+ internal void Done(int endAddr)
+ {
+ Debug.Assert(m_currentCatch > 0, "m_currentCatch > 0");
+ Debug.Assert(m_catchAddr[m_currentCatch - 1] > 0, "m_catchAddr[m_currentCatch-1] > 0");
+ Debug.Assert(m_catchEndAddr[m_currentCatch - 1] == -1, "m_catchEndAddr[m_currentCatch-1] == -1");
+ m_catchEndAddr[m_currentCatch - 1] = endAddr;
m_currentState = State_Done;
}
- internal int GetStartAddress() {
+ internal int GetStartAddress()
+ {
return m_startAddr;
}
- internal int GetEndAddress() {
+ internal int GetEndAddress()
+ {
return m_endAddr;
}
- internal int GetFinallyEndAddress() {
+ internal int GetFinallyEndAddress()
+ {
return m_endFinally;
}
- internal Label GetEndLabel() {
+ internal Label GetEndLabel()
+ {
return m_endLabel;
}
- internal int [] GetFilterAddresses() {
+ internal int[] GetFilterAddresses()
+ {
return m_filterAddr;
}
- internal int [] GetCatchAddresses() {
+ internal int[] GetCatchAddresses()
+ {
return m_catchAddr;
}
- internal int [] GetCatchEndAddresses() {
+ internal int[] GetCatchEndAddresses()
+ {
return m_catchEndAddr;
}
- internal Type [] GetCatchClass() {
+ internal Type[] GetCatchClass()
+ {
return m_catchClass;
}
- internal int GetNumberOfCatches() {
+ internal int GetNumberOfCatches()
+ {
return m_currentCatch;
}
- internal int[] GetExceptionTypes() {
+ internal int[] GetExceptionTypes()
+ {
return m_type;
}
- internal void SetFinallyEndLabel(Label lbl) {
- m_finallyEndLabel=lbl;
+ internal void SetFinallyEndLabel(Label lbl)
+ {
+ m_finallyEndLabel = lbl;
}
- internal Label GetFinallyEndLabel() {
+ internal Label GetFinallyEndLabel()
+ {
return m_finallyEndLabel;
}
@@ -1505,15 +1564,16 @@ namespace System.Reflection.Emit
// of an exception. This is somewhat of a mis-nomer. This gives a
// random result for cases where the two exceptions being compared do
// not having a nesting relation.
- internal bool IsInner(__ExceptionInfo exc) {
+ internal bool IsInner(__ExceptionInfo exc)
+ {
Contract.Requires(exc != null);
- Debug.Assert(m_currentCatch > 0,"m_currentCatch > 0");
- Debug.Assert(exc.m_currentCatch > 0,"exc.m_currentCatch > 0");
+ Debug.Assert(m_currentCatch > 0, "m_currentCatch > 0");
+ Debug.Assert(exc.m_currentCatch > 0, "exc.m_currentCatch > 0");
int exclast = exc.m_currentCatch - 1;
int last = m_currentCatch - 1;
- if (exc.m_catchEndAddr[exclast] < m_catchEndAddr[last])
+ if (exc.m_catchEndAddr[exclast] < m_catchEndAddr[last])
return true;
else if (exc.m_catchEndAddr[exclast] == m_catchEndAddr[last])
{
@@ -1530,7 +1590,8 @@ namespace System.Reflection.Emit
// 2 indicates in a catch block
// 3 indicates in a finally block
// 4 indicates Done
- internal int GetCurrentState() {
+ internal int GetCurrentState()
+ {
return m_currentState;
}
}
@@ -1545,10 +1606,10 @@ namespace System.Reflection.Emit
*
***************************/
[Serializable]
- enum ScopeAction
+ internal enum ScopeAction
{
- Open = 0x0,
- Close = 0x1,
+ Open = 0x0,
+ Close = 0x1,
}
internal sealed class ScopeTree
@@ -1569,8 +1630,8 @@ namespace System.Reflection.Emit
***************************/
internal int GetCurrentActiveScopeIndex()
{
- int cClose = 0;
- int i = m_iCount - 1;
+ int cClose = 0;
+ int i = m_iCount - 1;
if (m_iCount == 0)
{
@@ -1590,13 +1651,13 @@ namespace System.Reflection.Emit
}
internal void AddLocalSymInfoToCurrentScope(
- String strName,
- byte[] signature,
- int slot,
- int startOffset,
- int endOffset)
+ String strName,
+ byte[] signature,
+ int slot,
+ int startOffset,
+ int endOffset)
{
- int i = GetCurrentActiveScopeIndex();
+ int i = GetCurrentActiveScopeIndex();
if (m_localSymInfos[i] == null)
{
m_localSymInfos[i] = new LocalSymInfo();
@@ -1605,9 +1666,9 @@ namespace System.Reflection.Emit
}
internal void AddUsingNamespaceToCurrentScope(
- String strNamespace)
+ String strNamespace)
{
- int i = GetCurrentActiveScopeIndex();
+ int i = GetCurrentActiveScopeIndex();
if (m_localSymInfos[i] == null)
{
m_localSymInfos[i] = new LocalSymInfo();
@@ -1617,16 +1678,16 @@ namespace System.Reflection.Emit
internal void AddScopeInfo(ScopeAction sa, int iOffset)
{
- if (sa == ScopeAction.Close && m_iOpenScopeCount <=0)
+ if (sa == ScopeAction.Close && m_iOpenScopeCount <= 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_UnmatchingSymScope"));
+ throw new ArgumentException(SR.Argument_UnmatchingSymScope);
}
Contract.EndContractBlock();
// make sure that arrays are large enough to hold addition info
- EnsureCapacity();
-
-
+ EnsureCapacity();
+
+
m_ScopeActions[m_iCount] = sa;
m_iOffsets[m_iCount] = iOffset;
m_localSymInfos[m_iCount] = null;
@@ -1637,7 +1698,6 @@ namespace System.Reflection.Emit
}
else
m_iOpenScopeCount--;
-
}
/**************************
@@ -1675,7 +1735,7 @@ namespace System.Reflection.Emit
internal void EmitScopeTree(ISymbolWriter symWriter)
{
- int i;
+ int i;
for (i = 0; i < m_iCount; i++)
{
if (m_ScopeActions[i] == ScopeAction.Open)
@@ -1693,11 +1753,11 @@ namespace System.Reflection.Emit
}
}
- internal int[] m_iOffsets; // array of offsets
- internal ScopeAction[] m_ScopeActions; // array of scope actions
- internal int m_iCount; // how many entries in the arrays are occupied
- internal int m_iOpenScopeCount; // keep track how many scopes are open
- internal const int InitialSize = 16;
+ internal int[] m_iOffsets; // array of offsets
+ internal ScopeAction[] m_ScopeActions; // array of scope actions
+ internal int m_iCount; // how many entries in the arrays are occupied
+ internal int m_iOpenScopeCount; // keep track how many scopes are open
+ internal const int InitialSize = 16;
internal LocalSymInfo[] m_localSymInfos; // keep track debugging local information
}
@@ -1718,32 +1778,32 @@ namespace System.Reflection.Emit
internal void AddLineNumberInfo(
ISymbolDocumentWriter document,
- int iOffset,
- int iStartLine,
- int iStartColumn,
- int iEndLine,
- int iEndColumn)
- {
- int i;
-
+ int iOffset,
+ int iStartLine,
+ int iStartColumn,
+ int iEndLine,
+ int iEndColumn)
+ {
+ int i;
+
// make sure that arrays are large enough to hold addition info
i = FindDocument(document);
-
+
Debug.Assert(i < m_DocumentCount, "Bad document look up!");
m_Documents[i].AddLineNumberInfo(document, iOffset, iStartLine, iStartColumn, iEndLine, iEndColumn);
}
-
+
// Find a REDocument representing document. If we cannot find one, we will add a new entry into
// the REDocument array.
private int FindDocument(ISymbolDocumentWriter document)
{
- int i;
-
+ int i;
+
// This is an optimization. The chance that the previous line is coming from the same
// document is very high.
if (m_iLastFound < m_DocumentCount && m_Documents[m_iLastFound].m_document == document)
return m_iLastFound;
-
+
for (i = 0; i < m_DocumentCount; i++)
{
if (m_Documents[i].m_document == document)
@@ -1752,7 +1812,7 @@ namespace System.Reflection.Emit
return m_iLastFound;
}
}
-
+
// cannot find an existing document so add one to the array
EnsureCapacity();
m_iLastFound = m_DocumentCount;
@@ -1776,7 +1836,7 @@ namespace System.Reflection.Emit
else if (m_DocumentCount == m_Documents.Length)
{
// the arrays are full. Enlarge the arrays
- REDocument[] temp = new REDocument [m_DocumentCount * 2];
+ REDocument[] temp = new REDocument[m_DocumentCount * 2];
Array.Copy(m_Documents, 0, temp, 0, m_DocumentCount);
m_Documents = temp;
}
@@ -1788,10 +1848,10 @@ namespace System.Reflection.Emit
m_Documents[i].EmitLineNumberInfo(symWriter);
}
- private int m_DocumentCount; // how many documents that we have right now
+ private int m_DocumentCount; // how many documents that we have right now
private REDocument[] m_Documents; // array of documents
- private const int InitialSize = 16;
- private int m_iLastFound;
+ private const int InitialSize = 16;
+ private int m_iLastFound;
}
@@ -1811,17 +1871,17 @@ namespace System.Reflection.Emit
internal void AddLineNumberInfo(
ISymbolDocumentWriter document,
- int iOffset,
- int iStartLine,
- int iStartColumn,
- int iEndLine,
- int iEndColumn)
+ int iOffset,
+ int iStartLine,
+ int iStartColumn,
+ int iEndLine,
+ int iEndColumn)
{
Debug.Assert(document == m_document, "Bad document look up!");
-
+
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
-
+
m_iOffsets[m_iLineNumberCount] = iOffset;
m_iLines[m_iLineNumberCount] = iStartLine;
m_iColumns[m_iLineNumberCount] = iStartColumn;
@@ -1847,27 +1907,27 @@ namespace System.Reflection.Emit
m_iEndColumns = new int[InitialSize];
}
else if (m_iLineNumberCount == m_iOffsets.Length)
- {
+ {
// the arrays are full. Enlarge the arrays
// It would probably be simpler to just use Lists here
int newSize = checked(m_iLineNumberCount * 2);
- int[] temp = new int [newSize];
+ int[] temp = new int[newSize];
Array.Copy(m_iOffsets, 0, temp, 0, m_iLineNumberCount);
m_iOffsets = temp;
- temp = new int [newSize];
+ temp = new int[newSize];
Array.Copy(m_iLines, 0, temp, 0, m_iLineNumberCount);
m_iLines = temp;
- temp = new int [newSize];
+ temp = new int[newSize];
Array.Copy(m_iColumns, 0, temp, 0, m_iLineNumberCount);
m_iColumns = temp;
- temp = new int [newSize];
+ temp = new int[newSize];
Array.Copy(m_iEndLines, 0, temp, 0, m_iLineNumberCount);
m_iEndLines = temp;
- temp = new int [newSize];
+ temp = new int[newSize];
Array.Copy(m_iEndColumns, 0, temp, 0, m_iLineNumberCount);
m_iEndColumns = temp;
}
@@ -1875,40 +1935,40 @@ namespace System.Reflection.Emit
internal void EmitLineNumberInfo(ISymbolWriter symWriter)
{
- int[] iOffsetsTemp;
- int[] iLinesTemp;
- int[] iColumnsTemp;
- int[] iEndLinesTemp;
- int[] iEndColumnsTemp;
+ int[] iOffsetsTemp;
+ int[] iLinesTemp;
+ int[] iColumnsTemp;
+ int[] iEndLinesTemp;
+ int[] iEndColumnsTemp;
if (m_iLineNumberCount == 0)
return;
// reduce the array size to be exact
- iOffsetsTemp = new int [m_iLineNumberCount];
+ iOffsetsTemp = new int[m_iLineNumberCount];
Array.Copy(m_iOffsets, 0, iOffsetsTemp, 0, m_iLineNumberCount);
- iLinesTemp = new int [m_iLineNumberCount];
+ iLinesTemp = new int[m_iLineNumberCount];
Array.Copy(m_iLines, 0, iLinesTemp, 0, m_iLineNumberCount);
- iColumnsTemp = new int [m_iLineNumberCount];
+ iColumnsTemp = new int[m_iLineNumberCount];
Array.Copy(m_iColumns, 0, iColumnsTemp, 0, m_iLineNumberCount);
- iEndLinesTemp = new int [m_iLineNumberCount];
+ iEndLinesTemp = new int[m_iLineNumberCount];
Array.Copy(m_iEndLines, 0, iEndLinesTemp, 0, m_iLineNumberCount);
- iEndColumnsTemp = new int [m_iLineNumberCount];
+ iEndColumnsTemp = new int[m_iLineNumberCount];
Array.Copy(m_iEndColumns, 0, iEndColumnsTemp, 0, m_iLineNumberCount);
- symWriter.DefineSequencePoints(m_document, iOffsetsTemp, iLinesTemp, iColumnsTemp, iEndLinesTemp, iEndColumnsTemp);
+ symWriter.DefineSequencePoints(m_document, iOffsetsTemp, iLinesTemp, iColumnsTemp, iEndLinesTemp, iEndColumnsTemp);
}
- private int[] m_iOffsets; // array of offsets
- private int[] m_iLines; // array of offsets
- private int[] m_iColumns; // array of offsets
- private int[] m_iEndLines; // array of offsets
- private int[] m_iEndColumns; // array of offsets
+ private int[] m_iOffsets; // array of offsets
+ private int[] m_iLines; // array of offsets
+ private int[] m_iColumns; // array of offsets
+ private int[] m_iEndLines; // array of offsets
+ private int[] m_iEndColumns; // array of offsets
internal ISymbolDocumentWriter m_document; // The ISymbolDocumentWriter that this REDocument is tracking.
- private int m_iLineNumberCount; // how many entries in the arrays are occupied
- private const int InitialSize = 16;
+ private int m_iLineNumberCount; // how many entries in the arrays are occupied
+ private const int InitialSize = 16;
} // end of REDocument
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
index e6f4622f0e..cda651c9ce 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ISymWrapperCore.cs
@@ -2,14 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
+using System.Security;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.SymbolStore;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Security;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Diagnostics.SymbolStore;
-
//-----------------------------------------------------------------------------------
// On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit
// relies on that assembly to write out managed PDBs.
@@ -31,7 +31,7 @@ namespace System.Reflection.Emit
// SymWrapperCore is never instantiated and is used as an encapsulation class.
// It is our "ISymWrapper.dll" assembly within an assembly.
//------------------------------------------------------------------------------
- class SymWrapperCore
+ internal class SymWrapperCore
{
//------------------------------------------------------------------------------
// Block instantiation
@@ -49,7 +49,6 @@ namespace System.Reflection.Emit
//------------------------------------------------------------------------------
private unsafe class SymDocumentWriter : ISymbolDocumentWriter
{
-
//------------------------------------------------------------------------------
// Ctor
//------------------------------------------------------------------------------
@@ -57,10 +56,10 @@ namespace System.Reflection.Emit
{
m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle;
// The handle is actually a pointer to a native ISymUnmanagedDocumentWriter.
- m_pDocWriter = (ISymUnmanagedDocumentWriter *)m_pDocumentWriterSafeHandle.DangerousGetHandle();
+ m_pDocWriter = (ISymUnmanagedDocumentWriter*)m_pDocumentWriterSafeHandle.DangerousGetHandle();
m_vtable = (ISymUnmanagedDocumentWriterVTable)(Marshal.PtrToStructure(m_pDocWriter->m_unmanagedVTable, typeof(ISymUnmanagedDocumentWriterVTable)));
}
-
+
//------------------------------------------------------------------------------
// Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.)
//------------------------------------------------------------------------------
@@ -68,7 +67,7 @@ namespace System.Reflection.Emit
{
return m_pDocumentWriterSafeHandle;
}
-
+
//=========================================================================================
// Public interface methods start here. (Well actually, they're all NotSupported
@@ -82,11 +81,11 @@ namespace System.Reflection.Emit
{
throw new NotSupportedException(); // Intentionally not supported to match desktop CLR
}
-
+
//------------------------------------------------------------------------------
// SetCheckSum() wrapper
//------------------------------------------------------------------------------
- void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte [] checkSum)
+ void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte[] checkSum)
{
int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum);
if (hr < 0)
@@ -94,8 +93,8 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
- private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter * pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum);
+
+ private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter* pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum);
//------------------------------------------------------------------------------
// This layout must match the unmanaged ISymUnmanagedDocumentWriter* COM vtable
@@ -105,14 +104,14 @@ namespace System.Reflection.Emit
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedDocumentWriterVTable
{
- internal IntPtr QueryInterface;
- internal IntPtr AddRef;
- internal IntPtr Release;
+ internal IntPtr QueryInterface;
+ internal IntPtr AddRef;
+ internal IntPtr Release;
- internal IntPtr SetSource;
- internal DSetCheckSum SetCheckSum;
+ internal IntPtr SetSource;
+ internal DSetCheckSum SetCheckSum;
}
-
+
//------------------------------------------------------------------------------
// This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter
// COM object.
@@ -128,15 +127,13 @@ namespace System.Reflection.Emit
//------------------------------------------------------------------------------
private PunkSafeHandle m_pDocumentWriterSafeHandle;
- private ISymUnmanagedDocumentWriter * m_pDocWriter;
+ private ISymUnmanagedDocumentWriter* m_pDocWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
private ISymUnmanagedDocumentWriterVTable m_vtable;
-
-
} // class SymDocumentWriter
@@ -146,8 +143,6 @@ namespace System.Reflection.Emit
//------------------------------------------------------------------------------
internal unsafe class SymWriter : ISymbolWriter
{
-
-
//------------------------------------------------------------------------------
// Creates a SymWriter. The SymWriter is a managed wrapper around the unmanaged
// symbol writer provided by the runtime (ildbsymlib or diasymreader.dll).
@@ -166,7 +161,7 @@ namespace System.Reflection.Emit
private SymWriter()
{
}
-
+
//------------------------------------------------------------------------------
// DefineDocument() wrapper
//------------------------------------------------------------------------------
@@ -188,7 +183,7 @@ namespace System.Reflection.Emit
}
return new SymDocumentWriter(psymUnmanagedDocumentWriter);
}
-
+
//------------------------------------------------------------------------------
// OpenMethod() wrapper
//------------------------------------------------------------------------------
@@ -200,7 +195,7 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
+
//------------------------------------------------------------------------------
// CloseMethod() wrapper
//------------------------------------------------------------------------------
@@ -212,7 +207,7 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
+
//------------------------------------------------------------------------------
// DefineSequencePoints() wrapper
//------------------------------------------------------------------------------
@@ -248,11 +243,11 @@ namespace System.Reflection.Emit
{
return;
}
- if ( (offsets != null && offsets.Length != spCount) ||
- (lines != null && lines.Length != spCount) ||
+ if ((offsets != null && offsets.Length != spCount) ||
+ (lines != null && lines.Length != spCount) ||
(columns != null && columns.Length != spCount) ||
(endLines != null && endLines.Length != spCount) ||
- (endColumns != null && endColumns.Length != spCount) )
+ (endColumns != null && endColumns.Length != spCount))
{
throw new ArgumentException();
}
@@ -269,9 +264,8 @@ namespace System.Reflection.Emit
{
throw Marshal.GetExceptionForHR(hr);
}
-
}
-
+
//------------------------------------------------------------------------------
// OpenScope() wrapper
//------------------------------------------------------------------------------
@@ -285,7 +279,7 @@ namespace System.Reflection.Emit
}
return ret;
}
-
+
//------------------------------------------------------------------------------
// CloseScope() wrapper
//------------------------------------------------------------------------------
@@ -297,7 +291,7 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
+
//------------------------------------------------------------------------------
// DefineLocalVariable() wrapper
//------------------------------------------------------------------------------
@@ -339,7 +333,7 @@ namespace System.Reflection.Emit
throw Marshal.GetExceptionForHR(hr);
}
}
-
+
//------------------------------------------------------------------------------
// UsingNamespace() wrapper
//------------------------------------------------------------------------------
@@ -364,65 +358,65 @@ namespace System.Reflection.Emit
internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter)
{
m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter);
- m_vtable = (ISymUnmanagedWriterVTable) (Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable)));
+ m_vtable = (ISymUnmanagedWriterVTable)(Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable)));
}
//------------------------------------------------------------------------------
// Define delegates for the unmanaged COM methods we invoke.
//------------------------------------------------------------------------------
- private delegate int DInitialize(ISymUnmanagedWriter* pthis,
- IntPtr emitter, //IUnknown*
+ private delegate int DInitialize(ISymUnmanagedWriter* pthis,
+ IntPtr emitter, //IUnknown*
[MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR*
- IntPtr pIStream, //IStream*
- [MarshalAs(UnmanagedType.Bool)] bool fFullBuild
+ IntPtr pIStream, //IStream*
+ [MarshalAs(UnmanagedType.Bool)] bool fFullBuild
);
- private delegate int DDefineDocument(ISymUnmanagedWriter* pthis,
+ private delegate int DDefineDocument(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String url,
- [In] ref Guid language,
- [In] ref Guid languageVender,
- [In] ref Guid documentType,
- [Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter
+ [In] ref Guid language,
+ [In] ref Guid languageVender,
+ [In] ref Guid documentType,
+ [Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter
);
-
+
private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod);
private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod);
private delegate int DCloseMethod(ISymUnmanagedWriter* pthis);
private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis,
- PunkSafeHandle document,
- int spCount,
- [In] int[] offsets,
- [In] int[] lines,
- [In] int[] columns,
- [In] int[] endLines,
- [In] int[] endColumns);
+ PunkSafeHandle document,
+ int spCount,
+ [In] int[] offsets,
+ [In] int[] lines,
+ [In] int[] columns,
+ [In] int[] endLines,
+ [In] int[] endColumns);
private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval);
private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset);
private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset);
- private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis,
+ private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis,
[MarshalAs(UnmanagedType.LPWStr)] String name,
- int attributes,
- int cSig,
- [In] byte[] signature,
- int addrKind,
- int addr1,
- int addr2,
- int addr3,
- int startOffset,
- int endOffset
+ int attributes,
+ int cSig,
+ [In] byte[] signature,
+ int addrKind,
+ int addr1,
+ int addr2,
+ int addr3,
+ int startOffset,
+ int endOffset
);
private delegate int DClose(ISymUnmanagedWriter* pthis);
- private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis,
- int parent,
+ private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis,
+ int parent,
[MarshalAs(UnmanagedType.LPWStr)] String name,
- int cData,
- [In] byte[] data
+ int cData,
+ [In] byte[] data
);
@@ -440,38 +434,37 @@ namespace System.Reflection.Emit
[StructLayout(LayoutKind.Sequential)]
private struct ISymUnmanagedWriterVTable
{
- internal IntPtr QueryInterface;
- internal IntPtr AddRef;
- internal IntPtr Release;
+ internal IntPtr QueryInterface;
+ internal IntPtr AddRef;
+ internal IntPtr Release;
- internal DDefineDocument DefineDocument;
- internal DSetUserEntryPoint SetUserEntryPoint;
+ internal DDefineDocument DefineDocument;
+ internal DSetUserEntryPoint SetUserEntryPoint;
- internal DOpenMethod OpenMethod;
- internal DCloseMethod CloseMethod;
+ internal DOpenMethod OpenMethod;
+ internal DCloseMethod CloseMethod;
- internal DOpenScope OpenScope;
- internal DCloseScope CloseScope;
+ internal DOpenScope OpenScope;
+ internal DCloseScope CloseScope;
- internal DSetScopeRange SetScopeRange;
+ internal DSetScopeRange SetScopeRange;
- internal DDefineLocalVariable DefineLocalVariable;
- internal IntPtr DefineParameter;
- internal IntPtr DefineField;
- internal IntPtr DefineGlobalVariable;
+ internal DDefineLocalVariable DefineLocalVariable;
+ internal IntPtr DefineParameter;
+ internal IntPtr DefineField;
+ internal IntPtr DefineGlobalVariable;
- internal DClose Close;
- internal DSetSymAttribute SetSymAttribute;
+ internal DClose Close;
+ internal DSetSymAttribute SetSymAttribute;
- internal DOpenNamespace OpenNamespace;
- internal DCloseNamespace CloseNamespace;
- internal DUsingNamespace UsingNamespace;
+ internal DOpenNamespace OpenNamespace;
+ internal DCloseNamespace CloseNamespace;
+ internal DUsingNamespace UsingNamespace;
- internal IntPtr SetMethodSourceRange;
- internal DInitialize Initialize;
- internal IntPtr GetDebugInfo;
+ internal IntPtr SetMethodSourceRange;
+ internal DInitialize Initialize;
+ internal IntPtr GetDebugInfo;
internal DDefineSequencePoints DefineSequencePoints;
-
}
//------------------------------------------------------------------------------
@@ -490,19 +483,14 @@ namespace System.Reflection.Emit
// As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer.
// Managing lifetime is up to the caller (coreclr.dll).
//------------------------------------------------------------------------------
- private ISymUnmanagedWriter *m_pWriter;
+ private ISymUnmanagedWriter* m_pWriter;
//------------------------------------------------------------------------------
// Stores the "managed vtable" (actually a structure full of delegates that
// P/Invoke to the corresponding unmanaged COM methods.)
//------------------------------------------------------------------------------
private ISymUnmanagedWriterVTable m_vtable;
-
} // class SymWriter
-
-
-
-
} //class SymWrapperCore
@@ -518,7 +506,7 @@ namespace System.Reflection.Emit
//
// Had to make this a non-nested class since FCall's don't like to bind to nested classes.
//--------------------------------------------------------------------------------------
- sealed class PunkSafeHandle : SafeHandle
+ internal sealed class PunkSafeHandle : SafeHandle
{
internal PunkSafeHandle()
: base((IntPtr)0, true)
diff --git a/src/mscorlib/src/System/Reflection/Emit/Label.cs b/src/mscorlib/src/System/Reflection/Emit/Label.cs
index c7b987ff10..f6315a67d2 100644
--- a/src/mscorlib/src/System/Reflection/Emit/Label.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/Label.cs
@@ -13,11 +13,13 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
- using System;
- using System.Reflection;
- using System.Runtime.InteropServices;
+using System;
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+namespace System.Reflection.Emit
+{
// The Label class is an opaque representation of a label used by the
// ILGenerator class. The token is used to mark where labels occur in the IL
// stream and then the necessary offsets are put back in the code when the ILGenerator
@@ -25,27 +27,29 @@ namespace System.Reflection.Emit {
// Labels are created by using ILGenerator.CreateLabel and their position is set
// by using ILGenerator.MarkLabel.
[Serializable]
- public struct Label {
-
+ public struct Label
+ {
internal int m_label;
-
+
//public Label() {
// m_label=0;
//}
-
- internal Label (int label) {
- m_label=label;
+
+ internal Label(int label)
+ {
+ m_label = label;
}
-
- internal int GetLabelValue() {
+
+ internal int GetLabelValue()
+ {
return m_label;
}
-
+
public override int GetHashCode()
{
return m_label;
}
-
+
public override bool Equals(Object obj)
{
if (obj is Label)
@@ -53,17 +57,17 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(Label obj)
{
return obj.m_label == m_label;
}
-
+
public static bool operator ==(Label a, Label b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(Label a, Label b)
{
return !(a == b);
diff --git a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
index fe4c33160a..c04c3c8434 100644
--- a/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/LocalBuilder.cs
@@ -6,10 +6,10 @@ using System;
using System.Reflection;
using System.Runtime.InteropServices;
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
public sealed class LocalBuilder : LocalVariableInfo
- {
+ {
#region Private Data Members
private int m_localIndex;
private Type m_localType;
@@ -19,9 +19,9 @@ namespace System.Reflection.Emit
#region Constructor
private LocalBuilder() { }
- internal LocalBuilder(int localIndex, Type localType, MethodInfo methodBuilder)
+ internal LocalBuilder(int localIndex, Type localType, MethodInfo methodBuilder)
: this(localIndex, localType, methodBuilder, false) { }
- internal LocalBuilder(int localIndex, Type localType, MethodInfo methodBuilder, bool isPinned)
+ internal LocalBuilder(int localIndex, Type localType, MethodInfo methodBuilder, bool isPinned)
{
m_isPinned = isPinned;
m_localIndex = localIndex;
@@ -31,11 +31,11 @@ namespace System.Reflection.Emit
#endregion
#region Internal Members
- internal int GetLocalIndex()
+ internal int GetLocalIndex()
{
return m_localIndex;
}
- internal MethodInfo GetMethodBuilder()
+ internal MethodInfo GetMethodBuilder()
{
return m_methodBuilder;
}
@@ -43,13 +43,13 @@ namespace System.Reflection.Emit
#region LocalVariableInfo Override
public override bool IsPinned { get { return m_isPinned; } }
- public override Type LocalType
+ public override Type LocalType
{
- get
- {
- return m_localType;
+ get
+ {
+ return m_localType;
}
- }
+ }
public override int LocalIndex { get { return m_localIndex; } }
#endregion
@@ -57,7 +57,7 @@ namespace System.Reflection.Emit
public void SetLocalSymInfo(String name)
{
SetLocalSymInfo(name, 0, 0);
- }
+ }
public void SetLocalSymInfo(String name, int startOffset, int endOffset)
{
@@ -69,27 +69,27 @@ namespace System.Reflection.Emit
int index;
MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder;
- if (methodBuilder == null)
+ if (methodBuilder == null)
// it's a light code gen entity
throw new NotSupportedException();
- dynMod = (ModuleBuilder) methodBuilder.Module;
+ dynMod = (ModuleBuilder)methodBuilder.Module;
if (methodBuilder.IsTypeCreated())
{
// cannot change method after its containing type has been created
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
+ throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated);
}
-
+
// set the name and range of offset for the local
if (dynMod.GetSymWriter() == null)
{
// cannot set local name if not debug module
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule);
}
-
+
sigHelp = SignatureHelper.GetFieldSigHelper(dynMod);
sigHelp.AddArgument(m_localType);
signature = sigHelp.InternalGetSignature(out sigLength);
-
+
// The symbol store doesn't want the calling convention on the
// front of the signature, but InternalGetSignature returns
// the callinging convention. So we strip it off. This is a
@@ -97,7 +97,7 @@ namespace System.Reflection.Emit
// yet another array of bytes...
mungedSig = new byte[sigLength - 1];
Buffer.BlockCopy(signature, 1, mungedSig, 0, sigLength - 1);
-
+
index = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex();
if (index == -1)
{
@@ -105,7 +105,7 @@ namespace System.Reflection.Emit
methodBuilder.m_localSymInfo.AddLocalSymInfo(
name,
mungedSig,
- m_localIndex,
+ m_localIndex,
startOffset,
endOffset);
}
@@ -114,7 +114,7 @@ namespace System.Reflection.Emit
methodBuilder.GetILGenerator().m_ScopeTree.AddLocalSymInfoToCurrentScope(
name,
mungedSig,
- m_localIndex,
+ m_localIndex,
startOffset,
endOffset);
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
index 17c8ce074d..530a5ee092 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilder.cs
@@ -4,7 +4,7 @@
//
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
using System.Text;
using System;
@@ -35,7 +35,7 @@ namespace System.Reflection.Emit
private byte[] m_ubBody; // The IL for the method
private ExceptionHandler[] m_exceptions; // Exception handlers or null if there are none.
private const int DefaultMaxStack = 16;
- private int m_maxStack = DefaultMaxStack;
+ private int m_maxStack = DefaultMaxStack;
// Flags
internal bool m_bIsBaked;
@@ -69,7 +69,7 @@ namespace System.Reflection.Emit
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
- Init(name, attributes, callingConvention,
+ Init(name, attributes, callingConvention,
returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
mod, type, bIsGlobalMethod);
@@ -77,17 +77,17 @@ namespace System.Reflection.Emit
private void Init(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
- Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
+ Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers,
ModuleBuilder mod, TypeBuilder type, bool bIsGlobalMethod)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
+ throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
if (mod == null)
throw new ArgumentNullException(nameof(mod));
@@ -95,7 +95,7 @@ namespace System.Reflection.Emit
if (parameterTypes != null)
{
- foreach(Type t in parameterTypes)
+ foreach (Type t in parameterTypes)
{
if (t == null)
throw new ArgumentNullException(nameof(parameterTypes));
@@ -124,7 +124,7 @@ namespace System.Reflection.Emit
else if ((attributes & MethodAttributes.Virtual) != 0)
{
// A method can't be both static and virtual
- throw new ArgumentException(Environment.GetResourceString("Arg_NoStaticVirtual"));
+ throw new ArgumentException(SR.Arg_NoStaticVirtual);
}
if ((attributes & MethodAttributes.SpecialName) != MethodAttributes.SpecialName)
@@ -132,10 +132,10 @@ namespace System.Reflection.Emit
if ((type.Attributes & TypeAttributes.Interface) == TypeAttributes.Interface)
{
// methods on interface have to be abstract + virtual except special name methods such as type initializer
- if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
- (MethodAttributes.Abstract | MethodAttributes.Virtual) &&
+ if ((attributes & (MethodAttributes.Abstract | MethodAttributes.Virtual)) !=
+ (MethodAttributes.Abstract | MethodAttributes.Virtual) &&
(attributes & MethodAttributes.Static) == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod"));
+ throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod);
}
}
@@ -156,9 +156,9 @@ namespace System.Reflection.Emit
m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers;
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
-// m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
-// returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
-// parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
+ // m_signature = SignatureHelper.GetMethodSigHelper(mod, callingConvention,
+ // returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
+ // parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
m_iAttributes = attributes;
m_bIsGlobalMethod = bIsGlobalMethod;
@@ -179,9 +179,9 @@ namespace System.Reflection.Emit
internal void CheckContext(params Type[][] typess)
{
- m_module.CheckContext(typess);
+ m_module.CheckContext(typess);
}
-
+
internal void CheckContext(params Type[] types)
{
m_module.CheckContext(types);
@@ -197,22 +197,22 @@ namespace System.Reflection.Emit
}
Contract.EndContractBlock();
- __ExceptionInfo[] excp;
- int counter=0;
- int[] filterAddrs;
- int[] catchAddrs;
- int[] catchEndAddrs;
- Type[] catchClass;
- int[] type;
- int numCatch;
- int start, end;
- ModuleBuilder dynMod = (ModuleBuilder) m_module;
+ __ExceptionInfo[] excp;
+ int counter = 0;
+ int[] filterAddrs;
+ int[] catchAddrs;
+ int[] catchEndAddrs;
+ Type[] catchClass;
+ int[] type;
+ int numCatch;
+ int start, end;
+ ModuleBuilder dynMod = (ModuleBuilder)m_module;
m_containingType.ThrowIfCreated();
if (m_bIsBaked)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodHasBody"));
+ throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody);
}
if (il.m_methodBuilder != this && il.m_methodBuilder != null)
@@ -221,15 +221,15 @@ namespace System.Reflection.Emit
// through MethodBuilder::GetILGenerator.
//
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadILGeneratorUsage"));
+ throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage);
}
-
+
ThrowIfShouldNotHaveBody();
if (il.m_ScopeTree.m_iOpenScopeCount != 0)
{
// There are still unclosed local scope
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_OpenLocalVariableScope"));
+ throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope);
}
@@ -276,20 +276,18 @@ namespace System.Reflection.Emit
break;
}
}
-
}
}
- m_bIsBaked=true;
+ m_bIsBaked = true;
if (dynMod.GetSymWriter() != null)
{
-
// set the debugging information such as scope and line number
// if it is in a debug module
//
- SymbolToken tk = new SymbolToken(MetadataTokenInternal);
+ SymbolToken tk = new SymbolToken(MetadataTokenInternal);
ISymbolWriter symWriter = dynMod.GetSymWriter();
// call OpenMethod to make this method the current method
@@ -299,16 +297,16 @@ namespace System.Reflection.Emit
// the top-levelsmethod scope
//
symWriter.OpenScope(0);
-
+
if (m_symCustomAttrs != null)
{
- foreach(SymCustomAttr symCustomAttr in m_symCustomAttrs)
+ foreach (SymCustomAttr symCustomAttr in m_symCustomAttrs)
dynMod.GetSymWriter().SetSymAttribute(
- new SymbolToken (MetadataTokenInternal),
- symCustomAttr.m_name,
+ new SymbolToken(MetadataTokenInternal),
+ symCustomAttr.m_name,
symCustomAttr.m_data);
}
-
+
if (m_localSymInfo != null)
m_localSymInfo.EmitLocalSymInfo(symWriter);
il.m_ScopeTree.EmitScopeTree(symWriter);
@@ -330,14 +328,14 @@ namespace System.Reflection.Emit
m_ubBody = null;
m_localSymInfo = null;
m_mdMethodFixups = null;
- m_localSignature = null;
+ m_localSignature = null;
m_exceptions = null;
}
internal override Type[] GetParameterTypes()
{
if (m_parameterTypes == null)
- m_parameterTypes = EmptyArray<Type>.Value;
+ m_parameterTypes = Array.Empty<Type>();
return m_parameterTypes;
}
@@ -347,11 +345,11 @@ namespace System.Reflection.Emit
MethodInfo mi = null;
ConstructorInfo ci = null;
- if ( (mi = method as MethodInfo) != null )
+ if ((mi = method as MethodInfo) != null)
{
return mi.ReturnType;
}
- else if ( (ci = method as ConstructorInfo) != null)
+ else if ((ci = method as ConstructorInfo) != null)
{
return ci.GetReturnType();
}
@@ -377,9 +375,9 @@ namespace System.Reflection.Emit
internal SignatureHelper GetMethodSignature()
{
if (m_parameterTypes == null)
- m_parameterTypes = EmptyArray<Type>.Value;
+ m_parameterTypes = Array.Empty<Type>();
- m_signature = SignatureHelper.GetMethodSigHelper (m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
+ m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, m_inst != null ? m_inst.Length : 0,
m_returnType == null ? typeof(void) : m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers,
m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers);
@@ -394,7 +392,7 @@ namespace System.Reflection.Emit
signatureLength = m_localSignature.Length;
return m_localSignature;
}
-
+
if (m_ilGenerator != null)
{
if (m_ilGenerator.m_localCount != 0)
@@ -432,28 +430,28 @@ namespace System.Reflection.Emit
internal int CalculateNumberOfExceptions(__ExceptionInfo[] excp)
{
- int num=0;
+ int num = 0;
- if (excp==null)
+ if (excp == null)
{
return 0;
}
- for (int i=0; i<excp.Length; i++)
+ for (int i = 0; i < excp.Length; i++)
{
- num+=excp[i].GetNumberOfCatches();
+ num += excp[i].GetNumberOfCatches();
}
return num;
}
internal bool IsTypeCreated()
- {
- return (m_containingType != null && m_containingType.IsCreated());
+ {
+ return (m_containingType != null && m_containingType.IsCreated());
}
internal TypeBuilder GetTypeBuilder()
- {
+ {
return m_containingType;
}
@@ -464,20 +462,25 @@ namespace System.Reflection.Emit
#endregion
#region Object Overrides
- public override bool Equals(Object obj) {
- if (!(obj is MethodBuilder)) {
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is MethodBuilder))
+ {
return false;
}
- if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName))) {
+ if (!(this.m_strName.Equals(((MethodBuilder)obj).m_strName)))
+ {
return false;
}
- if (m_iAttributes!=(((MethodBuilder)obj).m_iAttributes)) {
+ if (m_iAttributes != (((MethodBuilder)obj).m_iAttributes))
+ {
return false;
}
SignatureHelper thatSig = ((MethodBuilder)obj).GetMethodSignature();
- if (thatSig.Equals(GetMethodSignature())) {
+ if (thatSig.Equals(GetMethodSignature()))
+ {
return true;
}
return false;
@@ -503,15 +506,15 @@ namespace System.Reflection.Emit
#region MemberInfo Overrides
public override String Name
{
- get
- {
- return m_strName;
+ get
+ {
+ return m_strName;
}
}
internal int MetadataTokenInternal
{
- get
+ get
{
return GetToken().Token;
}
@@ -519,7 +522,7 @@ namespace System.Reflection.Emit
public override Module Module
{
- get
+ get
{
return m_containingType.Module;
}
@@ -535,9 +538,9 @@ namespace System.Reflection.Emit
}
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
- get
+ get
{
return null;
}
@@ -556,7 +559,7 @@ namespace System.Reflection.Emit
#region MethodBase Overrides
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodImplAttributes GetMethodImplementationFlags()
@@ -571,12 +574,12 @@ namespace System.Reflection.Emit
public override CallingConventions CallingConvention
{
- get {return m_callingConvention;}
+ get { return m_callingConvention; }
}
public override RuntimeMethodHandle MethodHandle
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
+ get { throw new NotSupportedException(SR.NotSupported_DynamicModule); }
}
public override bool IsSecurityCritical
@@ -613,7 +616,7 @@ namespace System.Reflection.Emit
public override ParameterInfo[] GetParameters()
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
- throw new NotSupportedException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
+ throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
@@ -625,7 +628,7 @@ namespace System.Reflection.Emit
get
{
if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeNotCreated"));
+ throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated);
MethodInfo rmi = m_containingType.GetMethod(m_strName, m_parameterTypes);
@@ -637,20 +640,17 @@ namespace System.Reflection.Emit
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
-
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
-
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
-
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
#endregion
@@ -663,43 +663,43 @@ namespace System.Reflection.Emit
public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) throw new InvalidOperationException(); return this; }
public override bool IsGenericMethod { get { return m_inst != null; } }
-
+
public override Type[] GetGenericArguments() { return m_inst; }
- public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
+ public override MethodInfo MakeGenericMethod(params Type[] typeArguments)
{
- return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
+ return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments);
}
-
-
- public GenericTypeParameterBuilder[] DefineGenericParameters (params string[] names)
+
+
+ public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names)
{
if (names == null)
throw new ArgumentNullException(nameof(names));
if (names.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyArray"), nameof(names));
+ throw new ArgumentException(SR.Arg_EmptyArray, nameof(names));
Contract.EndContractBlock();
if (m_inst != null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GenericParametersAlreadySet"));
+ throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet);
- for (int i = 0; i < names.Length; i ++)
+ for (int i = 0; i < names.Length; i++)
if (names[i] == null)
throw new ArgumentNullException(nameof(names));
if (m_tkMethod.Token != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MethodBuilderBaked"));
+ throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked);
m_bIsGenMethDef = true;
m_inst = new GenericTypeParameterBuilder[names.Length];
- for (int i = 0; i < names.Length; i ++)
+ for (int i = 0; i < names.Length; i++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
-
- internal void ThrowIfGeneric () { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException (); }
+
+ internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) throw new InvalidOperationException(); }
#endregion
#region Public Members
@@ -773,22 +773,22 @@ namespace System.Reflection.Emit
return m_tkMethod;
}
- public void SetParameters (params Type[] parameterTypes)
+ public void SetParameters(params Type[] parameterTypes)
{
CheckContext(parameterTypes);
-
- SetSignature (null, null, null, parameterTypes, null, null);
+
+ SetSignature(null, null, null, parameterTypes, null, null);
}
- public void SetReturnType (Type returnType)
+ public void SetReturnType(Type returnType)
{
CheckContext(returnType);
-
- SetSignature (returnType, null, null, null, null, null);
+
+ SetSignature(returnType, null, null, null, null, null);
}
public void SetSignature(
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
+ Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
// We should throw InvalidOperation_MethodBuilderBaked here if the method signature has been baked.
@@ -800,7 +800,7 @@ namespace System.Reflection.Emit
CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes);
CheckContext(parameterTypeRequiredCustomModifiers);
CheckContext(parameterTypeOptionalCustomModifiers);
-
+
ThrowIfGeneric();
if (returnType != null)
@@ -811,7 +811,7 @@ namespace System.Reflection.Emit
if (parameterTypes != null)
{
m_parameterTypes = new Type[parameterTypes.Length];
- Array.Copy (parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
+ Array.Copy(parameterTypes, 0, m_parameterTypes, 0, parameterTypes.Length);
}
m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers;
@@ -820,18 +820,18 @@ namespace System.Reflection.Emit
m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers;
}
-
+
public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, String strParamName)
{
if (position < 0)
- throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
+ throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
Contract.EndContractBlock();
ThrowIfGeneric();
- m_containingType.ThrowIfCreated ();
+ m_containingType.ThrowIfCreated();
if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length))
- throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_ParamSequence"));
+ throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence);
attributes = attributes & ~ParameterAttributes.ReservedMask;
return new ParameterBuilder(this, position, attributes, strParamName);
@@ -844,11 +844,11 @@ namespace System.Reflection.Emit
public byte[] m_data;
}
- public void SetImplementationFlags(MethodImplAttributes attributes)
+ public void SetImplementationFlags(MethodImplAttributes attributes)
{
- ThrowIfGeneric ();
+ ThrowIfGeneric();
- m_containingType.ThrowIfCreated ();
+ m_containingType.ThrowIfCreated();
m_dwMethodImplFlags = attributes;
@@ -857,7 +857,8 @@ namespace System.Reflection.Emit
TypeBuilder.SetMethodImpl(m_module.GetNativeHandle(), MetadataTokenInternal, attributes);
}
- public ILGenerator GetILGenerator() {
+ public ILGenerator GetILGenerator()
+ {
Contract.Ensures(Contract.Result<ILGenerator>() != null);
ThrowIfGeneric();
@@ -868,18 +869,20 @@ namespace System.Reflection.Emit
return m_ilGenerator;
}
- public ILGenerator GetILGenerator(int size) {
+ public ILGenerator GetILGenerator(int size)
+ {
Contract.Ensures(Contract.Result<ILGenerator>() != null);
- ThrowIfGeneric ();
+ ThrowIfGeneric();
ThrowIfShouldNotHaveBody();
-
+
if (m_ilGenerator == null)
m_ilGenerator = new ILGenerator(this, size);
return m_ilGenerator;
}
- private void ThrowIfShouldNotHaveBody() {
+ private void ThrowIfShouldNotHaveBody()
+ {
if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != MethodImplAttributes.IL ||
(m_dwMethodImplFlags & MethodImplAttributes.Unmanaged) != 0 ||
(m_iAttributes & MethodAttributes.PinvokeImpl) != 0 ||
@@ -887,16 +890,16 @@ namespace System.Reflection.Emit
{
// cannot attach method body if methodimpl is marked not marked as managed IL
//
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ShouldNotHaveMethodBody"));
+ throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody);
}
}
-
- public bool InitLocals
- {
+
+ public bool InitLocals
+ {
// Property is set to true if user wishes to have zero initialized stack frame for this method. Default to false.
- get { ThrowIfGeneric (); return m_fInitLocals; }
- set { ThrowIfGeneric (); m_fInitLocals = value; }
+ get { ThrowIfGeneric(); return m_fInitLocals; }
+ set { ThrowIfGeneric(); m_fInitLocals = value; }
}
public Module GetModule()
@@ -904,12 +907,12 @@ namespace System.Reflection.Emit
return GetModuleBuilder();
}
- public String Signature
- {
- get
- {
- return GetMethodSignature().ToString();
- }
+ public String Signature
+ {
+ get
+ {
+ return GetMethodSignature().ToString();
+ }
}
@@ -941,7 +944,7 @@ namespace System.Reflection.Emit
ThrowIfGeneric();
customBuilder.CreateCustomAttribute((ModuleBuilder)m_module, MetadataTokenInternal);
-
+
if (IsKnownCA(customBuilder.m_con))
ParseCA(customBuilder.m_con, customBuilder.m_blob);
}
@@ -959,7 +962,7 @@ namespace System.Reflection.Emit
private void ParseCA(ConstructorInfo con, byte[] blob)
{
Type caType = con.DeclaringType;
- if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
+ if (caType == typeof(System.Runtime.CompilerServices.MethodImplAttribute))
{
// dig through the blob looking for the MethodImplAttributes flag
// that must be in the MethodCodeType field
@@ -968,11 +971,11 @@ namespace System.Reflection.Emit
// allows this method to have no body when any kind of MethodImplAttribute is present
m_canBeRuntimeImpl = true;
}
- else if (caType == typeof(DllImportAttribute)) {
+ else if (caType == typeof(DllImportAttribute))
+ {
m_canBeRuntimeImpl = true;
m_isDllImport = true;
}
-
}
internal bool m_canBeRuntimeImpl = false;
@@ -987,15 +990,15 @@ namespace System.Reflection.Emit
// and namespace information with a given active lexical scope.
#region Internal Data Members
- internal String[] m_strName;
- internal byte[][] m_ubSignature;
- internal int[] m_iLocalSlot;
- internal int[] m_iStartOffset;
- internal int[] m_iEndOffset;
- internal int m_iLocalSymCount; // how many entries in the arrays are occupied
- internal String[] m_namespace;
- internal int m_iNameSpaceCount;
- internal const int InitialSize = 16;
+ internal String[] m_strName;
+ internal byte[][] m_ubSignature;
+ internal int[] m_iLocalSlot;
+ internal int[] m_iStartOffset;
+ internal int[] m_iEndOffset;
+ internal int m_iLocalSymCount; // how many entries in the arrays are occupied
+ internal String[] m_namespace;
+ internal int m_iNameSpaceCount;
+ internal const int InitialSize = 16;
#endregion
#region Constructor
@@ -1016,7 +1019,7 @@ namespace System.Reflection.Emit
}
else if (m_iNameSpaceCount == m_namespace.Length)
{
- String [] strTemp = new String [checked(m_iNameSpaceCount * 2)];
+ String[] strTemp = new String[checked(m_iNameSpaceCount * 2)];
Array.Copy(m_namespace, 0, strTemp, 0, m_iNameSpaceCount);
m_namespace = strTemp;
}
@@ -1038,33 +1041,32 @@ namespace System.Reflection.Emit
// the arrays are full. Enlarge the arrays
// why aren't we just using lists here?
int newSize = checked(m_iLocalSymCount * 2);
- int[] temp = new int [newSize];
+ int[] temp = new int[newSize];
Array.Copy(m_iLocalSlot, 0, temp, 0, m_iLocalSymCount);
m_iLocalSlot = temp;
- temp = new int [newSize];
+ temp = new int[newSize];
Array.Copy(m_iStartOffset, 0, temp, 0, m_iLocalSymCount);
m_iStartOffset = temp;
- temp = new int [newSize];
+ temp = new int[newSize];
Array.Copy(m_iEndOffset, 0, temp, 0, m_iLocalSymCount);
m_iEndOffset = temp;
- String [] strTemp = new String [newSize];
+ String[] strTemp = new String[newSize];
Array.Copy(m_strName, 0, strTemp, 0, m_iLocalSymCount);
m_strName = strTemp;
byte[][] ubTemp = new byte[newSize][];
Array.Copy(m_ubSignature, 0, ubTemp, 0, m_iLocalSymCount);
m_ubSignature = ubTemp;
-
}
}
#endregion
#region Internal Members
- internal void AddLocalSymInfo(String strName,byte[] signature,int slot,int startOffset,int endOffset)
+ internal void AddLocalSymInfo(String strName, byte[] signature, int slot, int startOffset, int endOffset)
{
// make sure that arrays are large enough to hold addition info
EnsureCapacity();
@@ -1073,7 +1075,7 @@ namespace System.Reflection.Emit
m_iLocalSlot[m_iLocalSymCount] = slot;
m_strName[m_iLocalSymCount] = strName;
m_ubSignature[m_iLocalSymCount] = signature;
- checked {m_iLocalSymCount++; }
+ checked { m_iLocalSymCount++; }
}
internal void AddUsingNamespace(String strNamespace)
@@ -1085,13 +1087,13 @@ namespace System.Reflection.Emit
internal virtual void EmitLocalSymInfo(ISymbolWriter symWriter)
{
- int i;
+ int i;
- for (i = 0; i < m_iLocalSymCount; i ++)
+ for (i = 0; i < m_iLocalSymCount; i++)
{
symWriter.DefineLocalVariable(
m_strName[i],
- FieldAttributes.PrivateScope,
+ FieldAttributes.PrivateScope,
m_ubSignature[i],
SymAddressKind.ILOffset,
m_iLocalSlot[i],
@@ -1100,7 +1102,7 @@ namespace System.Reflection.Emit
m_iStartOffset[i],
m_iEndOffset[i]);
}
- for (i = 0; i < m_iNameSpaceCount; i ++)
+ for (i = 0; i < m_iNameSpaceCount; i++)
{
symWriter.UsingNamespace(m_namespace[i]);
}
@@ -1124,7 +1126,7 @@ namespace System.Reflection.Emit
internal readonly int m_handlerEndOffset;
internal readonly ExceptionHandlingClauseOptions m_kind;
-#region Constructors
+ #region Constructors
internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset,
int kind, int exceptionTypeToken)
@@ -1160,7 +1162,7 @@ namespace System.Reflection.Emit
return false;
}
}
-
+
#endregion
#region Equality
@@ -1187,7 +1189,7 @@ namespace System.Reflection.Emit
other.m_kind == m_kind;
}
- public static bool operator ==(ExceptionHandler left, ExceptionHandler right)
+ public static bool operator ==(ExceptionHandler left, ExceptionHandler right)
{
return left.Equals(right);
}
@@ -1196,7 +1198,7 @@ namespace System.Reflection.Emit
{
return !left.Equals(right);
}
-
+
#endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
index 57ad1665c0..2d0a9b41dd 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
@@ -4,14 +4,14 @@
//
+using System;
+using System.Reflection;
+using System.Collections;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
internal sealed class MethodBuilderInstantiation : MethodInfo
{
#region Static Members
@@ -38,18 +38,18 @@ namespace System.Reflection.Emit
m_inst = inst;
}
#endregion
-
+
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberBase
- public override MemberTypes MemberType { get { return m_method.MemberType; } }
+ public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override String Name { get { return m_method.Name; } }
- public override Type DeclaringType { get { return m_method.DeclaringType; } }
+ public override Type DeclaringType { get { return m_method.DeclaringType; } }
public override Type ReflectedType { get { return m_method.ReflectedType; } }
- public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
+ public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
public override Module Module { get { return m_method.Module; } }
@@ -57,9 +57,9 @@ namespace System.Reflection.Emit
#region MethodBase Members
[Pure]
- public override ParameterInfo[] GetParameters() { throw new NotSupportedException(); }
+ public override ParameterInfo[] GetParameters() { throw new NotSupportedException(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
- public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); } }
+ public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
@@ -88,11 +88,11 @@ namespace System.Reflection.Emit
public override MethodInfo MakeGenericMethod(params Type[] arguments)
{
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericMethodDefinition"));
+ throw new InvalidOperationException(SR.Arg_NotGenericMethodDefinition);
}
public override bool IsGenericMethod { get { return true; } }
-
+
#endregion
#region Public Abstract\Virtual Members
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
index 76b7279f30..0905ac922a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodToken.cs
@@ -12,25 +12,28 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
[Serializable]
public struct MethodToken
{
public static readonly MethodToken Empty = new MethodToken();
internal int m_method;
-
- internal MethodToken(int str) {
- m_method=str;
+
+ internal MethodToken(int str)
+ {
+ m_method = str;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_method; }
}
-
+
public override int GetHashCode()
{
return m_method;
@@ -43,21 +46,20 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(MethodToken obj)
{
return obj.m_method == m_method;
}
-
+
public static bool operator ==(MethodToken a, MethodToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(MethodToken a, MethodToken b)
{
return !(a == b);
}
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
index 30e6382550..d92d8220b8 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
@@ -4,7 +4,7 @@
//
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
@@ -120,7 +120,7 @@ namespace System.Reflection.Emit
object.ReferenceEquals(foundType.DeclaringType, enclosingType))
{
// Cannot have two types with the same name
- throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName"));
+ throw new ArgumentException(SR.Argument_DuplicateTypeName);
}
}
@@ -135,10 +135,9 @@ namespace System.Reflection.Emit
// convert the format string to byte array and then call FormCompoundType
return SymbolType.FormCompoundType(strFormat, baseType, 0);
-
}
-
-
+
+
internal void CheckContext(params Type[][] typess)
{
ContainingAssemblyBuilder.CheckContext(typess);
@@ -179,14 +178,6 @@ namespace System.Reflection.Emit
{
Debug.Assert(method != null);
-#if FEATURE_APPX
- if (ContainingAssemblyBuilder.ProfileAPICheck)
- {
- if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
- }
-#endif
-
return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
}
@@ -194,14 +185,6 @@ namespace System.Reflection.Emit
{
Debug.Assert(method != null);
-#if FEATURE_APPX
- if (ContainingAssemblyBuilder.ProfileAPICheck)
- {
- if ((method.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", method.FullName));
- }
-#endif
-
return GetMemberRefOfMethodInfo(GetNativeHandle(), tr, method);
}
@@ -213,15 +196,6 @@ namespace System.Reflection.Emit
{
Debug.Assert(runtimeField != null);
-#if FEATURE_APPX
- if (ContainingAssemblyBuilder.ProfileAPICheck)
- {
- RtFieldInfo rtField = runtimeField as RtFieldInfo;
- if (rtField != null && (rtField.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtField.FullName));
- }
-#endif
-
return GetMemberRefOfFieldInfo(GetNativeHandle(), tkType, declaringType, runtimeField.MetadataToken);
}
@@ -286,17 +260,6 @@ namespace System.Reflection.Emit
Debug.Assert(!type.IsByRef, "Must not be ByRef.");
Debug.Assert(!type.IsGenericType || type.IsGenericTypeDefinition, "Must not have generic arguments.");
-#if FEATURE_APPX
- if (ContainingAssemblyBuilder.ProfileAPICheck)
- {
- RuntimeType rtType = type as RuntimeType;
- if (rtType != null && (rtType.InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", rtType.FullName));
- }
- }
-#endif
-
return GetTypeRef(GetNativeHandle(), typeName, GetRuntimeModuleFromModule(refedModule).GetNativeHandle(), strRefedModuleFileName, tkResolution);
}
@@ -315,7 +278,7 @@ namespace System.Reflection.Emit
ConstructorOnTypeBuilderInstantiation conOnTypeBuilderInst = null;
RuntimeConstructorInfo rtCon = null;
- if ( (conBuilder = con as ConstructorBuilder) != null )
+ if ((conBuilder = con as ConstructorBuilder) != null)
{
if (usingRef == false && conBuilder.Module.Equals(this))
return conBuilder.GetToken();
@@ -324,14 +287,14 @@ namespace System.Reflection.Emit
tr = GetTypeTokenInternal(con.ReflectedType).Token;
mr = GetMemberRef(con.ReflectedType.Module, tr, conBuilder.GetToken().Token);
}
- else if ( (conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null )
+ else if ((conOnTypeBuilderInst = con as ConstructorOnTypeBuilderInstantiation) != null)
{
if (usingRef == true) throw new InvalidOperationException();
tr = GetTypeTokenInternal(con.DeclaringType).Token;
mr = GetMemberRef(con.DeclaringType.Module, tr, conOnTypeBuilderInst.MetadataTokenInternal);
}
- else if ( (rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false)
+ else if ((rtCon = con as RuntimeConstructorInfo) != null && con.ReflectedType.IsArray == false)
{
// constructor is not a dynamic field
// We need to get the TypeRef tokens
@@ -345,7 +308,7 @@ namespace System.Reflection.Emit
// go through the slower code path, i.e. retrieve parameters and form signature helper.
ParameterInfo[] parameters = con.GetParameters();
if (parameters == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
+ throw new ArgumentException(SR.Argument_InvalidConstructorInfo);
Type[] parameterTypes = new Type[parameters.Length];
Type[][] requiredCustomModifiers = new Type[parameters.Length][];
@@ -354,7 +317,7 @@ namespace System.Reflection.Emit
for (int i = 0; i < parameters.Length; i++)
{
if (parameters[i] == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorInfo"));
+ throw new ArgumentException(SR.Argument_InvalidConstructorInfo);
parameterTypes[i] = parameters[i].ParameterType;
requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
@@ -369,8 +332,8 @@ namespace System.Reflection.Emit
mr = GetMemberRefFromSignature(tr, con.Name, sigBytes, length);
}
-
- return new MethodToken( mr );
+
+ return new MethodToken(mr);
}
internal void Init(String strModuleName, String strFileName, int tkFile)
@@ -395,7 +358,7 @@ namespace System.Reflection.Emit
#endregion
#region Module Overrides
-
+
// m_internalModuleBuilder is null iff this is a "internal" ModuleBuilder
internal InternalModuleBuilder InternalModule
{
@@ -405,7 +368,7 @@ namespace System.Reflection.Emit
}
}
- internal override ModuleHandle GetModuleHandle()
+ protected override ModuleHandle GetModuleHandleImpl()
{
return new ModuleHandle(GetNativeHandle());
}
@@ -446,7 +409,7 @@ namespace System.Reflection.Emit
if ((method.CallingConvention & CallingConventions.VarArgs) == 0)
{
// Client should not supply optional parameter in default calling convention
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAVarArgCallingConvention"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention);
}
}
@@ -532,7 +495,7 @@ namespace System.Reflection.Emit
}
internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType,
- Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters)
+ Type[] parameterTypes, IEnumerable<Type> optionalParameterTypes, int cGenericParameters)
{
SignatureHelper sig = SignatureHelper.GetMethodSigHelper(this, call, returnType, cGenericParameters);
@@ -544,7 +507,8 @@ namespace System.Reflection.Emit
}
}
- if (optionalParameterTypes != null) {
+ if (optionalParameterTypes != null)
+ {
int i = 0;
foreach (Type type in optionalParameterTypes)
{
@@ -599,7 +563,7 @@ namespace System.Reflection.Emit
public override Type[] GetTypes()
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetTypesNoLock();
}
@@ -620,7 +584,7 @@ namespace System.Reflection.Emit
tmpTypeBldr = enumBldr.m_typeBuilder;
else
tmpTypeBldr = (TypeBuilder)builder;
-
+
// We should not return TypeBuilders.
// Otherwise anyone can emit code in it.
if (tmpTypeBldr.IsCreated())
@@ -636,15 +600,15 @@ namespace System.Reflection.Emit
{
return GetType(className, false, false);
}
-
+
public override Type GetType(String className, bool ignoreCase)
{
return GetType(className, false, ignoreCase);
}
-
+
public override Type GetType(String className, bool throwOnError, bool ignoreCase)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetTypeNoLock(className, throwOnError, ignoreCase);
}
@@ -658,7 +622,7 @@ namespace System.Reflection.Emit
// This API first delegate to the Module.GetType implementation. If succeeded, great!
// If not, we have to look up the current module to find the TypeBuilder to represent the base
// type and form the Type object for "foo[,]".
-
+
// Module.GetType() will verify className.
Type baseType = InternalModule.GetType(className, throwOnError, ignoreCase);
if (baseType != null)
@@ -674,7 +638,7 @@ namespace System.Reflection.Emit
while (startIndex <= className.Length)
{
// Are there any possible special characters left?
- int i = className.IndexOfAny(new char[]{'[', '*', '&'}, startIndex);
+ int i = className.IndexOfAny(new char[] { '[', '*', '&' }, startIndex);
if (i == -1)
{
// No, type name is simple.
@@ -709,7 +673,7 @@ namespace System.Reflection.Emit
parameters = null;
}
- baseName = baseName.Replace(@"\\",@"\").Replace(@"\[",@"[").Replace(@"\*",@"*").Replace(@"\&",@"&");
+ baseName = baseName.Replace(@"\\", @"\").Replace(@"\[", @"[").Replace(@"\*", @"*").Replace(@"\&", @"&");
if (parameters != null)
{
@@ -742,9 +706,9 @@ namespace System.Reflection.Emit
return null;
}
- if (parameters == null)
+ if (parameters == null)
return baseType;
-
+
return GetType(parameters, baseType);
}
@@ -885,7 +849,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
}
@@ -895,7 +859,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
}
@@ -905,7 +869,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
// Why do we only call CheckContext here? Why don't we call it in the other overloads?
CheckContext(parent);
@@ -918,7 +882,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize);
}
@@ -938,7 +902,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, TypeBuilder.UnspecifiedTypeSize);
}
@@ -955,7 +919,7 @@ namespace System.Reflection.Emit
{
Contract.Ensures(Contract.Result<TypeBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeNoLock(name, attr, parent, packsize);
}
@@ -979,7 +943,7 @@ namespace System.Reflection.Emit
Contract.Ensures(Contract.Result<EnumBuilder>() != null);
CheckContext(underlyingType);
- lock(SyncRoot)
+ lock (SyncRoot)
{
EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType);
@@ -1006,7 +970,7 @@ namespace System.Reflection.Emit
return new EnumBuilder(name, underlyingType, visibility, this);
}
-
+
#endregion
#region Define Resource
@@ -1021,7 +985,7 @@ namespace System.Reflection.Emit
return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes);
}
- public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
+ public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
Contract.Ensures(Contract.Result<MethodBuilder>() != null);
@@ -1029,33 +993,33 @@ namespace System.Reflection.Emit
return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
- public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
+ public MethodBuilder DefineGlobalMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
- return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType,
+ return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType,
requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
}
- private MethodBuilder DefineGlobalMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention,
+ private MethodBuilder DefineGlobalMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
if (m_moduleData.m_fGlobalBeenCreated == true)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
-
+ throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated);
+
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
-
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
+
if ((attributes & MethodAttributes.Static) == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_GlobalFunctionHasToBeStatic"));
+ throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic);
Contract.Ensures(Contract.Result<MethodBuilder>() != null);
Contract.EndContractBlock();
@@ -1066,14 +1030,14 @@ namespace System.Reflection.Emit
m_moduleData.m_fHasGlobal = true;
- return m_moduleData.m_globalTypeBuilder.DefineMethod(name, attributes, callingConvention,
- returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
+ return m_moduleData.m_globalTypeBuilder.DefineMethod(name, attributes, callingConvention,
+ returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
-
+
public void CreateGlobalFunctions()
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
CreateGlobalFunctionsNoLock();
}
@@ -1084,12 +1048,12 @@ namespace System.Reflection.Emit
if (m_moduleData.m_fGlobalBeenCreated)
{
// cannot create globals twice
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule);
}
m_moduleData.m_globalTypeBuilder.CreateType();
m_moduleData.m_fGlobalBeenCreated = true;
}
-
+
#endregion
#region Define Data
@@ -1101,7 +1065,7 @@ namespace System.Reflection.Emit
// will be the signature for the Field.
Contract.Ensures(Contract.Result<FieldBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineInitializedDataNoLock(name, data, attributes);
}
@@ -1114,20 +1078,20 @@ namespace System.Reflection.Emit
// will be the signature for the Field.
if (m_moduleData.m_fGlobalBeenCreated == true)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
+ throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated);
}
Contract.Ensures(Contract.Result<FieldBuilder>() != null);
Contract.EndContractBlock();
-
+
m_moduleData.m_fHasGlobal = true;
return m_moduleData.m_globalTypeBuilder.DefineInitializedData(name, data, attributes);
}
-
+
public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
{
Contract.Ensures(Contract.Result<FieldBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineUninitializedDataNoLock(name, size, attributes);
}
@@ -1141,15 +1105,15 @@ namespace System.Reflection.Emit
if (m_moduleData.m_fGlobalBeenCreated == true)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"));
+ throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated);
}
Contract.Ensures(Contract.Result<FieldBuilder>() != null);
Contract.EndContractBlock();
-
+
m_moduleData.m_fHasGlobal = true;
return m_moduleData.m_globalTypeBuilder.DefineUninitializedData(name, size, attributes);
}
-
+
#endregion
#region GetToken
@@ -1164,14 +1128,14 @@ namespace System.Reflection.Emit
private TypeToken GetTypeTokenInternal(Type type, bool getGenericDefinition)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetTypeTokenWorkerNoLock(type, getGenericDefinition);
}
}
public TypeToken GetTypeToken(Type type)
- {
+ {
return GetTypeTokenInternal(type, true);
}
@@ -1182,7 +1146,7 @@ namespace System.Reflection.Emit
Contract.EndContractBlock();
CheckContext(type);
-
+
// Return a token for the class relative to the Module. Tokens
// are used to indentify objects when the objects are used in IL
// instructions. Tokens are always relative to the Module. For example,
@@ -1194,7 +1158,7 @@ namespace System.Reflection.Emit
// We should also be aware of multiple dynamic modules and multiple implementation of Type!!!
if (type.IsByRef)
- throw new ArgumentException(Environment.GetResourceString("Argument_CannotGetTypeTokenForByRef"));
+ throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef);
if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) ||
type.IsGenericParameter ||
@@ -1231,10 +1195,10 @@ namespace System.Reflection.Emit
{
return new TypeToken(paramBuilder.MetadataTokenInternal);
}
-
+
return new TypeToken(GetTypeRefNested(type, this, String.Empty));
}
-
+
// After this point, the referenced module is not the same as the referencing
// module.
//
@@ -1258,21 +1222,21 @@ namespace System.Reflection.Emit
return new TypeToken(GetTypeRefNested(type, refedModule, strRefedModuleFileName));
}
-
+
public TypeToken GetTypeToken(String name)
{
// Return a token for the class relative to the Module.
// Module.GetType() verifies name
-
+
// Unfortunately, we will need to load the Type and then call GetTypeToken in
// order to correctly track the assembly reference information.
-
+
return GetTypeToken(InternalModule.GetType(name, false, true));
}
public MethodToken GetMethodToken(MethodInfo method)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetMethodTokenNoLock(method, true);
}
@@ -1280,7 +1244,7 @@ namespace System.Reflection.Emit
internal MethodToken GetMethodTokenInternal(MethodInfo method)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetMethodTokenNoLock(method, false);
}
@@ -1300,18 +1264,18 @@ namespace System.Reflection.Emit
int tr;
int mr = 0;
-
+
SymbolMethod symMethod = null;
MethodBuilder methBuilder = null;
- if ( (methBuilder = method as MethodBuilder) != null )
+ if ((methBuilder = method as MethodBuilder) != null)
{
int methodToken = methBuilder.MetadataTokenInternal;
if (method.Module.Equals(this))
return new MethodToken(methodToken);
if (method.DeclaringType == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule);
// method is defined in a different module
tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
@@ -1335,7 +1299,7 @@ namespace System.Reflection.Emit
// We need to get the TypeRef tokens
if (declaringType == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule);
RuntimeMethodInfo rtMeth = null;
@@ -1343,15 +1307,15 @@ namespace System.Reflection.Emit
{
// use reflection to build signature to work around the E_T_VAR problem in EEClass
ParameterInfo[] paramInfo = method.GetParameters();
-
+
Type[] tt = new Type[paramInfo.Length];
-
+
for (int i = 0; i < paramInfo.Length; i++)
tt[i] = paramInfo[i].ParameterType;
return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, tt);
}
- else if ( (rtMeth = method as RuntimeMethodInfo) != null )
+ else if ((rtMeth = method as RuntimeMethodInfo) != null)
{
tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
mr = GetMemberRefOfMethodInfo(tr, rtMeth);
@@ -1372,25 +1336,25 @@ namespace System.Reflection.Emit
requiredCustomModifiers[i] = parameters[i].GetRequiredCustomModifiers();
optionalCustomModifiers[i] = parameters[i].GetOptionalCustomModifiers();
}
-
+
tr = getGenericTypeDefinition ? GetTypeToken(method.DeclaringType).Token : GetTypeTokenInternal(method.DeclaringType).Token;
SignatureHelper sigHelp;
- try
+ try
{
sigHelp = SignatureHelper.GetMethodSigHelper(
- this, method.CallingConvention, method.ReturnType,
- method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(),
+ this, method.CallingConvention, method.ReturnType,
+ method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(),
parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
- }
- catch(NotImplementedException)
+ }
+ catch (NotImplementedException)
{
// Legacy code deriving from MethodInfo may not have implemented ReturnParameter.
sigHelp = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, parameterTypes);
}
- int length;
+ int length;
byte[] sigBytes = sigHelp.InternalGetSignature(out length);
mr = GetMemberRefFromSignature(tr, method.Name, sigBytes, length);
}
@@ -1464,17 +1428,17 @@ namespace System.Reflection.Emit
return tk;
}
-
- public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention,
+
+ public MethodToken GetArrayMethodToken(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes);
}
}
- private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention,
+ private MethodToken GetArrayMethodTokenNoLock(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
if (arrayClass == null)
@@ -1484,10 +1448,10 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(methodName));
if (methodName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(methodName));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(methodName));
if (arrayClass.IsArray == false)
- throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass"));
+ throw new ArgumentException(SR.Argument_HasToBeArrayClass);
Contract.EndContractBlock();
CheckContext(returnType, arrayClass);
@@ -1509,7 +1473,7 @@ namespace System.Reflection.Emit
typeSpec.Token, methodName, sigBytes, length));
}
- public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention,
+ public MethodInfo GetArrayMethod(Type arrayClass, String methodName, CallingConventions callingConvention,
Type returnType, Type[] parameterTypes)
{
CheckContext(returnType, arrayClass);
@@ -1531,23 +1495,24 @@ namespace System.Reflection.Emit
return InternalGetConstructorToken(con, false);
}
- public FieldToken GetFieldToken(FieldInfo field)
+ public FieldToken GetFieldToken(FieldInfo field)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return GetFieldTokenNoLock(field);
}
}
- private FieldToken GetFieldTokenNoLock(FieldInfo field)
+ private FieldToken GetFieldTokenNoLock(FieldInfo field)
{
- if (field == null) {
+ if (field == null)
+ {
throw new ArgumentNullException(nameof(field));
}
Contract.EndContractBlock();
- int tr;
- int mr = 0;
+ int tr;
+ int mr = 0;
FieldBuilder fdBuilder = null;
RuntimeFieldInfo rtField = null;
@@ -1572,22 +1537,22 @@ namespace System.Reflection.Emit
// field is defined in a different module
if (field.DeclaringType == null)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule);
}
tr = GetTypeTokenInternal(field.DeclaringType).Token;
mr = GetMemberRef(field.ReflectedType.Module, tr, fdBuilder.GetToken().Token);
}
}
- else if ( (rtField = field as RuntimeFieldInfo) != null)
+ else if ((rtField = field as RuntimeFieldInfo) != null)
{
// FieldInfo is not an dynamic field
-
+
// We need to get the TypeRef tokens
if (field.DeclaringType == null)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule);
}
-
+
if (field.DeclaringType != null && field.DeclaringType.IsGenericType)
{
int length;
@@ -1597,11 +1562,11 @@ namespace System.Reflection.Emit
}
else
{
- tr = GetTypeTokenInternal(field.DeclaringType).Token;
+ tr = GetTypeTokenInternal(field.DeclaringType).Token;
mr = GetMemberRefOfFieldInfo(tr, field.DeclaringType.GetTypeHandleInternal(), rtField);
}
}
- else if ( (fOnTB = field as FieldOnTypeBuilderInstantiation) != null)
+ else if ((fOnTB = field as FieldOnTypeBuilderInstantiation) != null)
{
FieldInfo fb = fOnTB.FieldInfo;
int length;
@@ -1623,11 +1588,11 @@ namespace System.Reflection.Emit
mr = GetMemberRefFromSignature(tr, field.Name, sigBytes, length);
}
-
+
return new FieldToken(mr, field.GetType());
}
-
- public StringToken GetStringConstant(String str)
+
+ public StringToken GetStringConstant(String str)
{
if (str == null)
{
@@ -1639,7 +1604,7 @@ namespace System.Reflection.Emit
// value has already been defined, the existing token will be returned.
return new StringToken(GetStringConstant(GetNativeHandle(), str, str.Length));
}
-
+
public SignatureToken GetSignatureToken(SignatureHelper sigHelper)
{
// Define signature token given a signature helper. This will define a metadata
@@ -1653,11 +1618,11 @@ namespace System.Reflection.Emit
int sigLength;
byte[] sigBytes;
-
+
// get the signature in byte form
sigBytes = sigHelper.InternalGetSignature(out sigLength);
return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), sigBytes, sigLength), this);
- }
+ }
public SignatureToken GetSignatureToken(byte[] sigBytes, int sigLength)
{
if (sigBytes == null)
@@ -1669,7 +1634,7 @@ namespace System.Reflection.Emit
return new SignatureToken(TypeBuilder.GetTokenFromSig(GetNativeHandle(), localSigBytes, sigLength), this);
}
-
+
#endregion
#region Other
@@ -1681,7 +1646,7 @@ namespace System.Reflection.Emit
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
Contract.EndContractBlock();
-
+
TypeBuilder.DefineCustomAttribute(
this,
1, // This is hard coding the module token to 1
@@ -1742,7 +1707,7 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(url));
Contract.EndContractBlock();
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineDocumentNoLock(url, language, languageVendor, documentType);
}
@@ -1753,12 +1718,12 @@ namespace System.Reflection.Emit
if (m_iSymWriter == null)
{
// Cannot DefineDocument when it is not a debug module
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotADebugModule"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule);
}
return m_iSymWriter.DefineDocument(url, language, languageVendor, documentType);
}
-
+
[Pure]
public bool IsTransient()
{
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
index 4b6f8b4efe..4f1b8eb713 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
@@ -6,16 +6,16 @@
////////////////////////////////////////////////////////////////////////////////
//
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.IO;
+using System.Reflection;
+using System.Runtime.Versioning;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.IO;
- using System.Reflection;
- using System.Runtime.Versioning;
-
// This is a package private class. This class hold all of the managed
// data member for ModuleBuilder. Note that what ever data members added to
// this class cannot be accessed from the EE.
@@ -46,25 +46,25 @@ namespace System.Reflection.Emit
if (strExtension == null || strExtension == String.Empty)
{
// This is required by our loader. It cannot load module file that does not have file extension.
- throw new ArgumentException(Environment.GetResourceString("Argument_NoModuleFileExtension", strFileName));
+ throw new ArgumentException(SR.Format(SR.Argument_NoModuleFileExtension, strFileName));
}
m_strFileName = strFileName;
}
}
- internal String m_strModuleName; // scope name (can be different from file name)
- internal String m_strFileName;
- internal bool m_fGlobalBeenCreated;
- internal bool m_fHasGlobal;
+ internal String m_strModuleName; // scope name (can be different from file name)
+ internal String m_strFileName;
+ internal bool m_fGlobalBeenCreated;
+ internal bool m_fHasGlobal;
[NonSerialized]
- internal TypeBuilder m_globalTypeBuilder;
+ internal TypeBuilder m_globalTypeBuilder;
[NonSerialized]
internal ModuleBuilder m_module;
- private int m_tkFile;
- internal bool m_isSaved;
+ private int m_tkFile;
+ internal bool m_isSaved;
internal const String MULTI_BYTE_VALUE_CLASS = "$ArrayType$";
- internal String m_strResourceFileName;
- internal byte[] m_resourceBytes;
+ internal String m_strResourceFileName;
+ internal byte[] m_resourceBytes;
} // class ModuleBuilderData
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs b/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs
index 324fad9ceb..99915492c1 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OpCodes.cs
@@ -10,2540 +10,2543 @@
**
**
============================================================*/
-namespace System.Reflection.Emit {
using System;
-//
-// Internal enums for opcode values. Note that the value names are used to construct
-// publicly visible ilasm-compatible opcode names, so their exact form is important!
-//
-internal enum OpCodeValues {
- Nop = 0x00,
- Break = 0x01,
- Ldarg_0 = 0x02,
- Ldarg_1 = 0x03,
- Ldarg_2 = 0x04,
- Ldarg_3 = 0x05,
- Ldloc_0 = 0x06,
- Ldloc_1 = 0x07,
- Ldloc_2 = 0x08,
- Ldloc_3 = 0x09,
- Stloc_0 = 0x0a,
- Stloc_1 = 0x0b,
- Stloc_2 = 0x0c,
- Stloc_3 = 0x0d,
- Ldarg_S = 0x0e,
- Ldarga_S = 0x0f,
- Starg_S = 0x10,
- Ldloc_S = 0x11,
- Ldloca_S = 0x12,
- Stloc_S = 0x13,
- Ldnull = 0x14,
- Ldc_I4_M1 = 0x15,
- Ldc_I4_0 = 0x16,
- Ldc_I4_1 = 0x17,
- Ldc_I4_2 = 0x18,
- Ldc_I4_3 = 0x19,
- Ldc_I4_4 = 0x1a,
- Ldc_I4_5 = 0x1b,
- Ldc_I4_6 = 0x1c,
- Ldc_I4_7 = 0x1d,
- Ldc_I4_8 = 0x1e,
- Ldc_I4_S = 0x1f,
- Ldc_I4 = 0x20,
- Ldc_I8 = 0x21,
- Ldc_R4 = 0x22,
- Ldc_R8 = 0x23,
- Dup = 0x25,
- Pop = 0x26,
- Jmp = 0x27,
- Call = 0x28,
- Calli = 0x29,
- Ret = 0x2a,
- Br_S = 0x2b,
- Brfalse_S = 0x2c,
- Brtrue_S = 0x2d,
- Beq_S = 0x2e,
- Bge_S = 0x2f,
- Bgt_S = 0x30,
- Ble_S = 0x31,
- Blt_S = 0x32,
- Bne_Un_S = 0x33,
- Bge_Un_S = 0x34,
- Bgt_Un_S = 0x35,
- Ble_Un_S = 0x36,
- Blt_Un_S = 0x37,
- Br = 0x38,
- Brfalse = 0x39,
- Brtrue = 0x3a,
- Beq = 0x3b,
- Bge = 0x3c,
- Bgt = 0x3d,
- Ble = 0x3e,
- Blt = 0x3f,
- Bne_Un = 0x40,
- Bge_Un = 0x41,
- Bgt_Un = 0x42,
- Ble_Un = 0x43,
- Blt_Un = 0x44,
- Switch = 0x45,
- Ldind_I1 = 0x46,
- Ldind_U1 = 0x47,
- Ldind_I2 = 0x48,
- Ldind_U2 = 0x49,
- Ldind_I4 = 0x4a,
- Ldind_U4 = 0x4b,
- Ldind_I8 = 0x4c,
- Ldind_I = 0x4d,
- Ldind_R4 = 0x4e,
- Ldind_R8 = 0x4f,
- Ldind_Ref = 0x50,
- Stind_Ref = 0x51,
- Stind_I1 = 0x52,
- Stind_I2 = 0x53,
- Stind_I4 = 0x54,
- Stind_I8 = 0x55,
- Stind_R4 = 0x56,
- Stind_R8 = 0x57,
- Add = 0x58,
- Sub = 0x59,
- Mul = 0x5a,
- Div = 0x5b,
- Div_Un = 0x5c,
- Rem = 0x5d,
- Rem_Un = 0x5e,
- And = 0x5f,
- Or = 0x60,
- Xor = 0x61,
- Shl = 0x62,
- Shr = 0x63,
- Shr_Un = 0x64,
- Neg = 0x65,
- Not = 0x66,
- Conv_I1 = 0x67,
- Conv_I2 = 0x68,
- Conv_I4 = 0x69,
- Conv_I8 = 0x6a,
- Conv_R4 = 0x6b,
- Conv_R8 = 0x6c,
- Conv_U4 = 0x6d,
- Conv_U8 = 0x6e,
- Callvirt = 0x6f,
- Cpobj = 0x70,
- Ldobj = 0x71,
- Ldstr = 0x72,
- Newobj = 0x73,
- Castclass = 0x74,
- Isinst = 0x75,
- Conv_R_Un = 0x76,
- Unbox = 0x79,
- Throw = 0x7a,
- Ldfld = 0x7b,
- Ldflda = 0x7c,
- Stfld = 0x7d,
- Ldsfld = 0x7e,
- Ldsflda = 0x7f,
- Stsfld = 0x80,
- Stobj = 0x81,
- Conv_Ovf_I1_Un = 0x82,
- Conv_Ovf_I2_Un = 0x83,
- Conv_Ovf_I4_Un = 0x84,
- Conv_Ovf_I8_Un = 0x85,
- Conv_Ovf_U1_Un = 0x86,
- Conv_Ovf_U2_Un = 0x87,
- Conv_Ovf_U4_Un = 0x88,
- Conv_Ovf_U8_Un = 0x89,
- Conv_Ovf_I_Un = 0x8a,
- Conv_Ovf_U_Un = 0x8b,
- Box = 0x8c,
- Newarr = 0x8d,
- Ldlen = 0x8e,
- Ldelema = 0x8f,
- Ldelem_I1 = 0x90,
- Ldelem_U1 = 0x91,
- Ldelem_I2 = 0x92,
- Ldelem_U2 = 0x93,
- Ldelem_I4 = 0x94,
- Ldelem_U4 = 0x95,
- Ldelem_I8 = 0x96,
- Ldelem_I = 0x97,
- Ldelem_R4 = 0x98,
- Ldelem_R8 = 0x99,
- Ldelem_Ref = 0x9a,
- Stelem_I = 0x9b,
- Stelem_I1 = 0x9c,
- Stelem_I2 = 0x9d,
- Stelem_I4 = 0x9e,
- Stelem_I8 = 0x9f,
- Stelem_R4 = 0xa0,
- Stelem_R8 = 0xa1,
- Stelem_Ref = 0xa2,
- Ldelem = 0xa3,
- Stelem = 0xa4,
- Unbox_Any = 0xa5,
- Conv_Ovf_I1 = 0xb3,
- Conv_Ovf_U1 = 0xb4,
- Conv_Ovf_I2 = 0xb5,
- Conv_Ovf_U2 = 0xb6,
- Conv_Ovf_I4 = 0xb7,
- Conv_Ovf_U4 = 0xb8,
- Conv_Ovf_I8 = 0xb9,
- Conv_Ovf_U8 = 0xba,
- Refanyval = 0xc2,
- Ckfinite = 0xc3,
- Mkrefany = 0xc6,
- Ldtoken = 0xd0,
- Conv_U2 = 0xd1,
- Conv_U1 = 0xd2,
- Conv_I = 0xd3,
- Conv_Ovf_I = 0xd4,
- Conv_Ovf_U = 0xd5,
- Add_Ovf = 0xd6,
- Add_Ovf_Un = 0xd7,
- Mul_Ovf = 0xd8,
- Mul_Ovf_Un = 0xd9,
- Sub_Ovf = 0xda,
- Sub_Ovf_Un = 0xdb,
- Endfinally = 0xdc,
- Leave = 0xdd,
- Leave_S = 0xde,
- Stind_I = 0xdf,
- Conv_U = 0xe0,
- Prefix7 = 0xf8,
- Prefix6 = 0xf9,
- Prefix5 = 0xfa,
- Prefix4 = 0xfb,
- Prefix3 = 0xfc,
- Prefix2 = 0xfd,
- Prefix1 = 0xfe,
- Prefixref = 0xff,
- Arglist = 0xfe00,
- Ceq = 0xfe01,
- Cgt = 0xfe02,
- Cgt_Un = 0xfe03,
- Clt = 0xfe04,
- Clt_Un = 0xfe05,
- Ldftn = 0xfe06,
- Ldvirtftn = 0xfe07,
- Ldarg = 0xfe09,
- Ldarga = 0xfe0a,
- Starg = 0xfe0b,
- Ldloc = 0xfe0c,
- Ldloca = 0xfe0d,
- Stloc = 0xfe0e,
- Localloc = 0xfe0f,
- Endfilter = 0xfe11,
- Unaligned_ = 0xfe12,
- Volatile_ = 0xfe13,
- Tail_ = 0xfe14,
- Initobj = 0xfe15,
- Constrained_ = 0xfe16,
- Cpblk = 0xfe17,
- Initblk = 0xfe18,
- Rethrow = 0xfe1a,
- Sizeof = 0xfe1c,
- Refanytype = 0xfe1d,
- Readonly_ = 0xfe1e,
-
- // If you add more opcodes here, modify OpCode.Name to handle them correctly
-};
-
-public class OpCodes {
-
-/// <summary>
-/// <para>
-/// The IL instruction opcodes supported by the
-/// runtime. The IL Instruction Specification describes each
-/// Opcode.
-/// </para>
-/// </summary>
-/// <seealso topic='IL Instruction Set Specification'/>
-
- private OpCodes() {
- }
-
- public static readonly OpCode Nop = new OpCode(OpCodeValues.Nop,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Break = new OpCode(OpCodeValues.Break,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Break << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarg_0 = new OpCode(OpCodeValues.Ldarg_0,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarg_1 = new OpCode(OpCodeValues.Ldarg_1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarg_2 = new OpCode(OpCodeValues.Ldarg_2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarg_3 = new OpCode(OpCodeValues.Ldarg_3,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloc_0 = new OpCode(OpCodeValues.Ldloc_0,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloc_1 = new OpCode(OpCodeValues.Ldloc_1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloc_2 = new OpCode(OpCodeValues.Ldloc_2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloc_3 = new OpCode(OpCodeValues.Ldloc_3,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stloc_0 = new OpCode(OpCodeValues.Stloc_0,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stloc_1 = new OpCode(OpCodeValues.Stloc_1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stloc_2 = new OpCode(OpCodeValues.Stloc_2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stloc_3 = new OpCode(OpCodeValues.Stloc_3,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarg_S = new OpCode(OpCodeValues.Ldarg_S,
- ((int)OperandType.ShortInlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarga_S = new OpCode(OpCodeValues.Ldarga_S,
- ((int)OperandType.ShortInlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Starg_S = new OpCode(OpCodeValues.Starg_S,
- ((int)OperandType.ShortInlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloc_S = new OpCode(OpCodeValues.Ldloc_S,
- ((int)OperandType.ShortInlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloca_S = new OpCode(OpCodeValues.Ldloca_S,
- ((int)OperandType.ShortInlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stloc_S = new OpCode(OpCodeValues.Stloc_S,
- ((int)OperandType.ShortInlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldnull = new OpCode(OpCodeValues.Ldnull,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_M1 = new OpCode(OpCodeValues.Ldc_I4_M1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_0 = new OpCode(OpCodeValues.Ldc_I4_0,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_1 = new OpCode(OpCodeValues.Ldc_I4_1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_2 = new OpCode(OpCodeValues.Ldc_I4_2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_3 = new OpCode(OpCodeValues.Ldc_I4_3,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_4 = new OpCode(OpCodeValues.Ldc_I4_4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_5 = new OpCode(OpCodeValues.Ldc_I4_5,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_6 = new OpCode(OpCodeValues.Ldc_I4_6,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_7 = new OpCode(OpCodeValues.Ldc_I4_7,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_8 = new OpCode(OpCodeValues.Ldc_I4_8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4_S = new OpCode(OpCodeValues.Ldc_I4_S,
- ((int)OperandType.ShortInlineI) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I4 = new OpCode(OpCodeValues.Ldc_I4,
- ((int)OperandType.InlineI) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_I8 = new OpCode(OpCodeValues.Ldc_I8,
- ((int)OperandType.InlineI8) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_R4 = new OpCode(OpCodeValues.Ldc_R4,
- ((int)OperandType.ShortInlineR) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldc_R8 = new OpCode(OpCodeValues.Ldc_R8,
- ((int)OperandType.InlineR) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Dup = new OpCode(OpCodeValues.Dup,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1_push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Pop = new OpCode(OpCodeValues.Pop,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Jmp = new OpCode(OpCodeValues.Jmp,
- ((int)OperandType.InlineMethod) |
- ((int)FlowControl.Call << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Call = new OpCode(OpCodeValues.Call,
- ((int)OperandType.InlineMethod) |
- ((int)FlowControl.Call << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Varpush << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Calli = new OpCode(OpCodeValues.Calli,
- ((int)OperandType.InlineSig) |
- ((int)FlowControl.Call << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Varpush << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ret = new OpCode(OpCodeValues.Ret,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Return << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Br_S = new OpCode(OpCodeValues.Br_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Brfalse_S = new OpCode(OpCodeValues.Brfalse_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Brtrue_S = new OpCode(OpCodeValues.Brtrue_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Beq_S = new OpCode(OpCodeValues.Beq_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bge_S = new OpCode(OpCodeValues.Bge_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bgt_S = new OpCode(OpCodeValues.Bgt_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ble_S = new OpCode(OpCodeValues.Ble_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Blt_S = new OpCode(OpCodeValues.Blt_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bne_Un_S = new OpCode(OpCodeValues.Bne_Un_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bge_Un_S = new OpCode(OpCodeValues.Bge_Un_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bgt_Un_S = new OpCode(OpCodeValues.Bgt_Un_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ble_Un_S = new OpCode(OpCodeValues.Ble_Un_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Blt_Un_S = new OpCode(OpCodeValues.Blt_Un_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Br = new OpCode(OpCodeValues.Br,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Brfalse = new OpCode(OpCodeValues.Brfalse,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Brtrue = new OpCode(OpCodeValues.Brtrue,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Beq = new OpCode(OpCodeValues.Beq,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bge = new OpCode(OpCodeValues.Bge,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bgt = new OpCode(OpCodeValues.Bgt,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ble = new OpCode(OpCodeValues.Ble,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Blt = new OpCode(OpCodeValues.Blt,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bne_Un = new OpCode(OpCodeValues.Bne_Un,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bge_Un = new OpCode(OpCodeValues.Bge_Un,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Bgt_Un = new OpCode(OpCodeValues.Bgt_Un,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ble_Un = new OpCode(OpCodeValues.Ble_Un,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Blt_Un = new OpCode(OpCodeValues.Blt_Un,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Switch = new OpCode(OpCodeValues.Switch,
- ((int)OperandType.InlineSwitch) |
- ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_I1 = new OpCode(OpCodeValues.Ldind_I1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_U1 = new OpCode(OpCodeValues.Ldind_U1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_I2 = new OpCode(OpCodeValues.Ldind_I2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_U2 = new OpCode(OpCodeValues.Ldind_U2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_I4 = new OpCode(OpCodeValues.Ldind_I4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_U4 = new OpCode(OpCodeValues.Ldind_U4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_I8 = new OpCode(OpCodeValues.Ldind_I8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_I = new OpCode(OpCodeValues.Ldind_I,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_R4 = new OpCode(OpCodeValues.Ldind_R4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_R8 = new OpCode(OpCodeValues.Ldind_R8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldind_Ref = new OpCode(OpCodeValues.Ldind_Ref,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_Ref = new OpCode(OpCodeValues.Stind_Ref,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_I1 = new OpCode(OpCodeValues.Stind_I1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_I2 = new OpCode(OpCodeValues.Stind_I2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_I4 = new OpCode(OpCodeValues.Stind_I4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_I8 = new OpCode(OpCodeValues.Stind_I8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi8 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_R4 = new OpCode(OpCodeValues.Stind_R4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popr4 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_R8 = new OpCode(OpCodeValues.Stind_R8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popr8 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Add = new OpCode(OpCodeValues.Add,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Sub = new OpCode(OpCodeValues.Sub,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Mul = new OpCode(OpCodeValues.Mul,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Div = new OpCode(OpCodeValues.Div,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Div_Un = new OpCode(OpCodeValues.Div_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Rem = new OpCode(OpCodeValues.Rem,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Rem_Un = new OpCode(OpCodeValues.Rem_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode And = new OpCode(OpCodeValues.And,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Or = new OpCode(OpCodeValues.Or,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Xor = new OpCode(OpCodeValues.Xor,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Shl = new OpCode(OpCodeValues.Shl,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Shr = new OpCode(OpCodeValues.Shr,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Shr_Un = new OpCode(OpCodeValues.Shr_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Neg = new OpCode(OpCodeValues.Neg,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Not = new OpCode(OpCodeValues.Not,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_I1 = new OpCode(OpCodeValues.Conv_I1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_I2 = new OpCode(OpCodeValues.Conv_I2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_I4 = new OpCode(OpCodeValues.Conv_I4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_I8 = new OpCode(OpCodeValues.Conv_I8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_R4 = new OpCode(OpCodeValues.Conv_R4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_R8 = new OpCode(OpCodeValues.Conv_R8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_U4 = new OpCode(OpCodeValues.Conv_U4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_U8 = new OpCode(OpCodeValues.Conv_U8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Callvirt = new OpCode(OpCodeValues.Callvirt,
- ((int)OperandType.InlineMethod) |
- ((int)FlowControl.Call << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Varpush << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Cpobj = new OpCode(OpCodeValues.Cpobj,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldobj = new OpCode(OpCodeValues.Ldobj,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldstr = new OpCode(OpCodeValues.Ldstr,
- ((int)OperandType.InlineString) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Newobj = new OpCode(OpCodeValues.Newobj,
- ((int)OperandType.InlineMethod) |
- ((int)FlowControl.Call << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Castclass = new OpCode(OpCodeValues.Castclass,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Isinst = new OpCode(OpCodeValues.Isinst,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_R_Un = new OpCode(OpCodeValues.Conv_R_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Unbox = new OpCode(OpCodeValues.Unbox,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Throw = new OpCode(OpCodeValues.Throw,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Throw << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldfld = new OpCode(OpCodeValues.Ldfld,
- ((int)OperandType.InlineField) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldflda = new OpCode(OpCodeValues.Ldflda,
- ((int)OperandType.InlineField) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stfld = new OpCode(OpCodeValues.Stfld,
- ((int)OperandType.InlineField) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldsfld = new OpCode(OpCodeValues.Ldsfld,
- ((int)OperandType.InlineField) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldsflda = new OpCode(OpCodeValues.Ldsflda,
- ((int)OperandType.InlineField) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stsfld = new OpCode(OpCodeValues.Stsfld,
- ((int)OperandType.InlineField) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stobj = new OpCode(OpCodeValues.Stobj,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I1_Un = new OpCode(OpCodeValues.Conv_Ovf_I1_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I2_Un = new OpCode(OpCodeValues.Conv_Ovf_I2_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I4_Un = new OpCode(OpCodeValues.Conv_Ovf_I4_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I8_Un = new OpCode(OpCodeValues.Conv_Ovf_I8_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U1_Un = new OpCode(OpCodeValues.Conv_Ovf_U1_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U2_Un = new OpCode(OpCodeValues.Conv_Ovf_U2_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U4_Un = new OpCode(OpCodeValues.Conv_Ovf_U4_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U8_Un = new OpCode(OpCodeValues.Conv_Ovf_U8_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I_Un = new OpCode(OpCodeValues.Conv_Ovf_I_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U_Un = new OpCode(OpCodeValues.Conv_Ovf_U_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Box = new OpCode(OpCodeValues.Box,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Newarr = new OpCode(OpCodeValues.Newarr,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldlen = new OpCode(OpCodeValues.Ldlen,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelema = new OpCode(OpCodeValues.Ldelema,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_I1 = new OpCode(OpCodeValues.Ldelem_I1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_U1 = new OpCode(OpCodeValues.Ldelem_U1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_I2 = new OpCode(OpCodeValues.Ldelem_I2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_U2 = new OpCode(OpCodeValues.Ldelem_U2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_I4 = new OpCode(OpCodeValues.Ldelem_I4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_U4 = new OpCode(OpCodeValues.Ldelem_U4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_I8 = new OpCode(OpCodeValues.Ldelem_I8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_I = new OpCode(OpCodeValues.Ldelem_I,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_R4 = new OpCode(OpCodeValues.Ldelem_R4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_R8 = new OpCode(OpCodeValues.Ldelem_R8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem_Ref = new OpCode(OpCodeValues.Ldelem_Ref,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_I = new OpCode(OpCodeValues.Stelem_I,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_I1 = new OpCode(OpCodeValues.Stelem_I1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_I2 = new OpCode(OpCodeValues.Stelem_I2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_I4 = new OpCode(OpCodeValues.Stelem_I4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_I8 = new OpCode(OpCodeValues.Stelem_I8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popi8 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_R4 = new OpCode(OpCodeValues.Stelem_R4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popr4 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_R8 = new OpCode(OpCodeValues.Stelem_R8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popr8 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem_Ref = new OpCode(OpCodeValues.Stelem_Ref,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldelem = new OpCode(OpCodeValues.Ldelem,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stelem = new OpCode(OpCodeValues.Stelem,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref_popi_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Unbox_Any = new OpCode(OpCodeValues.Unbox_Any,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I1 = new OpCode(OpCodeValues.Conv_Ovf_I1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U1 = new OpCode(OpCodeValues.Conv_Ovf_U1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I2 = new OpCode(OpCodeValues.Conv_Ovf_I2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U2 = new OpCode(OpCodeValues.Conv_Ovf_U2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I4 = new OpCode(OpCodeValues.Conv_Ovf_I4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U4 = new OpCode(OpCodeValues.Conv_Ovf_U4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I8 = new OpCode(OpCodeValues.Conv_Ovf_I8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U8 = new OpCode(OpCodeValues.Conv_Ovf_U8,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Refanyval = new OpCode(OpCodeValues.Refanyval,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ckfinite = new OpCode(OpCodeValues.Ckfinite,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Mkrefany = new OpCode(OpCodeValues.Mkrefany,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldtoken = new OpCode(OpCodeValues.Ldtoken,
- ((int)OperandType.InlineTok) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_U2 = new OpCode(OpCodeValues.Conv_U2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_U1 = new OpCode(OpCodeValues.Conv_U1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_I = new OpCode(OpCodeValues.Conv_I,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_I = new OpCode(OpCodeValues.Conv_Ovf_I,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_Ovf_U = new OpCode(OpCodeValues.Conv_Ovf_U,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Add_Ovf = new OpCode(OpCodeValues.Add_Ovf,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Add_Ovf_Un = new OpCode(OpCodeValues.Add_Ovf_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Mul_Ovf = new OpCode(OpCodeValues.Mul_Ovf,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Mul_Ovf_Un = new OpCode(OpCodeValues.Mul_Ovf_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Sub_Ovf = new OpCode(OpCodeValues.Sub_Ovf,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Sub_Ovf_Un = new OpCode(OpCodeValues.Sub_Ovf_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Endfinally = new OpCode(OpCodeValues.Endfinally,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Return << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Leave = new OpCode(OpCodeValues.Leave,
- ((int)OperandType.InlineBrTarget) |
- ((int)FlowControl.Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Leave_S = new OpCode(OpCodeValues.Leave_S,
- ((int)OperandType.ShortInlineBrTarget) |
- ((int)FlowControl.Branch << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stind_I = new OpCode(OpCodeValues.Stind_I,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (-2 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Conv_U = new OpCode(OpCodeValues.Conv_U,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix7 = new OpCode(OpCodeValues.Prefix7,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix6 = new OpCode(OpCodeValues.Prefix6,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix5 = new OpCode(OpCodeValues.Prefix5,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix4 = new OpCode(OpCodeValues.Prefix4,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix3 = new OpCode(OpCodeValues.Prefix3,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix2 = new OpCode(OpCodeValues.Prefix2,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefix1 = new OpCode(OpCodeValues.Prefix1,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Prefixref = new OpCode(OpCodeValues.Prefixref,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (1 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Arglist = new OpCode(OpCodeValues.Arglist,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ceq = new OpCode(OpCodeValues.Ceq,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Cgt = new OpCode(OpCodeValues.Cgt,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Cgt_Un = new OpCode(OpCodeValues.Cgt_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Clt = new OpCode(OpCodeValues.Clt,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Clt_Un = new OpCode(OpCodeValues.Clt_Un,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldftn = new OpCode(OpCodeValues.Ldftn,
- ((int)OperandType.InlineMethod) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldvirtftn = new OpCode(OpCodeValues.Ldvirtftn,
- ((int)OperandType.InlineMethod) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarg = new OpCode(OpCodeValues.Ldarg,
- ((int)OperandType.InlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldarga = new OpCode(OpCodeValues.Ldarga,
- ((int)OperandType.InlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Starg = new OpCode(OpCodeValues.Starg,
- ((int)OperandType.InlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloc = new OpCode(OpCodeValues.Ldloc,
- ((int)OperandType.InlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Ldloca = new OpCode(OpCodeValues.Ldloca,
- ((int)OperandType.InlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Stloc = new OpCode(OpCodeValues.Stloc,
- ((int)OperandType.InlineVar) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Localloc = new OpCode(OpCodeValues.Localloc,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Endfilter = new OpCode(OpCodeValues.Endfilter,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Return << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Unaligned = new OpCode(OpCodeValues.Unaligned_,
- ((int)OperandType.ShortInlineI) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Volatile = new OpCode(OpCodeValues.Volatile_,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Tailcall = new OpCode(OpCodeValues.Tail_,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Initobj = new OpCode(OpCodeValues.Initobj,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Constrained = new OpCode(OpCodeValues.Constrained_,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Cpblk = new OpCode(OpCodeValues.Cpblk,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Initblk = new OpCode(OpCodeValues.Initblk,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Popi_popi_popi << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (-3 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Rethrow = new OpCode(OpCodeValues.Rethrow,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Throw << OpCode.FlowControlShift) |
- ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- OpCode.EndsUncondJmpBlkFlag |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Sizeof = new OpCode(OpCodeValues.Sizeof,
- ((int)OperandType.InlineType) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (1 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Refanytype = new OpCode(OpCodeValues.Refanytype,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Next << OpCode.FlowControlShift) |
- ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
- public static readonly OpCode Readonly = new OpCode(OpCodeValues.Readonly_,
- ((int)OperandType.InlineNone) |
- ((int)FlowControl.Meta << OpCode.FlowControlShift) |
- ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
- ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
- ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
- (2 << OpCode.SizeShift) |
- (0 << OpCode.StackChangeShift)
- );
-
-
- public static bool TakesSingleByteArgument(OpCode inst)
+namespace System.Reflection.Emit
+{
+ //
+ // Internal enums for opcode values. Note that the value names are used to construct
+ // publicly visible ilasm-compatible opcode names, so their exact form is important!
+ //
+ internal enum OpCodeValues
+ {
+ Nop = 0x00,
+ Break = 0x01,
+ Ldarg_0 = 0x02,
+ Ldarg_1 = 0x03,
+ Ldarg_2 = 0x04,
+ Ldarg_3 = 0x05,
+ Ldloc_0 = 0x06,
+ Ldloc_1 = 0x07,
+ Ldloc_2 = 0x08,
+ Ldloc_3 = 0x09,
+ Stloc_0 = 0x0a,
+ Stloc_1 = 0x0b,
+ Stloc_2 = 0x0c,
+ Stloc_3 = 0x0d,
+ Ldarg_S = 0x0e,
+ Ldarga_S = 0x0f,
+ Starg_S = 0x10,
+ Ldloc_S = 0x11,
+ Ldloca_S = 0x12,
+ Stloc_S = 0x13,
+ Ldnull = 0x14,
+ Ldc_I4_M1 = 0x15,
+ Ldc_I4_0 = 0x16,
+ Ldc_I4_1 = 0x17,
+ Ldc_I4_2 = 0x18,
+ Ldc_I4_3 = 0x19,
+ Ldc_I4_4 = 0x1a,
+ Ldc_I4_5 = 0x1b,
+ Ldc_I4_6 = 0x1c,
+ Ldc_I4_7 = 0x1d,
+ Ldc_I4_8 = 0x1e,
+ Ldc_I4_S = 0x1f,
+ Ldc_I4 = 0x20,
+ Ldc_I8 = 0x21,
+ Ldc_R4 = 0x22,
+ Ldc_R8 = 0x23,
+ Dup = 0x25,
+ Pop = 0x26,
+ Jmp = 0x27,
+ Call = 0x28,
+ Calli = 0x29,
+ Ret = 0x2a,
+ Br_S = 0x2b,
+ Brfalse_S = 0x2c,
+ Brtrue_S = 0x2d,
+ Beq_S = 0x2e,
+ Bge_S = 0x2f,
+ Bgt_S = 0x30,
+ Ble_S = 0x31,
+ Blt_S = 0x32,
+ Bne_Un_S = 0x33,
+ Bge_Un_S = 0x34,
+ Bgt_Un_S = 0x35,
+ Ble_Un_S = 0x36,
+ Blt_Un_S = 0x37,
+ Br = 0x38,
+ Brfalse = 0x39,
+ Brtrue = 0x3a,
+ Beq = 0x3b,
+ Bge = 0x3c,
+ Bgt = 0x3d,
+ Ble = 0x3e,
+ Blt = 0x3f,
+ Bne_Un = 0x40,
+ Bge_Un = 0x41,
+ Bgt_Un = 0x42,
+ Ble_Un = 0x43,
+ Blt_Un = 0x44,
+ Switch = 0x45,
+ Ldind_I1 = 0x46,
+ Ldind_U1 = 0x47,
+ Ldind_I2 = 0x48,
+ Ldind_U2 = 0x49,
+ Ldind_I4 = 0x4a,
+ Ldind_U4 = 0x4b,
+ Ldind_I8 = 0x4c,
+ Ldind_I = 0x4d,
+ Ldind_R4 = 0x4e,
+ Ldind_R8 = 0x4f,
+ Ldind_Ref = 0x50,
+ Stind_Ref = 0x51,
+ Stind_I1 = 0x52,
+ Stind_I2 = 0x53,
+ Stind_I4 = 0x54,
+ Stind_I8 = 0x55,
+ Stind_R4 = 0x56,
+ Stind_R8 = 0x57,
+ Add = 0x58,
+ Sub = 0x59,
+ Mul = 0x5a,
+ Div = 0x5b,
+ Div_Un = 0x5c,
+ Rem = 0x5d,
+ Rem_Un = 0x5e,
+ And = 0x5f,
+ Or = 0x60,
+ Xor = 0x61,
+ Shl = 0x62,
+ Shr = 0x63,
+ Shr_Un = 0x64,
+ Neg = 0x65,
+ Not = 0x66,
+ Conv_I1 = 0x67,
+ Conv_I2 = 0x68,
+ Conv_I4 = 0x69,
+ Conv_I8 = 0x6a,
+ Conv_R4 = 0x6b,
+ Conv_R8 = 0x6c,
+ Conv_U4 = 0x6d,
+ Conv_U8 = 0x6e,
+ Callvirt = 0x6f,
+ Cpobj = 0x70,
+ Ldobj = 0x71,
+ Ldstr = 0x72,
+ Newobj = 0x73,
+ Castclass = 0x74,
+ Isinst = 0x75,
+ Conv_R_Un = 0x76,
+ Unbox = 0x79,
+ Throw = 0x7a,
+ Ldfld = 0x7b,
+ Ldflda = 0x7c,
+ Stfld = 0x7d,
+ Ldsfld = 0x7e,
+ Ldsflda = 0x7f,
+ Stsfld = 0x80,
+ Stobj = 0x81,
+ Conv_Ovf_I1_Un = 0x82,
+ Conv_Ovf_I2_Un = 0x83,
+ Conv_Ovf_I4_Un = 0x84,
+ Conv_Ovf_I8_Un = 0x85,
+ Conv_Ovf_U1_Un = 0x86,
+ Conv_Ovf_U2_Un = 0x87,
+ Conv_Ovf_U4_Un = 0x88,
+ Conv_Ovf_U8_Un = 0x89,
+ Conv_Ovf_I_Un = 0x8a,
+ Conv_Ovf_U_Un = 0x8b,
+ Box = 0x8c,
+ Newarr = 0x8d,
+ Ldlen = 0x8e,
+ Ldelema = 0x8f,
+ Ldelem_I1 = 0x90,
+ Ldelem_U1 = 0x91,
+ Ldelem_I2 = 0x92,
+ Ldelem_U2 = 0x93,
+ Ldelem_I4 = 0x94,
+ Ldelem_U4 = 0x95,
+ Ldelem_I8 = 0x96,
+ Ldelem_I = 0x97,
+ Ldelem_R4 = 0x98,
+ Ldelem_R8 = 0x99,
+ Ldelem_Ref = 0x9a,
+ Stelem_I = 0x9b,
+ Stelem_I1 = 0x9c,
+ Stelem_I2 = 0x9d,
+ Stelem_I4 = 0x9e,
+ Stelem_I8 = 0x9f,
+ Stelem_R4 = 0xa0,
+ Stelem_R8 = 0xa1,
+ Stelem_Ref = 0xa2,
+ Ldelem = 0xa3,
+ Stelem = 0xa4,
+ Unbox_Any = 0xa5,
+ Conv_Ovf_I1 = 0xb3,
+ Conv_Ovf_U1 = 0xb4,
+ Conv_Ovf_I2 = 0xb5,
+ Conv_Ovf_U2 = 0xb6,
+ Conv_Ovf_I4 = 0xb7,
+ Conv_Ovf_U4 = 0xb8,
+ Conv_Ovf_I8 = 0xb9,
+ Conv_Ovf_U8 = 0xba,
+ Refanyval = 0xc2,
+ Ckfinite = 0xc3,
+ Mkrefany = 0xc6,
+ Ldtoken = 0xd0,
+ Conv_U2 = 0xd1,
+ Conv_U1 = 0xd2,
+ Conv_I = 0xd3,
+ Conv_Ovf_I = 0xd4,
+ Conv_Ovf_U = 0xd5,
+ Add_Ovf = 0xd6,
+ Add_Ovf_Un = 0xd7,
+ Mul_Ovf = 0xd8,
+ Mul_Ovf_Un = 0xd9,
+ Sub_Ovf = 0xda,
+ Sub_Ovf_Un = 0xdb,
+ Endfinally = 0xdc,
+ Leave = 0xdd,
+ Leave_S = 0xde,
+ Stind_I = 0xdf,
+ Conv_U = 0xe0,
+ Prefix7 = 0xf8,
+ Prefix6 = 0xf9,
+ Prefix5 = 0xfa,
+ Prefix4 = 0xfb,
+ Prefix3 = 0xfc,
+ Prefix2 = 0xfd,
+ Prefix1 = 0xfe,
+ Prefixref = 0xff,
+ Arglist = 0xfe00,
+ Ceq = 0xfe01,
+ Cgt = 0xfe02,
+ Cgt_Un = 0xfe03,
+ Clt = 0xfe04,
+ Clt_Un = 0xfe05,
+ Ldftn = 0xfe06,
+ Ldvirtftn = 0xfe07,
+ Ldarg = 0xfe09,
+ Ldarga = 0xfe0a,
+ Starg = 0xfe0b,
+ Ldloc = 0xfe0c,
+ Ldloca = 0xfe0d,
+ Stloc = 0xfe0e,
+ Localloc = 0xfe0f,
+ Endfilter = 0xfe11,
+ Unaligned_ = 0xfe12,
+ Volatile_ = 0xfe13,
+ Tail_ = 0xfe14,
+ Initobj = 0xfe15,
+ Constrained_ = 0xfe16,
+ Cpblk = 0xfe17,
+ Initblk = 0xfe18,
+ Rethrow = 0xfe1a,
+ Sizeof = 0xfe1c,
+ Refanytype = 0xfe1d,
+ Readonly_ = 0xfe1e,
+
+ // If you add more opcodes here, modify OpCode.Name to handle them correctly
+ };
+
+ public class OpCodes
{
- switch (inst.OperandType)
+ /// <summary>
+ /// <para>
+ /// The IL instruction opcodes supported by the
+ /// runtime. The IL Instruction Specification describes each
+ /// Opcode.
+ /// </para>
+ /// </summary>
+ /// <seealso topic='IL Instruction Set Specification'/>
+
+ private OpCodes()
{
- case OperandType.ShortInlineBrTarget :
- case OperandType.ShortInlineI :
- case OperandType.ShortInlineVar :
- return true;
- };
- return false;
+ }
+
+ public static readonly OpCode Nop = new OpCode(OpCodeValues.Nop,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Break = new OpCode(OpCodeValues.Break,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Break << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarg_0 = new OpCode(OpCodeValues.Ldarg_0,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarg_1 = new OpCode(OpCodeValues.Ldarg_1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarg_2 = new OpCode(OpCodeValues.Ldarg_2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarg_3 = new OpCode(OpCodeValues.Ldarg_3,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloc_0 = new OpCode(OpCodeValues.Ldloc_0,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloc_1 = new OpCode(OpCodeValues.Ldloc_1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloc_2 = new OpCode(OpCodeValues.Ldloc_2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloc_3 = new OpCode(OpCodeValues.Ldloc_3,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stloc_0 = new OpCode(OpCodeValues.Stloc_0,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stloc_1 = new OpCode(OpCodeValues.Stloc_1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stloc_2 = new OpCode(OpCodeValues.Stloc_2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stloc_3 = new OpCode(OpCodeValues.Stloc_3,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarg_S = new OpCode(OpCodeValues.Ldarg_S,
+ ((int)OperandType.ShortInlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarga_S = new OpCode(OpCodeValues.Ldarga_S,
+ ((int)OperandType.ShortInlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Starg_S = new OpCode(OpCodeValues.Starg_S,
+ ((int)OperandType.ShortInlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloc_S = new OpCode(OpCodeValues.Ldloc_S,
+ ((int)OperandType.ShortInlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloca_S = new OpCode(OpCodeValues.Ldloca_S,
+ ((int)OperandType.ShortInlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stloc_S = new OpCode(OpCodeValues.Stloc_S,
+ ((int)OperandType.ShortInlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldnull = new OpCode(OpCodeValues.Ldnull,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_M1 = new OpCode(OpCodeValues.Ldc_I4_M1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_0 = new OpCode(OpCodeValues.Ldc_I4_0,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_1 = new OpCode(OpCodeValues.Ldc_I4_1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_2 = new OpCode(OpCodeValues.Ldc_I4_2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_3 = new OpCode(OpCodeValues.Ldc_I4_3,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_4 = new OpCode(OpCodeValues.Ldc_I4_4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_5 = new OpCode(OpCodeValues.Ldc_I4_5,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_6 = new OpCode(OpCodeValues.Ldc_I4_6,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_7 = new OpCode(OpCodeValues.Ldc_I4_7,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_8 = new OpCode(OpCodeValues.Ldc_I4_8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4_S = new OpCode(OpCodeValues.Ldc_I4_S,
+ ((int)OperandType.ShortInlineI) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I4 = new OpCode(OpCodeValues.Ldc_I4,
+ ((int)OperandType.InlineI) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_I8 = new OpCode(OpCodeValues.Ldc_I8,
+ ((int)OperandType.InlineI8) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_R4 = new OpCode(OpCodeValues.Ldc_R4,
+ ((int)OperandType.ShortInlineR) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldc_R8 = new OpCode(OpCodeValues.Ldc_R8,
+ ((int)OperandType.InlineR) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Dup = new OpCode(OpCodeValues.Dup,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1_push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Pop = new OpCode(OpCodeValues.Pop,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Jmp = new OpCode(OpCodeValues.Jmp,
+ ((int)OperandType.InlineMethod) |
+ ((int)FlowControl.Call << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Call = new OpCode(OpCodeValues.Call,
+ ((int)OperandType.InlineMethod) |
+ ((int)FlowControl.Call << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Varpush << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Calli = new OpCode(OpCodeValues.Calli,
+ ((int)OperandType.InlineSig) |
+ ((int)FlowControl.Call << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Varpush << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ret = new OpCode(OpCodeValues.Ret,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Return << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Br_S = new OpCode(OpCodeValues.Br_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Brfalse_S = new OpCode(OpCodeValues.Brfalse_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Brtrue_S = new OpCode(OpCodeValues.Brtrue_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Beq_S = new OpCode(OpCodeValues.Beq_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bge_S = new OpCode(OpCodeValues.Bge_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bgt_S = new OpCode(OpCodeValues.Bgt_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ble_S = new OpCode(OpCodeValues.Ble_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Blt_S = new OpCode(OpCodeValues.Blt_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bne_Un_S = new OpCode(OpCodeValues.Bne_Un_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bge_Un_S = new OpCode(OpCodeValues.Bge_Un_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bgt_Un_S = new OpCode(OpCodeValues.Bgt_Un_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ble_Un_S = new OpCode(OpCodeValues.Ble_Un_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Blt_Un_S = new OpCode(OpCodeValues.Blt_Un_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Br = new OpCode(OpCodeValues.Br,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Brfalse = new OpCode(OpCodeValues.Brfalse,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Brtrue = new OpCode(OpCodeValues.Brtrue,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Beq = new OpCode(OpCodeValues.Beq,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bge = new OpCode(OpCodeValues.Bge,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bgt = new OpCode(OpCodeValues.Bgt,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ble = new OpCode(OpCodeValues.Ble,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Blt = new OpCode(OpCodeValues.Blt,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bne_Un = new OpCode(OpCodeValues.Bne_Un,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bge_Un = new OpCode(OpCodeValues.Bge_Un,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Bgt_Un = new OpCode(OpCodeValues.Bgt_Un,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ble_Un = new OpCode(OpCodeValues.Ble_Un,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Blt_Un = new OpCode(OpCodeValues.Blt_Un,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Macro << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Switch = new OpCode(OpCodeValues.Switch,
+ ((int)OperandType.InlineSwitch) |
+ ((int)FlowControl.Cond_Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_I1 = new OpCode(OpCodeValues.Ldind_I1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_U1 = new OpCode(OpCodeValues.Ldind_U1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_I2 = new OpCode(OpCodeValues.Ldind_I2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_U2 = new OpCode(OpCodeValues.Ldind_U2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_I4 = new OpCode(OpCodeValues.Ldind_I4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_U4 = new OpCode(OpCodeValues.Ldind_U4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_I8 = new OpCode(OpCodeValues.Ldind_I8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_I = new OpCode(OpCodeValues.Ldind_I,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_R4 = new OpCode(OpCodeValues.Ldind_R4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_R8 = new OpCode(OpCodeValues.Ldind_R8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldind_Ref = new OpCode(OpCodeValues.Ldind_Ref,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_Ref = new OpCode(OpCodeValues.Stind_Ref,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_I1 = new OpCode(OpCodeValues.Stind_I1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_I2 = new OpCode(OpCodeValues.Stind_I2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_I4 = new OpCode(OpCodeValues.Stind_I4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_I8 = new OpCode(OpCodeValues.Stind_I8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi8 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_R4 = new OpCode(OpCodeValues.Stind_R4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popr4 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_R8 = new OpCode(OpCodeValues.Stind_R8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popr8 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Add = new OpCode(OpCodeValues.Add,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Sub = new OpCode(OpCodeValues.Sub,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Mul = new OpCode(OpCodeValues.Mul,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Div = new OpCode(OpCodeValues.Div,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Div_Un = new OpCode(OpCodeValues.Div_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Rem = new OpCode(OpCodeValues.Rem,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Rem_Un = new OpCode(OpCodeValues.Rem_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode And = new OpCode(OpCodeValues.And,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Or = new OpCode(OpCodeValues.Or,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Xor = new OpCode(OpCodeValues.Xor,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Shl = new OpCode(OpCodeValues.Shl,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Shr = new OpCode(OpCodeValues.Shr,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Shr_Un = new OpCode(OpCodeValues.Shr_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Neg = new OpCode(OpCodeValues.Neg,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Not = new OpCode(OpCodeValues.Not,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_I1 = new OpCode(OpCodeValues.Conv_I1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_I2 = new OpCode(OpCodeValues.Conv_I2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_I4 = new OpCode(OpCodeValues.Conv_I4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_I8 = new OpCode(OpCodeValues.Conv_I8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_R4 = new OpCode(OpCodeValues.Conv_R4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_R8 = new OpCode(OpCodeValues.Conv_R8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_U4 = new OpCode(OpCodeValues.Conv_U4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_U8 = new OpCode(OpCodeValues.Conv_U8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Callvirt = new OpCode(OpCodeValues.Callvirt,
+ ((int)OperandType.InlineMethod) |
+ ((int)FlowControl.Call << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Varpush << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Cpobj = new OpCode(OpCodeValues.Cpobj,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldobj = new OpCode(OpCodeValues.Ldobj,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldstr = new OpCode(OpCodeValues.Ldstr,
+ ((int)OperandType.InlineString) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Newobj = new OpCode(OpCodeValues.Newobj,
+ ((int)OperandType.InlineMethod) |
+ ((int)FlowControl.Call << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Varpop << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Castclass = new OpCode(OpCodeValues.Castclass,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Isinst = new OpCode(OpCodeValues.Isinst,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_R_Un = new OpCode(OpCodeValues.Conv_R_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Unbox = new OpCode(OpCodeValues.Unbox,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Throw = new OpCode(OpCodeValues.Throw,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Throw << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldfld = new OpCode(OpCodeValues.Ldfld,
+ ((int)OperandType.InlineField) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldflda = new OpCode(OpCodeValues.Ldflda,
+ ((int)OperandType.InlineField) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stfld = new OpCode(OpCodeValues.Stfld,
+ ((int)OperandType.InlineField) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldsfld = new OpCode(OpCodeValues.Ldsfld,
+ ((int)OperandType.InlineField) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldsflda = new OpCode(OpCodeValues.Ldsflda,
+ ((int)OperandType.InlineField) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stsfld = new OpCode(OpCodeValues.Stsfld,
+ ((int)OperandType.InlineField) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stobj = new OpCode(OpCodeValues.Stobj,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I1_Un = new OpCode(OpCodeValues.Conv_Ovf_I1_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I2_Un = new OpCode(OpCodeValues.Conv_Ovf_I2_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I4_Un = new OpCode(OpCodeValues.Conv_Ovf_I4_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I8_Un = new OpCode(OpCodeValues.Conv_Ovf_I8_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U1_Un = new OpCode(OpCodeValues.Conv_Ovf_U1_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U2_Un = new OpCode(OpCodeValues.Conv_Ovf_U2_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U4_Un = new OpCode(OpCodeValues.Conv_Ovf_U4_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U8_Un = new OpCode(OpCodeValues.Conv_Ovf_U8_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I_Un = new OpCode(OpCodeValues.Conv_Ovf_I_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U_Un = new OpCode(OpCodeValues.Conv_Ovf_U_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Box = new OpCode(OpCodeValues.Box,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Newarr = new OpCode(OpCodeValues.Newarr,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldlen = new OpCode(OpCodeValues.Ldlen,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelema = new OpCode(OpCodeValues.Ldelema,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_I1 = new OpCode(OpCodeValues.Ldelem_I1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_U1 = new OpCode(OpCodeValues.Ldelem_U1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_I2 = new OpCode(OpCodeValues.Ldelem_I2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_U2 = new OpCode(OpCodeValues.Ldelem_U2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_I4 = new OpCode(OpCodeValues.Ldelem_I4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_U4 = new OpCode(OpCodeValues.Ldelem_U4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_I8 = new OpCode(OpCodeValues.Ldelem_I8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_I = new OpCode(OpCodeValues.Ldelem_I,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_R4 = new OpCode(OpCodeValues.Ldelem_R4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr4 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_R8 = new OpCode(OpCodeValues.Ldelem_R8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem_Ref = new OpCode(OpCodeValues.Ldelem_Ref,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushref << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_I = new OpCode(OpCodeValues.Stelem_I,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_I1 = new OpCode(OpCodeValues.Stelem_I1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_I2 = new OpCode(OpCodeValues.Stelem_I2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_I4 = new OpCode(OpCodeValues.Stelem_I4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_I8 = new OpCode(OpCodeValues.Stelem_I8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popi8 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_R4 = new OpCode(OpCodeValues.Stelem_R4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popr4 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_R8 = new OpCode(OpCodeValues.Stelem_R8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popr8 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem_Ref = new OpCode(OpCodeValues.Stelem_Ref,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldelem = new OpCode(OpCodeValues.Ldelem,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stelem = new OpCode(OpCodeValues.Stelem,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref_popi_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Unbox_Any = new OpCode(OpCodeValues.Unbox_Any,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I1 = new OpCode(OpCodeValues.Conv_Ovf_I1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U1 = new OpCode(OpCodeValues.Conv_Ovf_U1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I2 = new OpCode(OpCodeValues.Conv_Ovf_I2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U2 = new OpCode(OpCodeValues.Conv_Ovf_U2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I4 = new OpCode(OpCodeValues.Conv_Ovf_I4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U4 = new OpCode(OpCodeValues.Conv_Ovf_U4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I8 = new OpCode(OpCodeValues.Conv_Ovf_I8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U8 = new OpCode(OpCodeValues.Conv_Ovf_U8,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Refanyval = new OpCode(OpCodeValues.Refanyval,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ckfinite = new OpCode(OpCodeValues.Ckfinite,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushr8 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Mkrefany = new OpCode(OpCodeValues.Mkrefany,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldtoken = new OpCode(OpCodeValues.Ldtoken,
+ ((int)OperandType.InlineTok) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_U2 = new OpCode(OpCodeValues.Conv_U2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_U1 = new OpCode(OpCodeValues.Conv_U1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_I = new OpCode(OpCodeValues.Conv_I,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_I = new OpCode(OpCodeValues.Conv_Ovf_I,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_Ovf_U = new OpCode(OpCodeValues.Conv_Ovf_U,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Add_Ovf = new OpCode(OpCodeValues.Add_Ovf,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Add_Ovf_Un = new OpCode(OpCodeValues.Add_Ovf_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Mul_Ovf = new OpCode(OpCodeValues.Mul_Ovf,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Mul_Ovf_Un = new OpCode(OpCodeValues.Mul_Ovf_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Sub_Ovf = new OpCode(OpCodeValues.Sub_Ovf,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Sub_Ovf_Un = new OpCode(OpCodeValues.Sub_Ovf_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Endfinally = new OpCode(OpCodeValues.Endfinally,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Return << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Leave = new OpCode(OpCodeValues.Leave,
+ ((int)OperandType.InlineBrTarget) |
+ ((int)FlowControl.Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Leave_S = new OpCode(OpCodeValues.Leave_S,
+ ((int)OperandType.ShortInlineBrTarget) |
+ ((int)FlowControl.Branch << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stind_I = new OpCode(OpCodeValues.Stind_I,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (-2 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Conv_U = new OpCode(OpCodeValues.Conv_U,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix7 = new OpCode(OpCodeValues.Prefix7,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix6 = new OpCode(OpCodeValues.Prefix6,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix5 = new OpCode(OpCodeValues.Prefix5,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix4 = new OpCode(OpCodeValues.Prefix4,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix3 = new OpCode(OpCodeValues.Prefix3,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix2 = new OpCode(OpCodeValues.Prefix2,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefix1 = new OpCode(OpCodeValues.Prefix1,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Prefixref = new OpCode(OpCodeValues.Prefixref,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Nternal << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (1 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Arglist = new OpCode(OpCodeValues.Arglist,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ceq = new OpCode(OpCodeValues.Ceq,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Cgt = new OpCode(OpCodeValues.Cgt,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Cgt_Un = new OpCode(OpCodeValues.Cgt_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Clt = new OpCode(OpCodeValues.Clt,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Clt_Un = new OpCode(OpCodeValues.Clt_Un,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1_pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldftn = new OpCode(OpCodeValues.Ldftn,
+ ((int)OperandType.InlineMethod) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldvirtftn = new OpCode(OpCodeValues.Ldvirtftn,
+ ((int)OperandType.InlineMethod) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popref << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarg = new OpCode(OpCodeValues.Ldarg,
+ ((int)OperandType.InlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldarga = new OpCode(OpCodeValues.Ldarga,
+ ((int)OperandType.InlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Starg = new OpCode(OpCodeValues.Starg,
+ ((int)OperandType.InlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloc = new OpCode(OpCodeValues.Ldloc,
+ ((int)OperandType.InlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push1 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Ldloca = new OpCode(OpCodeValues.Ldloca,
+ ((int)OperandType.InlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Stloc = new OpCode(OpCodeValues.Stloc,
+ ((int)OperandType.InlineVar) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Localloc = new OpCode(OpCodeValues.Localloc,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Endfilter = new OpCode(OpCodeValues.Endfilter,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Return << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Unaligned = new OpCode(OpCodeValues.Unaligned_,
+ ((int)OperandType.ShortInlineI) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Volatile = new OpCode(OpCodeValues.Volatile_,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Tailcall = new OpCode(OpCodeValues.Tail_,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Initobj = new OpCode(OpCodeValues.Initobj,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Constrained = new OpCode(OpCodeValues.Constrained_,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Cpblk = new OpCode(OpCodeValues.Cpblk,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Initblk = new OpCode(OpCodeValues.Initblk,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Popi_popi_popi << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (-3 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Rethrow = new OpCode(OpCodeValues.Rethrow,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Throw << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Objmodel << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ OpCode.EndsUncondJmpBlkFlag |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Sizeof = new OpCode(OpCodeValues.Sizeof,
+ ((int)OperandType.InlineType) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (1 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Refanytype = new OpCode(OpCodeValues.Refanytype,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Next << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Primitive << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop1 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Pushi << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+ public static readonly OpCode Readonly = new OpCode(OpCodeValues.Readonly_,
+ ((int)OperandType.InlineNone) |
+ ((int)FlowControl.Meta << OpCode.FlowControlShift) |
+ ((int)OpCodeType.Prefix << OpCode.OpCodeTypeShift) |
+ ((int)StackBehaviour.Pop0 << OpCode.StackBehaviourPopShift) |
+ ((int)StackBehaviour.Push0 << OpCode.StackBehaviourPushShift) |
+ (2 << OpCode.SizeShift) |
+ (0 << OpCode.StackChangeShift)
+ );
+
+
+ public static bool TakesSingleByteArgument(OpCode inst)
+ {
+ switch (inst.OperandType)
+ {
+ case OperandType.ShortInlineBrTarget:
+ case OperandType.ShortInlineI:
+ case OperandType.ShortInlineVar:
+ return true;
+ };
+ return false;
+ }
}
}
-}
diff --git a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
index 74a9de16b6..37768be9d7 100644
--- a/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/Opcode.cs
@@ -2,191 +2,196 @@
// 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.Emit {
using System;
using System.Threading;
using System.Diagnostics.Contracts;
-public struct OpCode
+namespace System.Reflection.Emit
{
- //
- // Use packed bitfield for flags to avoid code bloat
- //
-
- internal const int OperandTypeMask = 0x1F; // 000000000000000000000000000XXXXX
-
- internal const int FlowControlShift = 5; // 00000000000000000000000XXXX00000
- internal const int FlowControlMask = 0x0F;
+ public struct OpCode
+ {
+ //
+ // Use packed bitfield for flags to avoid code bloat
+ //
- internal const int OpCodeTypeShift = 9; // 00000000000000000000XXX000000000
- internal const int OpCodeTypeMask = 0x07;
+ internal const int OperandTypeMask = 0x1F; // 000000000000000000000000000XXXXX
- internal const int StackBehaviourPopShift = 12; // 000000000000000XXXXX000000000000
- internal const int StackBehaviourPushShift = 17; // 0000000000XXXXX00000000000000000
- internal const int StackBehaviourMask = 0x1F;
+ internal const int FlowControlShift = 5; // 00000000000000000000000XXXX00000
+ internal const int FlowControlMask = 0x0F;
- internal const int SizeShift = 22; // 00000000XX0000000000000000000000
- internal const int SizeMask = 0x03;
+ internal const int OpCodeTypeShift = 9; // 00000000000000000000XXX000000000
+ internal const int OpCodeTypeMask = 0x07;
- internal const int EndsUncondJmpBlkFlag = 0x01000000; // 0000000X000000000000000000000000
+ internal const int StackBehaviourPopShift = 12; // 000000000000000XXXXX000000000000
+ internal const int StackBehaviourPushShift = 17; // 0000000000XXXXX00000000000000000
+ internal const int StackBehaviourMask = 0x1F;
- // unused // 0000XXX0000000000000000000000000
+ internal const int SizeShift = 22; // 00000000XX0000000000000000000000
+ internal const int SizeMask = 0x03;
- internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000
+ internal const int EndsUncondJmpBlkFlag = 0x01000000; // 0000000X000000000000000000000000
- private OpCodeValues m_value;
- private int m_flags;
+ // unused // 0000XXX0000000000000000000000000
- internal OpCode(OpCodeValues value, int flags)
- {
- m_value = value;
- m_flags = flags;
- }
+ internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000
- internal bool EndsUncondJmpBlk()
- {
- return (m_flags & EndsUncondJmpBlkFlag) != 0;
- }
-
- internal int StackChange()
- {
- return (m_flags >> StackChangeShift);
- }
+ private OpCodeValues m_value;
+ private int m_flags;
- public OperandType OperandType
- {
- get
+ internal OpCode(OpCodeValues value, int flags)
{
- return (OperandType)(m_flags & OperandTypeMask);
+ m_value = value;
+ m_flags = flags;
}
- }
- public FlowControl FlowControl
- {
- get
+ internal bool EndsUncondJmpBlk()
{
- return (FlowControl)((m_flags >> FlowControlShift) & FlowControlMask);
+ return (m_flags & EndsUncondJmpBlkFlag) != 0;
}
- }
- public OpCodeType OpCodeType
- {
- get
+ internal int StackChange()
{
- return (OpCodeType)((m_flags >> OpCodeTypeShift) & OpCodeTypeMask);
+ return (m_flags >> StackChangeShift);
}
- }
- public StackBehaviour StackBehaviourPop
- {
- get
+ public OperandType OperandType
{
- return (StackBehaviour)((m_flags >> StackBehaviourPopShift) & StackBehaviourMask);
+ get
+ {
+ return (OperandType)(m_flags & OperandTypeMask);
+ }
}
- }
- public StackBehaviour StackBehaviourPush
- {
- get
+ public FlowControl FlowControl
{
- return (StackBehaviour)((m_flags >> StackBehaviourPushShift) & StackBehaviourMask);
+ get
+ {
+ return (FlowControl)((m_flags >> FlowControlShift) & FlowControlMask);
+ }
}
- }
- public int Size
- {
- get
+ public OpCodeType OpCodeType
{
- return (m_flags >> SizeShift) & SizeMask;
+ get
+ {
+ return (OpCodeType)((m_flags >> OpCodeTypeShift) & OpCodeTypeMask);
+ }
}
- }
- public short Value
- {
- get
+ public StackBehaviour StackBehaviourPop
{
- return (short)m_value;
+ get
+ {
+ return (StackBehaviour)((m_flags >> StackBehaviourPopShift) & StackBehaviourMask);
+ }
}
- }
- private static volatile string[] g_nameCache;
+ public StackBehaviour StackBehaviourPush
+ {
+ get
+ {
+ return (StackBehaviour)((m_flags >> StackBehaviourPushShift) & StackBehaviourMask);
+ }
+ }
- public String Name
- {
- get
+ public int Size
{
- if (Size == 0)
- return null;
+ get
+ {
+ return (m_flags >> SizeShift) & SizeMask;
+ }
+ }
- // Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.)
- // Note that we do not any locks here because of we always get the same names. The last one wins.
- string[] nameCache = g_nameCache;
- if (nameCache == null) {
- nameCache = new String[0x11f];
- g_nameCache = nameCache;
+ public short Value
+ {
+ get
+ {
+ return (short)m_value;
}
+ }
- OpCodeValues opCodeValue = (OpCodeValues)(ushort)Value;
+ private static volatile string[] g_nameCache;
- int idx = (int)opCodeValue;
- if (idx > 0xFF) {
- if (idx >= 0xfe00 && idx <= 0xfe1e) {
- // Transform two byte opcode value to lower range that's suitable
- // for array index
- idx = 0x100 + (idx - 0xfe00);
- }
- else {
- // Unknown opcode
+ public String Name
+ {
+ get
+ {
+ if (Size == 0)
return null;
+
+ // Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.)
+ // Note that we do not any locks here because of we always get the same names. The last one wins.
+ string[] nameCache = g_nameCache;
+ if (nameCache == null)
+ {
+ nameCache = new String[0x11f];
+ g_nameCache = nameCache;
}
- }
- String name = Volatile.Read(ref nameCache[idx]);
- if (name != null)
- return name;
+ OpCodeValues opCodeValue = (OpCodeValues)(ushort)Value;
+
+ int idx = (int)opCodeValue;
+ if (idx > 0xFF)
+ {
+ if (idx >= 0xfe00 && idx <= 0xfe1e)
+ {
+ // Transform two byte opcode value to lower range that's suitable
+ // for array index
+ idx = 0x100 + (idx - 0xfe00);
+ }
+ else
+ {
+ // Unknown opcode
+ return null;
+ }
+ }
- // Create ilasm style name from the enum value name.
- name = Enum.GetName(typeof(OpCodeValues), opCodeValue).ToLowerInvariant().Replace("_", ".");
- Volatile.Write(ref nameCache[idx], name);
- return name;
+ String name = Volatile.Read(ref nameCache[idx]);
+ if (name != null)
+ return name;
+
+ // Create ilasm style name from the enum value name.
+ name = Enum.GetName(typeof(OpCodeValues), opCodeValue).ToLowerInvariant().Replace("_", ".");
+ Volatile.Write(ref nameCache[idx], name);
+ return name;
+ }
}
- }
- [Pure]
- public override bool Equals(Object obj)
- {
- if (obj is OpCode)
- return Equals((OpCode)obj);
- else
- return false;
- }
+ [Pure]
+ public override bool Equals(Object obj)
+ {
+ if (obj is OpCode)
+ return Equals((OpCode)obj);
+ else
+ return false;
+ }
- [Pure]
- public bool Equals(OpCode obj)
- {
- return obj.Value == Value;
- }
+ [Pure]
+ public bool Equals(OpCode obj)
+ {
+ return obj.Value == Value;
+ }
- [Pure]
- public static bool operator ==(OpCode a, OpCode b)
- {
- return a.Equals(b);
- }
+ [Pure]
+ public static bool operator ==(OpCode a, OpCode b)
+ {
+ return a.Equals(b);
+ }
- [Pure]
- public static bool operator !=(OpCode a, OpCode b)
- {
- return !(a == b);
- }
+ [Pure]
+ public static bool operator !=(OpCode a, OpCode b)
+ {
+ return !(a == b);
+ }
- public override int GetHashCode()
- {
- return Value;
- }
+ public override int GetHashCode()
+ {
+ return Value;
+ }
- public override String ToString()
- {
- return Name;
+ public override String ToString()
+ {
+ return Name;
+ }
}
}
-}
diff --git a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
index 87dea058e5..2363d607fc 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OpcodeType.cs
@@ -12,20 +12,20 @@
** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND!
** See opcodegen.pl for more information.**
============================================================*/
-namespace System.Reflection.Emit {
using System;
-[Serializable]
-public enum OpCodeType
+namespace System.Reflection.Emit
{
-
- [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- Annotation = 0,
- Macro = 1,
- Nternal = 2,
- Objmodel = 3,
- Prefix = 4,
- Primitive = 5,
-}
+ [Serializable]
+ public enum OpCodeType
+ {
+ [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
+ Annotation = 0,
+ Macro = 1,
+ Nternal = 2,
+ Objmodel = 3,
+ Prefix = 4,
+ Primitive = 5,
+ }
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
index e972e8603d..033539b999 100644
--- a/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/OperandType.cs
@@ -12,32 +12,32 @@
** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND!
** See opcodegen.pl for more information.**
============================================================*/
-namespace System.Reflection.Emit {
using System;
-[Serializable]
-public enum OperandType
+namespace System.Reflection.Emit
{
-
- InlineBrTarget = 0,
- InlineField = 1,
- InlineI = 2,
- InlineI8 = 3,
- InlineMethod = 4,
- InlineNone = 5,
- [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
- InlinePhi = 6,
- InlineR = 7,
- InlineSig = 9,
- InlineString = 10,
- InlineSwitch = 11,
- InlineTok = 12,
- InlineType = 13,
- InlineVar = 14,
- ShortInlineBrTarget = 15,
- ShortInlineI = 16,
- ShortInlineR = 17,
- ShortInlineVar = 18,
-}
+ [Serializable]
+ public enum OperandType
+ {
+ InlineBrTarget = 0,
+ InlineField = 1,
+ InlineI = 2,
+ InlineI8 = 3,
+ InlineMethod = 4,
+ InlineNone = 5,
+ [Obsolete("This API has been deprecated. http://go.microsoft.com/fwlink/?linkid=14202")]
+ InlinePhi = 6,
+ InlineR = 7,
+ InlineSig = 9,
+ InlineString = 10,
+ InlineSwitch = 11,
+ InlineTok = 12,
+ InlineType = 13,
+ InlineVar = 14,
+ ShortInlineBrTarget = 15,
+ ShortInlineI = 16,
+ ShortInlineR = 17,
+ ShortInlineVar = 18,
+ }
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
index 531ff41dd7..f9246fce6d 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PEFileKinds.cs
@@ -2,14 +2,16 @@
// 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.Emit {
-
- using System;
+
+using System;
+
+namespace System.Reflection.Emit
+{
// This Enum matchs the CorFieldAttr defined in CorHdr.h
[Serializable]
public enum PEFileKinds
{
- Dll = 0x0001,
+ Dll = 0x0001,
ConsoleApplication = 0x0002,
WindowApplication = 0x0003,
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
index 1b3babf595..636825956a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ParameterBuilder.cs
@@ -12,17 +12,18 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
- using System.Runtime.InteropServices;
- using System;
- using System.Reflection;
- using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System;
+using System.Reflection;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection.Emit
+{
public class ParameterBuilder
{
-
// Set the default value of the parameter
- public virtual void SetConstant(Object defaultValue)
+ public virtual void SetConstant(Object defaultValue)
{
TypeBuilder.SetConstantValue(
m_methodBuilder.GetModuleBuilder(),
@@ -30,7 +31,7 @@ namespace System.Reflection.Emit {
m_iPosition == 0 ? m_methodBuilder.ReturnType : m_methodBuilder.m_parameterTypes[m_iPosition - 1],
defaultValue);
}
-
+
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
@@ -44,7 +45,7 @@ namespace System.Reflection.Emit {
TypeBuilder.DefineCustomAttribute(
m_methodBuilder.GetModuleBuilder(),
m_pdToken.Token,
- ((ModuleBuilder )m_methodBuilder.GetModule()).GetConstructorToken(con).Token,
+ ((ModuleBuilder)m_methodBuilder.GetModule()).GetConstructorToken(con).Token,
binaryAttribute,
false, false);
}
@@ -57,65 +58,71 @@ namespace System.Reflection.Emit {
throw new ArgumentNullException(nameof(customBuilder));
}
Contract.EndContractBlock();
- customBuilder.CreateCustomAttribute((ModuleBuilder) (m_methodBuilder .GetModule()), m_pdToken.Token);
+ customBuilder.CreateCustomAttribute((ModuleBuilder)(m_methodBuilder.GetModule()), m_pdToken.Token);
}
-
+
//*******************************
// Make a private constructor so these cannot be constructed externally.
//*******************************
- private ParameterBuilder() {}
+ private ParameterBuilder() { }
internal ParameterBuilder(
- MethodBuilder methodBuilder,
- int sequence,
- ParameterAttributes attributes,
- String strParamName) // can be NULL string
+ MethodBuilder methodBuilder,
+ int sequence,
+ ParameterAttributes attributes,
+ String strParamName) // can be NULL string
{
m_iPosition = sequence;
m_strParamName = strParamName;
m_methodBuilder = methodBuilder;
m_strParamName = strParamName;
m_attributes = attributes;
- m_pdToken = new ParameterToken( TypeBuilder.SetParamInfo(
+ m_pdToken = new ParameterToken(TypeBuilder.SetParamInfo(
m_methodBuilder.GetModuleBuilder().GetNativeHandle(),
- m_methodBuilder.GetToken().Token,
- sequence,
- attributes,
+ m_methodBuilder.GetToken().Token,
+ sequence,
+ attributes,
strParamName));
}
-
+
public virtual ParameterToken GetToken()
{
return m_pdToken;
- }
-
- public virtual String Name {
- get {return m_strParamName;}
}
-
- public virtual int Position {
- get {return m_iPosition;}
+
+ public virtual String Name
+ {
+ get { return m_strParamName; }
+ }
+
+ public virtual int Position
+ {
+ get { return m_iPosition; }
}
-
- public virtual int Attributes {
- get {return (int) m_attributes;}
+
+ public virtual int Attributes
+ {
+ get { return (int)m_attributes; }
}
-
- public bool IsIn {
- get {return ((m_attributes & ParameterAttributes.In) != 0);}
+
+ public bool IsIn
+ {
+ get { return ((m_attributes & ParameterAttributes.In) != 0); }
}
- public bool IsOut {
- get {return ((m_attributes & ParameterAttributes.Out) != 0);}
+ public bool IsOut
+ {
+ get { return ((m_attributes & ParameterAttributes.Out) != 0); }
}
- public bool IsOptional {
- get {return ((m_attributes & ParameterAttributes.Optional) != 0);}
+ public bool IsOptional
+ {
+ get { return ((m_attributes & ParameterAttributes.Optional) != 0); }
}
-
- private String m_strParamName;
- private int m_iPosition;
+
+ private String m_strParamName;
+ private int m_iPosition;
private ParameterAttributes m_attributes;
- private MethodBuilder m_methodBuilder;
- private ParameterToken m_pdToken;
+ private MethodBuilder m_methodBuilder;
+ private ParameterToken m_pdToken;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
index a4a32a51fb..42f85af464 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ParameterToken.cs
@@ -12,33 +12,36 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
// The ParameterToken class is an opaque representation of the Token returned
// by the Metadata to represent the parameter.
[Serializable]
- public struct ParameterToken {
-
+ public struct ParameterToken
+ {
public static readonly ParameterToken Empty = new ParameterToken();
internal int m_tkParameter;
-
-
- internal ParameterToken(int tkParam) {
+
+
+ internal ParameterToken(int tkParam)
+ {
m_tkParameter = tkParam;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_tkParameter; }
}
-
+
public override int GetHashCode()
{
return m_tkParameter;
}
-
+
public override bool Equals(Object obj)
{
if (obj is ParameterToken)
@@ -46,21 +49,20 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(ParameterToken obj)
{
return obj.m_tkParameter == m_tkParameter;
}
-
+
public static bool operator ==(ParameterToken a, ParameterToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(ParameterToken a, ParameterToken b)
{
return !(a == b);
}
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
index 7c4ed9dc0f..6dbcba251f 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PropertyBuilder.cs
@@ -12,8 +12,9 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
+
+namespace System.Reflection.Emit
+{
using System;
using System.Reflection;
using CultureInfo = System.Globalization.CultureInfo;
@@ -25,30 +26,29 @@ namespace System.Reflection.Emit {
// method will return a new PropertyBuilder to a client.
//
public sealed class PropertyBuilder : PropertyInfo
- {
-
+ {
// Make a private constructor so these cannot be constructed externally.
- private PropertyBuilder() {}
-
+ private PropertyBuilder() { }
+
// Constructs a PropertyBuilder.
//
internal PropertyBuilder(
- ModuleBuilder mod, // the module containing this PropertyBuilder
- String name, // property name
- SignatureHelper sig, // property signature descriptor info
- PropertyAttributes attr, // property attribute such as DefaultProperty, Bindable, DisplayBind, etc
- Type returnType, // return type of the property.
- PropertyToken prToken, // the metadata token for this property
- TypeBuilder containingType) // the containing type
+ ModuleBuilder mod, // the module containing this PropertyBuilder
+ String name, // property name
+ SignatureHelper sig, // property signature descriptor info
+ PropertyAttributes attr, // property attribute such as DefaultProperty, Bindable, DisplayBind, etc
+ Type returnType, // return type of the property.
+ PropertyToken prToken, // the metadata token for this property
+ TypeBuilder containingType) // the containing type
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
+ throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
Contract.EndContractBlock();
-
+
m_name = name;
m_moduleBuilder = mod;
m_signature = sig;
@@ -58,32 +58,32 @@ namespace System.Reflection.Emit {
m_tkProperty = prToken.Token;
m_containingType = containingType;
}
-
+
//************************************************
// Set the default value of the Property
//************************************************
- public void SetConstant(Object defaultValue)
+ public void SetConstant(Object defaultValue)
{
m_containingType.ThrowIfCreated();
-
+
TypeBuilder.SetConstantValue(
m_moduleBuilder,
m_prToken.Token,
m_returnType,
defaultValue);
}
-
+
// Return the Token for this property within the TypeBuilder that the
// property is defined within.
public PropertyToken PropertyToken
{
- get {return m_prToken;}
+ get { return m_prToken; }
}
-
+
public override Module Module
{
- get
+ get
{
return m_containingType.Module;
}
@@ -102,25 +102,25 @@ namespace System.Reflection.Emit {
m_prToken.Token,
semantics,
mdBuilder.GetToken().Token);
- }
+ }
public void SetGetMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Getter);
m_getMethod = mdBuilder;
}
-
+
public void SetSetMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Setter);
- m_setMethod = mdBuilder;
+ m_setMethod = mdBuilder;
}
public void AddOtherMethod(MethodBuilder mdBuilder)
{
SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other);
}
-
+
// Use this function if client decides to form the custom attribute blob themselves
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
@@ -129,7 +129,7 @@ namespace System.Reflection.Emit {
throw new ArgumentNullException(nameof(con));
if (binaryAttribute == null)
throw new ArgumentNullException(nameof(binaryAttribute));
-
+
m_containingType.ThrowIfCreated();
TypeBuilder.DefineCustomAttribute(
m_moduleBuilder,
@@ -151,29 +151,29 @@ namespace System.Reflection.Emit {
}
// Not supported functions in dynamic module.
- public override Object GetValue(Object obj,Object[] index)
+ public override Object GetValue(Object obj, Object[] index)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override Object GetValue(Object obj,BindingFlags invokeAttr,Binder binder,Object[] index,CultureInfo culture)
+ public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override void SetValue(Object obj,Object value,Object[] index)
+ public override void SetValue(Object obj, Object value, Object[] index)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override void SetValue(Object obj,Object value,BindingFlags invokeAttr,Binder binder,Object[] index,CultureInfo culture)
+ public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodInfo[] GetAccessors(bool nonPublic)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override MethodInfo GetGetMethod(bool nonPublic)
@@ -198,61 +198,69 @@ namespace System.Reflection.Emit {
public override ParameterInfo[] GetIndexParameters()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override Type PropertyType {
+ public override Type PropertyType
+ {
get { return m_returnType; }
}
- public override PropertyAttributes Attributes {
- get { return m_attributes;}
+ public override PropertyAttributes Attributes
+ {
+ get { return m_attributes; }
}
- public override bool CanRead {
- get { if (m_getMethod != null) return true; else return false; } }
+ public override bool CanRead
+ {
+ get { if (m_getMethod != null) return true; else return false; }
+ }
- public override bool CanWrite {
+ public override bool CanWrite
+ {
get { if (m_setMethod != null) return true; else return false; }
}
public override Object[] GetCustomAttributes(bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override bool IsDefined (Type attributeType, bool inherit)
+ public override bool IsDefined(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
- public override String Name {
+ public override String Name
+ {
get { return m_name; }
}
- public override Type DeclaringType {
+ public override Type DeclaringType
+ {
get { return m_containingType; }
}
- public override Type ReflectedType {
+ public override Type ReflectedType
+ {
get { return m_containingType; }
}
// These are package private so that TypeBuilder can access them.
- private String m_name; // The name of the property
- private PropertyToken m_prToken; // The token of this property
- private int m_tkProperty;
- private ModuleBuilder m_moduleBuilder;
- private SignatureHelper m_signature;
- private PropertyAttributes m_attributes; // property's attribute flags
- private Type m_returnType; // property's return type
- private MethodInfo m_getMethod;
- private MethodInfo m_setMethod;
- private TypeBuilder m_containingType;
+ private String m_name; // The name of the property
+ private PropertyToken m_prToken; // The token of this property
+ private int m_tkProperty;
+ private ModuleBuilder m_moduleBuilder;
+ private SignatureHelper m_signature;
+ private PropertyAttributes m_attributes; // property's attribute flags
+ private Type m_returnType; // property's return type
+ private MethodInfo m_getMethod;
+ private MethodInfo m_setMethod;
+ private TypeBuilder m_containingType;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
index 72ab983bb9..b450b198d2 100644
--- a/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/PropertyToken.cs
@@ -12,26 +12,29 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
[Serializable]
- public struct PropertyToken {
-
+ public struct PropertyToken
+ {
public static readonly PropertyToken Empty = new PropertyToken();
internal int m_property;
- internal PropertyToken(int str) {
- m_property=str;
+ internal PropertyToken(int str)
+ {
+ m_property = str;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_property; }
}
-
+
// Satisfy value class requirements
public override int GetHashCode()
{
@@ -46,23 +49,20 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(PropertyToken obj)
{
return obj.m_property == m_property;
}
-
+
public static bool operator ==(PropertyToken a, PropertyToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(PropertyToken a, PropertyToken b)
{
return !(a == b);
}
-
}
-
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
index b43abcb51c..fd1a8e70fe 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
@@ -4,23 +4,23 @@
//
-namespace System.Reflection.Emit
+using System.Text;
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+
+namespace System.Reflection.Emit
{
- using System.Text;
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
-
public sealed class SignatureHelper
{
#region Consts Fields
private const int NO_SIZE_IN_SIG = -1;
#endregion
-
+
#region Static Members
public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
@@ -31,7 +31,7 @@ namespace System.Reflection.Emit
{
return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null);
}
-
+
public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null);
@@ -41,17 +41,17 @@ namespace System.Reflection.Emit
{
SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst);
sigHelp.AddData(inst.Length);
- foreach(Type t in inst)
+ foreach (Type t in inst)
sigHelp.AddArgument(t);
return sigHelp;
}
-
+
internal static SignatureHelper GetMethodSigHelper(
Module scope, CallingConventions callingConvention,
Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
- return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
+ return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers,
optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
@@ -62,11 +62,11 @@ namespace System.Reflection.Emit
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
-
+
if (returnType == null)
{
returnType = typeof(void);
- }
+ }
intCall = MdSigCallingConvention.Default;
@@ -81,8 +81,8 @@ namespace System.Reflection.Emit
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
- sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType,
- requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
+ sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType,
+ requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
@@ -92,7 +92,7 @@ namespace System.Reflection.Emit
{
SignatureHelper sigHelp;
MdSigCallingConvention intCall;
-
+
if (returnType == null)
returnType = typeof(void);
@@ -114,19 +114,19 @@ namespace System.Reflection.Emit
}
else
{
- throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), nameof(unmanagedCallConv));
+ throw new ArgumentException(SR.Argument_UnknownUnmanagedCallConv, nameof(unmanagedCallConv));
}
-
+
sigHelp = new SignatureHelper(mod, intCall, returnType, null, null);
-
+
return sigHelp;
}
public static SignatureHelper GetLocalVarSigHelper()
- {
+ {
return GetLocalVarSigHelper(null);
}
-
+
public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType)
{
return GetMethodSigHelper(null, callingConvention, returnType);
@@ -141,47 +141,47 @@ namespace System.Reflection.Emit
{
return new SignatureHelper(mod, MdSigCallingConvention.LocalSig);
}
-
+
public static SignatureHelper GetFieldSigHelper(Module mod)
{
return new SignatureHelper(mod, MdSigCallingConvention.Field);
}
-
+
public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes)
{
return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null);
}
- public static SignatureHelper GetPropertySigHelper(Module mod,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
+ public static SignatureHelper GetPropertySigHelper(Module mod,
+ Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
- return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
+ return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers,
parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
}
public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention,
- Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
+ Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers,
Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers)
{
SignatureHelper sigHelp;
-
+
if (returnType == null)
{
returnType = typeof(void);
- }
+ }
MdSigCallingConvention intCall = MdSigCallingConvention.Property;
if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis)
intCall |= MdSigCallingConvention.HasThis;
- sigHelp = new SignatureHelper(mod, intCall,
+ sigHelp = new SignatureHelper(mod, intCall,
returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers);
sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers);
return sigHelp;
}
-
+
internal static SignatureHelper GetTypeSigToken(Module module, Type type)
{
if (module == null)
@@ -216,13 +216,13 @@ namespace System.Reflection.Emit
// Use this constructor to instantiate a any signatures that will require a return type.
Init(mod, callingConvention, cGenericParameters);
- if (callingConvention == MdSigCallingConvention.Field)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig"));
+ if (callingConvention == MdSigCallingConvention.Field)
+ throw new ArgumentException(SR.Argument_BadFieldSig);
- AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
+ AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers);
}
- private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
+ private SignatureHelper(Module mod, MdSigCallingConvention callingConvention,
Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
: this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers)
{
@@ -244,31 +244,31 @@ namespace System.Reflection.Emit
m_sigDone = false;
m_sizeLoc = NO_SIZE_IN_SIG;
- if (m_module == null && mod != null)
- throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder"));
+ if (m_module == null && mod != null)
+ throw new ArgumentException(SR.NotSupported_MustBeModuleBuilder);
}
private void Init(Module mod, MdSigCallingConvention callingConvention)
{
Init(mod, callingConvention, 0);
}
-
+
private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam)
- {
+ {
Init(mod);
AddData((byte)callingConvention);
if (callingConvention == MdSigCallingConvention.Field ||
- callingConvention == MdSigCallingConvention.GenericInst)
+ callingConvention == MdSigCallingConvention.GenericInst)
{
m_sizeLoc = NO_SIZE_IN_SIG;
- }
- else
+ }
+ else
{
if (cGenericParam > 0)
AddData(cGenericParam);
-
+
m_sizeLoc = m_currSig++;
}
}
@@ -302,10 +302,10 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(optionalCustomModifiers));
if (t.HasElementType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(optionalCustomModifiers));
+ throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(optionalCustomModifiers));
if (t.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(optionalCustomModifiers));
+ throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(optionalCustomModifiers));
AddElementType(CorElementType.CModOpt);
@@ -325,10 +325,10 @@ namespace System.Reflection.Emit
throw new ArgumentNullException(nameof(requiredCustomModifiers));
if (t.HasElementType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), nameof(requiredCustomModifiers));
+ throw new ArgumentException(SR.Argument_ArraysInvalid, nameof(requiredCustomModifiers));
if (t.ContainsGenericParameters)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), nameof(requiredCustomModifiers));
+ throw new ArgumentException(SR.Argument_GenericsInvalid, nameof(requiredCustomModifiers));
AddElementType(CorElementType.CModReqd);
@@ -425,7 +425,7 @@ namespace System.Reflection.Emit
}
else if (clsArgument.IsArray)
{
- if (clsArgument.IsSzArray)
+ if (clsArgument.IsSZArray)
{
AddElementType(CorElementType.SzArray);
@@ -482,7 +482,7 @@ namespace System.Reflection.Emit
}
}
}
-
+
private void AddData(int data)
{
// A managed representation of CorSigCompressData;
@@ -491,80 +491,79 @@ namespace System.Reflection.Emit
{
m_signature = ExpandArray(m_signature);
}
-
+
if (data <= 0x7F)
{
m_signature[m_currSig++] = (byte)(data & 0xFF);
- }
+ }
else if (data <= 0x3FFF)
{
- m_signature[m_currSig++] = (byte)((data >>8) | 0x80);
+ m_signature[m_currSig++] = (byte)((data >> 8) | 0x80);
m_signature[m_currSig++] = (byte)(data & 0xFF);
- }
+ }
else if (data <= 0x1FFFFFFF)
{
- m_signature[m_currSig++] = (byte)((data >>24) | 0xC0);
- m_signature[m_currSig++] = (byte)((data >>16) & 0xFF);
- m_signature[m_currSig++] = (byte)((data >>8) & 0xFF);
+ m_signature[m_currSig++] = (byte)((data >> 24) | 0xC0);
+ m_signature[m_currSig++] = (byte)((data >> 16) & 0xFF);
+ m_signature[m_currSig++] = (byte)((data >> 8) & 0xFF);
m_signature[m_currSig++] = (byte)((data) & 0xFF);
- }
+ }
else
{
- throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
- }
-
+ throw new ArgumentException(SR.Argument_LargeInteger);
+ }
}
-
+
private void AddElementType(CorElementType cvt)
{
// Adds an element to the signature. A managed represenation of CorSigCompressElement
- if (m_currSig + 1 > m_signature.Length)
+ if (m_currSig + 1 > m_signature.Length)
m_signature = ExpandArray(m_signature);
m_signature[m_currSig++] = (byte)cvt;
}
-
- private void AddToken(int token)
+
+ private void AddToken(int token)
{
// A managed represenation of CompressToken
// Pulls the token appart to get a rid, adds some appropriate bits
// to the token and then adds this to the signature.
- int rid = (token & 0x00FFFFFF); //This is RidFromToken;
+ int rid = (token & 0x00FFFFFF); //This is RidFromToken;
MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken;
-
- if (rid > 0x3FFFFFF)
+
+ if (rid > 0x3FFFFFF)
{
// token is too big to be compressed
- throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
+ throw new ArgumentException(SR.Argument_LargeInteger);
}
-
- rid = (rid << 2);
-
+
+ rid = (rid << 2);
+
// TypeDef is encoded with low bits 00
// TypeRef is encoded with low bits 01
// TypeSpec is encoded with low bits 10
- if (type == MetadataTokenType.TypeRef)
- {
+ if (type == MetadataTokenType.TypeRef)
+ {
//if type is mdtTypeRef
- rid|=0x1;
- }
- else if (type == MetadataTokenType.TypeSpec)
- {
+ rid |= 0x1;
+ }
+ else if (type == MetadataTokenType.TypeSpec)
+ {
//if type is mdtTypeSpec
- rid|=0x2;
+ rid |= 0x2;
}
-
+
AddData(rid);
}
-
+
private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType)
{
// Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType
AddElementType(CorType);
AddToken(clsToken.Token);
}
-
+
private unsafe void InternalAddRuntimeType(Type type)
{
// Add a runtime type into the signature.
@@ -580,11 +579,11 @@ namespace System.Reflection.Emit
if (m_currSig + sizeof(void*) > m_signature.Length)
m_signature = ExpandArray(m_signature);
- byte *phandle = (byte*)&handle;
+ byte* phandle = (byte*)&handle;
for (int i = 0; i < sizeof(void*); i++)
m_signature[m_currSig++] = phandle[i];
}
-
+
private byte[] ExpandArray(byte[] inArray)
{
// Expand the signature buffer size
@@ -595,25 +594,25 @@ namespace System.Reflection.Emit
{
// Expand the signature buffer size
- if (requiredLength < inArray.Length)
- requiredLength = inArray.Length*2;
+ if (requiredLength < inArray.Length)
+ requiredLength = inArray.Length * 2;
byte[] outArray = new byte[requiredLength];
Buffer.BlockCopy(inArray, 0, outArray, 0, inArray.Length);
return outArray;
}
-
+
private void IncrementArgCounts()
{
- if (m_sizeLoc == NO_SIZE_IN_SIG)
- {
+ if (m_sizeLoc == NO_SIZE_IN_SIG)
+ {
//We don't have a size if this is a field.
return;
}
m_argCount++;
}
-
+
private void SetNumberOfSignatureElements(bool forceCopy)
{
// For most signatures, this will set the number of elements in a byte which we have reserved for it.
@@ -628,18 +627,18 @@ namespace System.Reflection.Emit
byte[] temp;
int newSigSize;
int currSigHolder = m_currSig;
-
- if (m_sizeLoc == NO_SIZE_IN_SIG)
+
+ if (m_sizeLoc == NO_SIZE_IN_SIG)
return;
-
+
//If we have fewer than 128 arguments and we haven't been told to copy the
//array, we can just set the appropriate bit and return.
- if (m_argCount < 0x80 && !forceCopy)
+ if (m_argCount < 0x80 && !forceCopy)
{
m_signature[m_sizeLoc] = (byte)m_argCount;
return;
- }
-
+ }
+
//We need to have more bytes for the size. Figure out how many bytes here.
//Since we need to copy anyway, we're just going to take the cost of doing a
//new allocation.
@@ -655,45 +654,45 @@ namespace System.Reflection.Emit
{
newSigSize = 4;
}
-
+
//Allocate the new array.
temp = new byte[m_currSig + newSigSize - 1];
-
+
//Copy the calling convention. The calling convention is always just one byte
//so we just copy that byte. Then copy the rest of the array, shifting everything
//to make room for the new number of elements.
temp[0] = m_signature[0];
Buffer.BlockCopy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1));
m_signature = temp;
-
+
//Use the AddData method to add the number of elements appropriately compressed.
m_currSig = m_sizeLoc;
AddData(m_argCount);
m_currSig = currSigHolder + (newSigSize - 1);
}
-
+
#endregion
#region Internal Members
internal int ArgumentCount
- {
- get
- {
- return m_argCount;
- }
+ {
+ get
+ {
+ return m_argCount;
+ }
}
internal static bool IsSimpleType(CorElementType type)
{
- if (type <= CorElementType.String)
+ if (type <= CorElementType.String)
return true;
- if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object)
+ if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object)
return true;
return false;
}
-
+
internal byte[] InternalGetSignature(out int length)
{
// An internal method to return the signature. Does not trim the
@@ -703,7 +702,7 @@ namespace System.Reflection.Emit
//
// param length : an out param indicating the length of the array.
// return : A reference to the internal ubyte array.
-
+
if (!m_sigDone)
{
m_sigDone = true;
@@ -713,20 +712,20 @@ namespace System.Reflection.Emit
// array. Bummer, eh?
SetNumberOfSignatureElements(false);
}
-
+
length = m_currSig;
return m_signature;
}
-
-
-
-
+
+
+
+
internal byte[] InternalGetSignatureArray()
{
- int argCount = m_argCount;
+ int argCount = m_argCount;
int currSigLength = m_currSig;
int newSigSize = currSigLength;
-
+
//Allocate the new array.
if (argCount < 0x7F)
newSigSize += 1;
@@ -745,26 +744,26 @@ namespace System.Reflection.Emit
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
else if (argCount <= 0x3FFF)
{
- temp[sigCopyIndex++] = (byte)((argCount >>8) | 0x80);
+ temp[sigCopyIndex++] = (byte)((argCount >> 8) | 0x80);
temp[sigCopyIndex++] = (byte)(argCount & 0xFF);
- }
+ }
else if (argCount <= 0x1FFFFFFF)
{
- temp[sigCopyIndex++] = (byte)((argCount >>24) | 0xC0);
- temp[sigCopyIndex++] = (byte)((argCount >>16) & 0xFF);
- temp[sigCopyIndex++] = (byte)((argCount >>8) & 0xFF);
+ temp[sigCopyIndex++] = (byte)((argCount >> 24) | 0xC0);
+ temp[sigCopyIndex++] = (byte)((argCount >> 16) & 0xFF);
+ temp[sigCopyIndex++] = (byte)((argCount >> 8) & 0xFF);
temp[sigCopyIndex++] = (byte)((argCount) & 0xFF);
- }
+ }
else
- throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger"));
+ throw new ArgumentException(SR.Argument_LargeInteger);
// copy the sig part of the sig
Buffer.BlockCopy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2);
// mark the end of sig
temp[newSigSize - 1] = (byte)CorElementType.End;
-
+
return temp;
}
-
+
#endregion
#region Public Methods
@@ -781,21 +780,21 @@ namespace System.Reflection.Emit
IncrementArgCounts();
AddOneArgTypeHelper(argument, pinned);
}
-
+
public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length))
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(requiredCustomModifiers), nameof(arguments)));
+ throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, nameof(requiredCustomModifiers), nameof(arguments)));
if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length))
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(optionalCustomModifiers), nameof(arguments)));
+ throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, nameof(optionalCustomModifiers), nameof(arguments)));
if (arguments != null)
{
- for (int i =0; i < arguments.Length; i++)
+ for (int i = 0; i < arguments.Length; i++)
{
- AddArgument(arguments[i],
- requiredCustomModifiers == null ? null : requiredCustomModifiers[i],
+ AddArgument(arguments[i],
+ requiredCustomModifiers == null ? null : requiredCustomModifiers[i],
optionalCustomModifiers == null ? null : optionalCustomModifiers[i]);
}
}
@@ -804,13 +803,13 @@ namespace System.Reflection.Emit
public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers)
{
if (m_sigDone)
- throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized"));
-
+ throw new ArgumentException(SR.Argument_SigIsFinalized);
+
if (argument == null)
throw new ArgumentNullException(nameof(argument));
IncrementArgCounts();
-
+
// Add an argument to the signature. Takes a Type and determines whether it
// is one of the primitive types of which we have special knowledge or a more
// general class. In the former case, we only add the appropriate short cut encoding,
@@ -825,26 +824,26 @@ namespace System.Reflection.Emit
public override bool Equals(Object obj)
{
- if (!(obj is SignatureHelper))
+ if (!(obj is SignatureHelper))
{
return false;
}
-
+
SignatureHelper temp = (SignatureHelper)obj;
-
- if ( !temp.m_module.Equals(m_module) || temp.m_currSig!=m_currSig || temp.m_sizeLoc!=m_sizeLoc || temp.m_sigDone !=m_sigDone )
+
+ if (!temp.m_module.Equals(m_module) || temp.m_currSig != m_currSig || temp.m_sizeLoc != m_sizeLoc || temp.m_sigDone != m_sigDone)
{
return false;
}
-
- for (int i=0; i<m_currSig; i++)
+
+ for (int i = 0; i < m_currSig; i++)
{
- if (m_signature[i]!=temp.m_signature[i])
+ if (m_signature[i] != temp.m_signature[i])
return false;
}
return true;
}
-
+
public override int GetHashCode()
{
// Start the hash code with the hash code of the module and the values of the member variables.
@@ -855,7 +854,7 @@ namespace System.Reflection.Emit
HashCode += 1;
// Then add the hash code of all the arguments.
- for (int i=0; i < m_currSig; i++)
+ for (int i = 0; i < m_currSig; i++)
HashCode += m_signature[i].GetHashCode();
return HashCode;
@@ -865,23 +864,23 @@ namespace System.Reflection.Emit
{
return GetSignature(false);
}
-
+
internal byte[] GetSignature(bool appendEndOfSig)
{
// Chops the internal signature to the appropriate length. Adds the
// end token to the signature and marks the signature as finished so that
// no further tokens can be added. Return the full signature in a trimmed array.
- if (!m_sigDone)
+ if (!m_sigDone)
{
- if (appendEndOfSig)
+ if (appendEndOfSig)
AddElementType(CorElementType.End);
SetNumberOfSignatureElements(true);
m_sigDone = true;
}
-
+
// This case will only happen if the user got the signature through
// InternalGetSignature first and then called GetSignature.
- if (m_signature.Length > m_currSig)
+ if (m_signature.Length > m_currSig)
{
byte[] temp = new byte[m_currSig];
Array.Copy(m_signature, 0, temp, 0, m_currSig);
@@ -890,7 +889,7 @@ namespace System.Reflection.Emit
return m_signature;
}
-
+
public override String ToString()
{
StringBuilder sb = new StringBuilder();
@@ -906,7 +905,7 @@ namespace System.Reflection.Emit
}
sb.Append("Signature: " + Environment.NewLine);
- for (int i=0; i<=m_currSig; i++)
+ for (int i = 0; i <= m_currSig; i++)
{
sb.Append(m_signature[i] + " ");
}
@@ -914,9 +913,8 @@ namespace System.Reflection.Emit
sb.Append(Environment.NewLine);
return sb.ToString();
}
-
- #endregion
+ #endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs b/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs
index 5c908b89c7..e17e0c955e 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SignatureToken.cs
@@ -13,32 +13,35 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
- public struct SignatureToken {
-
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
+ public struct SignatureToken
+ {
public static readonly SignatureToken Empty = new SignatureToken();
internal int m_signature;
internal ModuleBuilder m_moduleBuilder;
-
- internal SignatureToken(int str, ModuleBuilder mod) {
- m_signature=str;
+
+ internal SignatureToken(int str, ModuleBuilder mod)
+ {
+ m_signature = str;
m_moduleBuilder = mod;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_signature; }
}
-
+
public override int GetHashCode()
{
return m_signature;
}
-
+
public override bool Equals(Object obj)
{
if (obj is SignatureToken)
@@ -46,21 +49,20 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(SignatureToken obj)
{
return obj.m_signature == m_signature;
}
-
+
public static bool operator ==(SignatureToken a, SignatureToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(SignatureToken a, SignatureToken b)
{
return !(a == b);
}
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
index 8a447d03fc..afcf2ddf0a 100644
--- a/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/StackBehaviour.cs
@@ -12,42 +12,42 @@
** THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT BY HAND!
** See clr\src\inc\opcodegen.pl for more information.**
============================================================*/
-namespace System.Reflection.Emit {
using System;
-[Serializable]
-public enum StackBehaviour
+namespace System.Reflection.Emit
{
-
- Pop0 = 0,
- Pop1 = 1,
- Pop1_pop1 = 2,
- Popi = 3,
- Popi_pop1 = 4,
- Popi_popi = 5,
- Popi_popi8 = 6,
- Popi_popi_popi = 7,
- Popi_popr4 = 8,
- Popi_popr8 = 9,
- Popref = 10,
- Popref_pop1 = 11,
- Popref_popi = 12,
- Popref_popi_popi = 13,
- Popref_popi_popi8 = 14,
- Popref_popi_popr4 = 15,
- Popref_popi_popr8 = 16,
- Popref_popi_popref = 17,
- Push0 = 18,
- Push1 = 19,
- Push1_push1 = 20,
- Pushi = 21,
- Pushi8 = 22,
- Pushr4 = 23,
- Pushr8 = 24,
- Pushref = 25,
- Varpop = 26,
- Varpush = 27,
- Popref_popi_pop1 = 28,
-}
+ [Serializable]
+ public enum StackBehaviour
+ {
+ Pop0 = 0,
+ Pop1 = 1,
+ Pop1_pop1 = 2,
+ Popi = 3,
+ Popi_pop1 = 4,
+ Popi_popi = 5,
+ Popi_popi8 = 6,
+ Popi_popi_popi = 7,
+ Popi_popr4 = 8,
+ Popi_popr8 = 9,
+ Popref = 10,
+ Popref_pop1 = 11,
+ Popref_popi = 12,
+ Popref_popi_popi = 13,
+ Popref_popi_popi8 = 14,
+ Popref_popi_popr4 = 15,
+ Popref_popi_popr8 = 16,
+ Popref_popi_popref = 17,
+ Push0 = 18,
+ Push1 = 19,
+ Push1_push1 = 20,
+ Pushi = 21,
+ Pushi8 = 22,
+ Pushr4 = 23,
+ Pushr8 = 24,
+ Pushref = 25,
+ Varpop = 26,
+ Varpush = 27,
+ Popref_popi_pop1 = 28,
+ }
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
index 852225697c..1d90816fc6 100644
--- a/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/StringToken.cs
@@ -12,36 +12,39 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+
+namespace System.Reflection.Emit
+{
[Serializable]
- public struct StringToken {
-
+ public struct StringToken
+ {
internal int m_string;
-
+
//public StringToken() {
// m_string=0;
//}
-
- internal StringToken(int str) {
- m_string=str;
+
+ internal StringToken(int str)
+ {
+ m_string = str;
}
-
+
// Returns the metadata token for this particular string.
// Generated by a call to Module.GetStringConstant().
//
- public int Token {
+ public int Token
+ {
get { return m_string; }
}
-
+
public override int GetHashCode()
{
return m_string;
}
-
+
public override bool Equals(Object obj)
{
if (obj is StringToken)
@@ -49,29 +52,20 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(StringToken obj)
{
return obj.m_string == m_string;
}
-
+
public static bool operator ==(StringToken a, StringToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(StringToken a, StringToken b)
{
return !(a == b);
}
-
}
-
-
-
-
-
-
-
-
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
index 6b47770608..42713b86db 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SymbolMethod.cs
@@ -4,14 +4,14 @@
//
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
using System.Reflection;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
-
+
internal sealed class SymbolMethod : MethodInfo
{
#region Private Data Members
@@ -26,7 +26,7 @@ namespace System.Reflection.Emit
#endregion
#region Constructor
- internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, String methodName,
+ internal SymbolMethod(ModuleBuilder mod, MethodToken token, Type arrayClass, String methodName,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
{
// This is a kind of MethodInfo to represent methods for array type of unbaked type
@@ -47,9 +47,9 @@ namespace System.Reflection.Emit
}
else
{
- m_parameterTypes = EmptyArray<Type>.Value;
+ m_parameterTypes = Array.Empty<Type>();
}
-
+
m_module = mod;
m_containingType = arrayClass;
m_name = methodName;
@@ -70,28 +70,28 @@ namespace System.Reflection.Emit
{
return mod.GetArrayMethodToken(m_containingType, m_name, m_callingConvention, m_returnType, m_parameterTypes);
}
-
+
#endregion
#region MemberInfo Overrides
- public override Module Module
- {
- get { return m_module; }
- }
+ public override Module Module
+ {
+ get { return m_module; }
+ }
public override Type ReflectedType
{
get { return m_containingType as Type; }
}
- public override String Name
+ public override String Name
{
get { return m_name; }
}
- public override Type DeclaringType
+ public override Type DeclaringType
{
- get {return m_containingType;}
+ get { return m_containingType; }
}
#endregion
@@ -99,27 +99,27 @@ namespace System.Reflection.Emit
[Pure]
public override ParameterInfo[] GetParameters()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
+ throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
-
+
public override MethodImplAttributes GetMethodImplementationFlags()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
+ throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
-
- public override MethodAttributes Attributes
+
+ public override MethodAttributes Attributes
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod")); }
+ get { throw new NotSupportedException(SR.NotSupported_SymbolMethod); }
}
-
- public override CallingConventions CallingConvention
+
+ public override CallingConventions CallingConvention
{
get { return m_callingConvention; }
}
- public override RuntimeMethodHandle MethodHandle
+ public override RuntimeMethodHandle MethodHandle
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod")); }
+ get { throw new NotSupportedException(SR.NotSupported_SymbolMethod); }
}
#endregion
@@ -133,16 +133,16 @@ namespace System.Reflection.Emit
}
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ public override ICustomAttributeProvider ReturnTypeCustomAttributes
{
- get { return null; }
+ get { return null; }
}
-
+
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
+ throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
-
+
public override MethodInfo GetBaseDefinition()
{
return this;
@@ -152,19 +152,19 @@ namespace System.Reflection.Emit
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
+ throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
-
+
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
+ throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SymbolMethod"));
+ throw new NotSupportedException(SR.NotSupported_SymbolMethod);
}
-
+
#endregion
#region Public Members
diff --git a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
index 205299125b..16848b43dd 100644
--- a/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/SymbolType.cs
@@ -4,7 +4,7 @@
//
-namespace System.Reflection.Emit
+namespace System.Reflection.Emit
{
using System.Runtime.InteropServices;
using System;
@@ -15,16 +15,17 @@ namespace System.Reflection.Emit
[Serializable]
internal enum TypeKind
{
- IsArray = 1,
+ IsArray = 1,
IsPointer = 2,
- IsByRef = 3,
+ IsByRef = 3,
}
// This is a kind of Type object that will represent the compound expression of a parameter type or field type.
internal sealed class SymbolType : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ {
+ if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
@@ -52,8 +53,8 @@ namespace System.Reflection.Emit
return baseType;
}
-
-
+
+
if (format[curIndex] == '&')
{
@@ -62,10 +63,10 @@ namespace System.Reflection.Emit
symbolType = new SymbolType(TypeKind.IsByRef);
symbolType.SetFormat(format, curIndex, 1);
curIndex++;
-
+
if (curIndex != format.Length)
// ByRef has to be the last char!!
- throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
+ throw new ArgumentException(SR.Argument_BadSigFormat);
symbolType.SetElementType(baseType);
return symbolType;
@@ -84,13 +85,13 @@ namespace System.Reflection.Emit
// Example: [2..4] - one dimension array with lower bound 2 and size of 3
// Example: [3, 5, 6] - three dimension array with lower bound 3, 5, 6
// Example: [-3, ] [] - one dimensional array of two dimensional array (with lower bound -3 sepcified)
-
+
while (format[curIndex] != ']')
{
if (format[curIndex] == '*')
{
symbolType.m_isSzArray = false;
- curIndex++;
+ curIndex++;
}
// consume, one dimension at a time
if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-')
@@ -117,10 +118,9 @@ namespace System.Reflection.Emit
// set the upper bound to be less than LowerBound to indicate that upper bound it not specified yet!
iUpperBound = iLowerBound - 1;
-
}
if (format[curIndex] == '.')
- {
+ {
// upper bound is specified
// skip over ".."
@@ -128,7 +128,7 @@ namespace System.Reflection.Emit
if (format[curIndex] != '.')
{
// bad format!! Throw exception
- throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
+ throw new ArgumentException(SR.Argument_BadSigFormat);
}
curIndex++;
@@ -158,7 +158,7 @@ namespace System.Reflection.Emit
{
// User specified upper bound less than lower bound, this is an error.
// Throw error exception.
- throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
+ throw new ArgumentException(SR.Argument_BadSigFormat);
}
}
}
@@ -176,10 +176,10 @@ namespace System.Reflection.Emit
}
else if (format[curIndex] != ']')
{
- throw new ArgumentException(Environment.GetResourceString("Argument_BadSigFormat"));
+ throw new ArgumentException(SR.Argument_BadSigFormat);
}
}
-
+
// The last dimension information
symbolType.SetBounds(iLowerBound, iUpperBound);
@@ -209,21 +209,21 @@ namespace System.Reflection.Emit
#endregion
#region Data Members
- internal TypeKind m_typeKind;
- internal Type m_baseType;
- internal int m_cRank; // count of dimension
+ internal TypeKind m_typeKind;
+ internal Type m_baseType;
+ internal int m_cRank; // count of dimension
// If LowerBound and UpperBound is equal, that means one element.
// If UpperBound is less than LowerBound, then the size is not specified.
- internal int[] m_iaLowerBound;
- internal int[] m_iaUpperBound; // count of dimension
- private string m_format; // format string to form the full name.
- private bool m_isSzArray = true;
+ internal int[] m_iaLowerBound;
+ internal int[] m_iaUpperBound; // count of dimension
+ private string m_format; // format string to form the full name.
+ private bool m_isSzArray = true;
#endregion
#region Constructor
internal SymbolType(TypeKind typeKind)
{
- m_typeKind = typeKind;
+ m_typeKind = typeKind;
m_iaLowerBound = new int[4];
m_iaUpperBound = new int[4];
}
@@ -246,15 +246,15 @@ namespace System.Reflection.Emit
if (lower != 0 || upper != -1)
m_isSzArray = false;
-
+
if (m_iaLowerBound.Length <= m_cRank)
{
// resize the bound array
- int[] iaTemp = new int[m_cRank * 2];
+ int[] iaTemp = new int[m_cRank * 2];
Array.Copy(m_iaLowerBound, 0, iaTemp, 0, m_cRank);
- m_iaLowerBound = iaTemp;
+ m_iaLowerBound = iaTemp;
Array.Copy(m_iaUpperBound, 0, iaTemp, 0, m_cRank);
- m_iaUpperBound = iaTemp;
+ m_iaUpperBound = iaTemp;
}
m_iaLowerBound[m_cRank] = lower;
@@ -269,36 +269,27 @@ namespace System.Reflection.Emit
m_format = format.Substring(curIndex, length);
}
#endregion
-
+
#region Type Overrides
- internal override bool IsSzArray
- {
- get
- {
- if (m_cRank > 1)
- return false;
-
- return m_isSzArray;
- }
- }
+ public override bool IsSZArray => m_cRank <= 1 && m_isSzArray;
- public override Type MakePointerType()
- {
+ public override Type MakePointerType()
+ {
return SymbolType.FormCompoundType(m_format + "*", m_baseType, 0);
}
- public override Type MakeByRefType()
- {
+ public override Type MakeByRefType()
+ {
return SymbolType.FormCompoundType(m_format + "&", m_baseType, 0);
}
-
- public override Type MakeArrayType()
- {
+
+ public override Type MakeArrayType()
+ {
return SymbolType.FormCompoundType(m_format + "[]", m_baseType, 0);
}
-
- public override Type MakeArrayType(int rank)
- {
+
+ public override Type MakeArrayType(int rank)
+ {
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
@@ -308,9 +299,9 @@ namespace System.Reflection.Emit
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -322,55 +313,55 @@ namespace System.Reflection.Emit
public override int GetArrayRank()
{
if (!IsArray)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
+ throw new NotSupportedException(SR.NotSupported_SubclassOverride);
Contract.EndContractBlock();
return m_cRank;
}
-
- public override Guid GUID
+
+ public override Guid GUID
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); }
+ get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); }
}
- public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target,
+ public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target,
Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
- public override Module Module
+ public override Module Module
{
- get
+ get
{
Type baseType;
- for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType);
+ for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) ;
return baseType.Module;
}
}
- public override Assembly Assembly
+ public override Assembly Assembly
{
- get
+ get
{
Type baseType;
- for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType) baseType).m_baseType);
+ for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) ;
return baseType.Assembly;
}
}
-
- public override RuntimeTypeHandle TypeHandle
+
+ public override RuntimeTypeHandle TypeHandle
{
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType")); }
+ get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); }
}
-
- public override String Name
+
+ public override String Name
{
- get
- {
+ get
+ {
Type baseType;
String sFormat = m_format;
@@ -380,140 +371,139 @@ namespace System.Reflection.Emit
return baseType.Name + sFormat;
}
}
-
- public override String FullName
+
+ public override String FullName
{
- get
- {
+ get
+ {
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
}
}
- public override String AssemblyQualifiedName
+ public override String AssemblyQualifiedName
{
- get
- {
+ get
+ {
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
}
}
public override String ToString()
- {
- return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
+ {
+ return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
-
- public override String Namespace
+
+ public override String Namespace
{
get { return m_baseType.Namespace; }
}
-
- public override Type BaseType
+
+ public override Type BaseType
{
-
get { return typeof(System.Array); }
}
-
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
+
+ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
- protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
+
+ protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
- public override Type GetInterface(String name,bool ignoreCase)
+
+ public override Type GetInterface(String name, bool ignoreCase)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override Type[] GetInterfaces()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
- public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
+
+ public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override EventInfo[] GetEvents()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
- protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
+
+ protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
- public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
+ public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
-
+
protected override TypeAttributes GetAttributeFlagsImpl()
{
// Return the attribute flags of the base type?
Type baseType;
- for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType);
+ for (baseType = m_baseType; baseType is SymbolType; baseType = ((SymbolType)baseType).m_baseType) ;
return baseType.Attributes;
}
-
+
protected override bool IsArrayImpl()
{
return m_typeKind == TypeKind.IsArray;
@@ -533,12 +523,12 @@ namespace System.Reflection.Emit
{
return false;
}
-
- protected override bool IsValueTypeImpl()
+
+ protected override bool IsValueTypeImpl()
{
return false;
}
-
+
protected override bool IsCOMObjectImpl()
{
return false;
@@ -556,31 +546,30 @@ namespace System.Reflection.Emit
{
return m_baseType;
}
-
+
protected override bool HasElementTypeImpl()
{
return m_baseType != null;
}
-
- public override Type UnderlyingSystemType
+
+ public override Type UnderlyingSystemType
{
-
get { return this; }
}
-
+
public override Object[] GetCustomAttributes(bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
- public override bool IsDefined (Type attributeType, bool inherit)
+ public override bool IsDefined(Type attributeType, bool inherit)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NonReflectedType"));
+ throw new NotSupportedException(SR.NotSupported_NonReflectedType);
}
#endregion
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
index 88502cb096..a98af2bdcf 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilder.cs
@@ -5,7 +5,8 @@
//
-namespace System.Reflection.Emit {
+namespace System.Reflection.Emit
+{
using System;
using System.Reflection;
using System.Security;
@@ -22,21 +23,22 @@ namespace System.Reflection.Emit {
[Serializable]
public enum PackingSize
{
- Unspecified = 0,
- Size1 = 1,
- Size2 = 2,
- Size4 = 4,
- Size8 = 8,
- Size16 = 16,
- Size32 = 32,
- Size64 = 64,
- Size128 = 128,
+ Unspecified = 0,
+ Size1 = 1,
+ Size2 = 2,
+ Size4 = 4,
+ Size8 = 8,
+ Size16 = 16,
+ Size32 = 32,
+ Size64 = 64,
+ Size128 = 128,
}
public sealed class TypeBuilder : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ {
+ if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
@@ -46,7 +48,7 @@ namespace System.Reflection.Emit {
private ConstructorInfo m_con;
private byte[] m_binaryAttribute;
private CustomAttributeBuilder m_customBuilder;
-
+
public CustAttr(ConstructorInfo con, byte[] binaryAttribute)
{
if (con == null)
@@ -83,12 +85,12 @@ namespace System.Reflection.Emit {
}
}
#endregion
-
+
#region Public Static Methods
public static MethodInfo GetMethod(Type type, MethodInfo method)
{
if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));
+ throw new ArgumentException(SR.Argument_MustBeTypeBuilder);
// The following checks establishes invariants that more simply put require type to be generic and
// method to be a generic method definition declared on the generic type definition of type.
@@ -96,15 +98,15 @@ namespace System.Reflection.Emit {
// this function followed by MakeGenericMethod on the resulting MethodInfo to finally get G<Foo>.M<Bar>.
// We could also allow G<T>.M<Bar> to be created before G<Foo>.M<Bar> (BindGenParm followed by this method)
// if we wanted to but that just complicates things so these checks are designed to prevent that scenario.
-
+
if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedGenericMethodDefinition"), nameof(method));
-
+ throw new ArgumentException(SR.Argument_NeedGenericMethodDefinition, nameof(method));
+
if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_MethodNeedGenericDeclaringType"), nameof(method));
-
+ throw new ArgumentException(SR.Argument_MethodNeedGenericDeclaringType, nameof(method));
+
if (type.GetGenericTypeDefinition() != method.DeclaringType)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidMethodDeclaringType"), nameof(type));
+ throw new ArgumentException(SR.Argument_InvalidMethodDeclaringType, nameof(type));
Contract.EndContractBlock();
// The following converts from Type or TypeBuilder of G<T> to TypeBuilderInstantiation G<T>. These types
@@ -112,51 +114,51 @@ namespace System.Reflection.Emit {
// G<M>.M() be encoded by a typeSpec whose parent is the typeDef for G<M> and whose instantiation is also G<M>.
if (type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
-
+
if (!(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation);
}
public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor)
- {
+ {
if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));
+ throw new ArgumentException(SR.Argument_MustBeTypeBuilder);
if (!constructor.DeclaringType.IsGenericTypeDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstructorNeedGenericDeclaringType"), nameof(constructor));
+ throw new ArgumentException(SR.Argument_ConstructorNeedGenericDeclaringType, nameof(constructor));
Contract.EndContractBlock();
-
+
if (!(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
// TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
if (type is TypeBuilder && type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type.GetGenericTypeDefinition() != constructor.DeclaringType)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidConstructorDeclaringType"), nameof(type));
+ throw new ArgumentException(SR.Argument_InvalidConstructorDeclaringType, nameof(type));
return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation);
}
public static FieldInfo GetField(Type type, FieldInfo field)
{
if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeTypeBuilder"));
+ throw new ArgumentException(SR.Argument_MustBeTypeBuilder);
if (!field.DeclaringType.IsGenericTypeDefinition)
- throw new ArgumentException(Environment.GetResourceString("Argument_FieldNeedGenericDeclaringType"), nameof(field));
+ throw new ArgumentException(SR.Argument_FieldNeedGenericDeclaringType, nameof(field));
Contract.EndContractBlock();
-
+
if (!(type is TypeBuilderInstantiation))
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
// TypeBuilder G<T> ==> TypeBuilderInstantiation G<T>
if (type is TypeBuilder && type.IsGenericTypeDefinition)
type = type.MakeGenericType(type.GetGenericArguments());
if (type.GetGenericTypeDefinition() != field.DeclaringType)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFieldDeclaringType"), nameof(type));
+ throw new ArgumentException(SR.Argument_InvalidFieldDeclaringType, nameof(type));
return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation);
}
@@ -168,41 +170,41 @@ namespace System.Reflection.Emit {
#region Private Static FCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private static extern void SetParentType(RuntimeModule module, int tdTypeDef, int tkParent);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private static extern void AddInterfaceImpl(RuntimeModule module, int tdTypeDef, int tkInterface);
#endregion
#region Internal Static FCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern int DefineMethod(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength,
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern int DefineMethod(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength,
MethodAttributes attributes);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern int DefineMethodSpec(RuntimeModule module, int tkParent, byte[] signature, int sigLength);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern int DefineField(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength,
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern int DefineField(RuntimeModule module, int tkParent, String name, byte[] signature, int sigLength,
FieldAttributes attributes);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals,
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void SetMethodIL(RuntimeModule module, int tk, bool isInitLocals,
byte[] body, int bodyLength,
- byte[] LocalSig, int sigLength,
+ byte[] LocalSig, int sigLength,
int maxStackSize,
- ExceptionHandler[] exceptions, int numExceptions,
- int [] tokenFixups, int numTokenFixups);
+ ExceptionHandler[] exceptions, int numExceptions,
+ int[] tokenFixups, int numTokenFixups);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor,
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void DefineCustomAttribute(RuntimeModule module, int tkAssociate, int tkConstructor,
byte[] attr, int attrLength, bool toDisk, bool updateCompilerFlags);
internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor,
@@ -216,55 +218,55 @@ namespace System.Reflection.Emit {
Buffer.BlockCopy(attr, 0, localAttr, 0, attr.Length);
}
- DefineCustomAttribute(module.GetNativeHandle(), tkAssociate, tkConstructor,
+ DefineCustomAttribute(module.GetNativeHandle(), tkAssociate, tkConstructor,
localAttr, (localAttr != null) ? localAttr.Length : 0, toDisk, updateCompilerFlags);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern int DefineProperty(RuntimeModule module, int tkParent, String name, PropertyAttributes attributes,
byte[] signature, int sigLength);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern int DefineEvent(RuntimeModule module, int tkParent, String name, EventAttributes attributes, int tkEventType);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern void DefineMethodSemantics(RuntimeModule module, int tkAssociation,
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern void DefineMethodSemantics(RuntimeModule module, int tkAssociation,
MethodSemanticsAttributes semantics, int tkMethod);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern void DefineMethodImpl(RuntimeModule module, int tkType, int tkBody, int tkDecl);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern void SetMethodImpl(RuntimeModule module, int tkMethod, MethodImplAttributes MethodImplAttributes);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence,
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern int SetParamInfo(RuntimeModule module, int tkMethod, int iSequence,
ParameterAttributes iParamAttributes, String strParamName);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern int GetTokenFromSig(RuntimeModule module, byte[] signature, int sigLength);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern void SetFieldLayoutOffset(RuntimeModule module, int fdToken, int iOffset);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
internal static extern void SetClassLayout(RuntimeModule module, int tk, PackingSize iPackingSize, int iTypeSize);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private static extern unsafe void SetConstantValue(RuntimeModule module, int tk, int corType, void* pValue);
-#endregion
-#region Internal\Private Static Members
+ #endregion
+ #region Internal\Private Static Members
[Pure]
internal static bool IsTypeEqual(Type t1, Type t2)
@@ -273,14 +275,14 @@ namespace System.Reflection.Emit {
if (t1 == t2)
return true;
TypeBuilder tb1 = null;
- TypeBuilder tb2 = null;
- Type runtimeType1 = null;
- Type runtimeType2 = null;
-
+ TypeBuilder tb2 = null;
+ Type runtimeType1 = null;
+ Type runtimeType2 = null;
+
// set up the runtimeType and TypeBuilder type corresponding to t1 and t2
if (t1 is TypeBuilder)
{
- tb1 =(TypeBuilder)t1;
+ tb1 = (TypeBuilder)t1;
// This will be null if it is not baked.
runtimeType1 = tb1.m_bakedRuntimeType;
}
@@ -291,7 +293,7 @@ namespace System.Reflection.Emit {
if (t2 is TypeBuilder)
{
- tb2 =(TypeBuilder)t2;
+ tb2 = (TypeBuilder)t2;
// This will be null if it is not baked.
runtimeType2 = tb2.m_bakedRuntimeType;
}
@@ -299,16 +301,16 @@ namespace System.Reflection.Emit {
{
runtimeType2 = t2;
}
-
+
// If the type builder view is eqaul then it is equal
if (tb1 != null && tb2 != null && Object.ReferenceEquals(tb1, tb2))
return true;
// if the runtimetype view is eqaul than it is equal
- if (runtimeType1 != null && runtimeType2 != null && runtimeType1 == runtimeType2)
+ if (runtimeType1 != null && runtimeType2 != null && runtimeType1 == runtimeType2)
return true;
- return false;
+ return false;
}
internal static unsafe void SetConstantValue(ModuleBuilder module, int tk, Type destType, Object value)
@@ -349,7 +351,7 @@ namespace System.Reflection.Emit {
// The constant value supplied should match either the baked enum type or its underlying type
// we don't need to compare it with the EnumBuilder itself because you can never have an object of that type
if (type != enumBldr.m_typeBuilder.m_bakedRuntimeType && type != underlyingType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
else if ((typeBldr = destType as TypeBuilder) != null)
{
@@ -358,7 +360,7 @@ namespace System.Reflection.Emit {
// The constant value supplied should match either the baked enum type or its underlying type
// typeBldr.m_enumUnderlyingType is null if the user hasn't created a "value__" field on the enum
if (underlyingType == null || (type != typeBldr.UnderlyingSystemType && type != underlyingType))
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
else // must be a runtime Enum Type
{
@@ -368,7 +370,7 @@ namespace System.Reflection.Emit {
// The constant value supplied should match either the enum itself or its underlying type
if (type != destType && type != underlyingType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
type = underlyingType;
@@ -377,9 +379,9 @@ namespace System.Reflection.Emit {
{
// Note that it is non CLS compliant if destType != type. But RefEmit never guarantees CLS-Compliance.
if (!destType.IsAssignableFrom(type))
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantDoesntMatch"));
+ throw new ArgumentException(SR.Argument_ConstantDoesntMatch);
}
-
+
CorElementType corType = RuntimeTypeHandle.GetCorElementType((RuntimeType)type);
switch (corType)
@@ -414,7 +416,7 @@ namespace System.Reflection.Emit {
}
else
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNotSupported", type.ToString()));
+ throw new ArgumentException(SR.Format(SR.Argument_ConstantNotSupported, type.ToString()));
}
break;
}
@@ -425,7 +427,7 @@ namespace System.Reflection.Emit {
{
// nullable types can hold null value.
if (!(destType.IsGenericType && destType.GetGenericTypeDefinition() == typeof(Nullable<>)))
- throw new ArgumentException(Environment.GetResourceString("Argument_ConstantNull"));
+ throw new ArgumentException(SR.Argument_ConstantNull);
}
SetConstantValue(module.GetNativeHandle(), tk, (int)CorElementType.Class, null);
@@ -436,7 +438,7 @@ namespace System.Reflection.Emit {
#region Private Data Members
private List<CustAttr> m_ca;
- private TypeToken m_tdType;
+ private TypeToken m_tdType;
private ModuleBuilder m_module;
private String m_strName;
private String m_strNameSpace;
@@ -483,8 +485,8 @@ namespace System.Reflection.Emit {
{
Contract.Requires(declMeth != null);
m_declMeth = declMeth;
- m_DeclaringType =m_declMeth.GetTypeBuilder();
- m_module =declMeth.GetModuleBuilder();
+ m_DeclaringType = m_declMeth.GetTypeBuilder();
+ m_module = declMeth.GetModuleBuilder();
InitAsGenericParam(szName, genParamPos);
}
@@ -493,7 +495,7 @@ namespace System.Reflection.Emit {
{
Contract.Requires(declType != null);
m_DeclaringType = declType;
- m_module =declType.GetModuleBuilder();
+ m_module = declType.GetModuleBuilder();
InitAsGenericParam(szName, genParamPos);
}
@@ -512,7 +514,7 @@ namespace System.Reflection.Emit {
Type[] interfaces,
ModuleBuilder module,
PackingSize iPackingSize,
- int iTypeSize,
+ int iTypeSize,
TypeBuilder enclosingType)
{
Init(name, attr, parent, interfaces, module, iPackingSize, iTypeSize, enclosingType);
@@ -525,14 +527,14 @@ namespace System.Reflection.Emit {
throw new ArgumentNullException(nameof(fullname));
if (fullname.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(fullname));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(fullname));
if (fullname[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(fullname));
+ throw new ArgumentException(SR.Argument_IllegalName, nameof(fullname));
if (fullname.Length > 1023)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNameTooLong"), nameof(fullname));
+ throw new ArgumentException(SR.Argument_TypeNameTooLong, nameof(fullname));
Contract.EndContractBlock();
int i;
@@ -547,14 +549,14 @@ namespace System.Reflection.Emit {
{
// Nested Type should have nested attribute set.
// If we are renumbering TypeAttributes' bit, we need to change the logic here.
- if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
- throw new ArgumentException(Environment.GetResourceString("Argument_BadNestedTypeFlags"), nameof(attr));
+ if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) || ((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic))
+ throw new ArgumentException(SR.Argument_BadNestedTypeFlags, nameof(attr));
}
int[] interfaceTokens = null;
if (interfaces != null)
{
- for(i = 0; i < interfaces.Length; i++)
+ for (i = 0; i < interfaces.Length; i++)
{
if (interfaces[i] == null)
{
@@ -563,7 +565,7 @@ namespace System.Reflection.Emit {
}
}
interfaceTokens = new int[interfaces.Length + 1];
- for(i = 0; i < interfaces.Length; i++)
+ for (i = 0; i < interfaces.Length; i++)
{
interfaceTokens[i] = m_module.GetTypeTokenInternal(interfaces[i]).Token;
}
@@ -609,14 +611,14 @@ namespace System.Reflection.Emit {
m_iPackingSize = iPackingSize;
m_iTypeSize = iTypeSize;
- if ((m_iPackingSize != 0) ||(m_iTypeSize != 0))
+ if ((m_iPackingSize != 0) || (m_iTypeSize != 0))
SetClassLayout(GetModuleBuilder().GetNativeHandle(), m_tdType.Token, m_iPackingSize, m_iTypeSize);
m_module.AddType(FullName, this);
}
-#endregion
-#region Private Members
+ #endregion
+ #region Private Members
private FieldBuilder DefineDataHelper(String name, byte[] data, int size, FieldAttributes attributes)
{
@@ -629,10 +631,10 @@ namespace System.Reflection.Emit {
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (size <= 0 || size >= 0x003f0000)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadSizeForData"));
+ throw new ArgumentException(SR.Argument_BadSizeForData);
Contract.EndContractBlock();
ThrowIfCreated();
@@ -653,7 +655,7 @@ namespace System.Reflection.Emit {
valueClassType.CreateType();
}
- fdBuilder = DefineField(name, valueClassType,(attributes | FieldAttributes.Static));
+ fdBuilder = DefineField(name, valueClassType, (attributes | FieldAttributes.Static));
// now we need to set the RVA
fdBuilder.SetData(data, size);
@@ -666,54 +668,54 @@ namespace System.Reflection.Emit {
if (DeclaringType == null)
{
// Not a nested class.
- if (((attr & TypeAttributes.VisibilityMask) != TypeAttributes.NotPublic) &&((attr & TypeAttributes.VisibilityMask) != TypeAttributes.Public))
+ if (((attr & TypeAttributes.VisibilityMask) != TypeAttributes.NotPublic) && ((attr & TypeAttributes.VisibilityMask) != TypeAttributes.Public))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrNestedVisibilityOnNonNestedType"));
+ throw new ArgumentException(SR.Argument_BadTypeAttrNestedVisibilityOnNonNestedType);
}
}
else
{
// Nested class.
- if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic) ||((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public))
+ if (((attr & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic) || ((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrNonNestedVisibilityNestedType"));
+ throw new ArgumentException(SR.Argument_BadTypeAttrNonNestedVisibilityNestedType);
}
}
// Verify that the layout mask is valid.
- if (((attr & TypeAttributes.LayoutMask) != TypeAttributes.AutoLayout) &&((attr & TypeAttributes.LayoutMask) != TypeAttributes.SequentialLayout) &&((attr & TypeAttributes.LayoutMask) != TypeAttributes.ExplicitLayout))
+ if (((attr & TypeAttributes.LayoutMask) != TypeAttributes.AutoLayout) && ((attr & TypeAttributes.LayoutMask) != TypeAttributes.SequentialLayout) && ((attr & TypeAttributes.LayoutMask) != TypeAttributes.ExplicitLayout))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrInvalidLayout"));
+ throw new ArgumentException(SR.Argument_BadTypeAttrInvalidLayout);
}
// Check if the user attempted to set any reserved bits.
if ((attr & TypeAttributes.ReservedMask) != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_BadTypeAttrReservedBitsSet"));
+ throw new ArgumentException(SR.Argument_BadTypeAttrReservedBitsSet);
}
}
[Pure]
public bool IsCreated()
- {
+ {
return m_hasBeenCreated;
}
-
+
#endregion
#region FCalls
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private extern static int DefineType(RuntimeModule module,
String fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private extern static int DefineGenericParam(RuntimeModule module,
String name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private static extern void TermCreateClass(RuntimeModule module, int tk, ObjectHandleOnStack type);
#endregion
@@ -721,7 +723,7 @@ namespace System.Reflection.Emit {
internal void ThrowIfCreated()
{
if (IsCreated())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_TypeHasBeenCreated"));
+ throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated);
}
internal object SyncRoot
@@ -749,12 +751,12 @@ namespace System.Reflection.Emit {
{
m_genParamAttributes = genericParameterAttributes;
}
-
+
internal void SetGenParamCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
CustAttr ca = new CustAttr(con, binaryAttribute);
- lock(SyncRoot)
+ lock (SyncRoot)
{
SetGenParamCustomAttributeNoLock(ca);
}
@@ -764,7 +766,7 @@ namespace System.Reflection.Emit {
{
CustAttr ca = new CustAttr(customBuilder);
- lock(SyncRoot)
+ lock (SyncRoot)
{
SetGenParamCustomAttributeNoLock(ca);
}
@@ -774,7 +776,7 @@ namespace System.Reflection.Emit {
{
if (m_ca == null)
m_ca = new List<TypeBuilder.CustAttr>();
-
+
m_ca.Add(ca);
}
#endregion
@@ -782,30 +784,30 @@ namespace System.Reflection.Emit {
#region Object Overrides
public override String ToString()
{
- return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
+ return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString);
}
#endregion
#region MemberInfo Overrides
- public override Type DeclaringType
+ public override Type DeclaringType
{
get { return m_DeclaringType; }
}
- public override Type ReflectedType
+ public override Type ReflectedType
{
// Return the class that was used to obtain this field.
-
+
get { return m_DeclaringType; }
}
- public override String Name
+ public override String Name
{
get { return m_strName; }
}
- public override Module Module
+ public override Module Module
{
get { return GetModuleBuilder(); }
}
@@ -818,12 +820,12 @@ namespace System.Reflection.Emit {
#endregion
#region Type Overrides
- public override Guid GUID
+ public override Guid GUID
{
- get
+ get
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GUID;
@@ -834,27 +836,26 @@ namespace System.Reflection.Emit {
Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters);
}
- public override Assembly Assembly
+ public override Assembly Assembly
{
get { return m_module.Assembly; }
}
- public override RuntimeTypeHandle TypeHandle
+ public override RuntimeTypeHandle TypeHandle
{
-
- get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule")); }
+ get { throw new NotSupportedException(SR.NotSupported_DynamicModule); }
}
- public override String FullName
+ public override String FullName
{
- get
- {
+ get
+ {
if (m_strFullQualName == null)
m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
@@ -862,29 +863,29 @@ namespace System.Reflection.Emit {
}
}
- public override String Namespace
+ public override String Namespace
{
get { return m_strNameSpace; }
}
- public override String AssemblyQualifiedName
+ public override String AssemblyQualifiedName
{
- get
- {
+ get
+ {
return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName);
}
}
- public override Type BaseType
+ public override Type BaseType
{
- get{ return m_typeParent; }
+ get { return m_typeParent; }
}
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
+ protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers);
@@ -893,17 +894,17 @@ namespace System.Reflection.Emit {
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetConstructors(bindingAttr);
}
- protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
+ protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
if (types == null)
@@ -919,7 +920,7 @@ namespace System.Reflection.Emit {
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetMethods(bindingAttr);
@@ -928,7 +929,7 @@ namespace System.Reflection.Emit {
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetField(name, bindingAttr);
@@ -937,18 +938,18 @@ namespace System.Reflection.Emit {
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetFields(bindingAttr);
}
- public override Type GetInterface(String name,bool ignoreCase)
+ public override Type GetInterface(String name, bool ignoreCase)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
-
+
return m_bakedRuntimeType.GetInterface(name, ignoreCase);
}
@@ -961,16 +962,16 @@ namespace System.Reflection.Emit {
if (m_typeInterfaces == null)
{
- return EmptyArray<Type>.Value;
+ return Array.Empty<Type>();
}
return m_typeInterfaces.ToArray();
}
- public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
+ public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetEvent(name, bindingAttr);
@@ -979,7 +980,7 @@ namespace System.Reflection.Emit {
public override EventInfo[] GetEvents()
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetEvents();
@@ -988,13 +989,13 @@ namespace System.Reflection.Emit {
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetProperties(bindingAttr);
@@ -1003,7 +1004,7 @@ namespace System.Reflection.Emit {
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetNestedTypes(bindingAttr);
@@ -1012,16 +1013,16 @@ namespace System.Reflection.Emit {
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
- return m_bakedRuntimeType.GetNestedType(name,bindingAttr);
+ return m_bakedRuntimeType.GetNestedType(name, bindingAttr);
}
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetMember(name, type, bindingAttr);
@@ -1030,7 +1031,7 @@ namespace System.Reflection.Emit {
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetInterfaceMap(interfaceType);
@@ -1039,7 +1040,7 @@ namespace System.Reflection.Emit {
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetEvents(bindingAttr);
@@ -1048,66 +1049,68 @@ namespace System.Reflection.Emit {
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return m_bakedRuntimeType.GetMembers(bindingAttr);
}
-
+
public override bool IsAssignableFrom(Type c)
{
if (TypeBuilder.IsTypeEqual(c, this))
return true;
-
+
Type fromRuntimeType = null;
TypeBuilder fromTypeBuilder = c as TypeBuilder;
-
+
if (fromTypeBuilder != null)
fromRuntimeType = fromTypeBuilder.m_bakedRuntimeType;
else
fromRuntimeType = c;
-
+
if (fromRuntimeType != null && fromRuntimeType is RuntimeType)
{
// fromType is baked. So if this type is not baked, it cannot be assignable to!
if (m_bakedRuntimeType == null)
return false;
-
+
// since toType is also baked, delegate to the base
return m_bakedRuntimeType.IsAssignableFrom(fromRuntimeType);
}
-
+
// So if c is not a runtimeType nor TypeBuilder. We don't know how to deal with it.
// return false then.
if (fromTypeBuilder == null)
return false;
-
+
// If fromTypeBuilder is a subclass of this class, then c can be cast to this type.
if (fromTypeBuilder.IsSubclassOf(this))
return true;
-
+
if (this.IsInterface == false)
return false;
-
+
// now is This type a base type on one of the interface impl?
Type[] interfaces = fromTypeBuilder.GetInterfaces();
- for(int i = 0; i < interfaces.Length; i++)
+ for (int i = 0; i < interfaces.Length; i++)
{
// unfortunately, IsSubclassOf does not cover the case when they are the same type.
if (TypeBuilder.IsTypeEqual(interfaces[i], this))
return true;
-
+
if (interfaces[i].IsSubclassOf(this))
return true;
}
- return false;
- }
+ return false;
+ }
protected override TypeAttributes GetAttributeFlagsImpl()
{
return m_iAttr;
}
+ public override bool IsSZArray => false;
+
protected override bool IsArrayImpl()
{
return false;
@@ -1127,14 +1130,13 @@ namespace System.Reflection.Emit {
protected override bool IsCOMObjectImpl()
{
- return((GetAttributeFlagsImpl() & TypeAttributes.Import) != 0) ? true : false;
+ return ((GetAttributeFlagsImpl() & TypeAttributes.Import) != 0) ? true : false;
}
public override Type GetElementType()
{
-
// You will never have to deal with a TypeBuilder if you are just referring to arrays.
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
}
protected override bool HasElementTypeImpl()
@@ -1165,9 +1167,9 @@ namespace System.Reflection.Emit {
if (TypeBuilder.IsTypeEqual(p, c))
return false;
- p = p.BaseType;
-
- while(p != null)
+ p = p.BaseType;
+
+ while (p != null)
{
if (TypeBuilder.IsTypeEqual(p, c))
return true;
@@ -1177,10 +1179,10 @@ namespace System.Reflection.Emit {
return false;
}
-
- public override Type UnderlyingSystemType
+
+ public override Type UnderlyingSystemType
{
- get
+ get
{
if (m_bakedRuntimeType != null)
return m_bakedRuntimeType;
@@ -1188,9 +1190,9 @@ namespace System.Reflection.Emit {
if (IsEnum)
{
if (m_enumUnderlyingType == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoUnderlyingTypeOnEnum"));
-
- return m_enumUnderlyingType;
+ throw new InvalidOperationException(SR.InvalidOperation_NoUnderlyingTypeOnEnum);
+
+ return m_enumUnderlyingType;
}
else
{
@@ -1199,22 +1201,22 @@ namespace System.Reflection.Emit {
}
}
- public override Type MakePointerType()
- {
- return SymbolType.FormCompoundType("*", this, 0);
+ public override Type MakePointerType()
+ {
+ return SymbolType.FormCompoundType("*", this, 0);
}
- public override Type MakeByRefType()
+ public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
- public override Type MakeArrayType()
+ public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
- public override Type MakeArrayType(int rank)
+ public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
@@ -1225,9 +1227,9 @@ namespace System.Reflection.Emit {
{
szrank = "*";
}
- else
+ else
{
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
szrank += ",";
}
@@ -1241,7 +1243,7 @@ namespace System.Reflection.Emit {
public override Object[] GetCustomAttributes(bool inherit)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
Contract.EndContractBlock();
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit);
@@ -1250,7 +1252,7 @@ namespace System.Reflection.Emit {
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
@@ -1259,7 +1261,7 @@ namespace System.Reflection.Emit {
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
@@ -1267,7 +1269,7 @@ namespace System.Reflection.Emit {
public override bool IsDefined(Type attributeType, bool inherit)
{
if (!IsCreated())
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_TypeNotYetCreated"));
+ throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated);
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
@@ -1276,7 +1278,7 @@ namespace System.Reflection.Emit {
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(m_bakedRuntimeType, attributeRuntimeType, inherit);
}
@@ -1284,12 +1286,12 @@ namespace System.Reflection.Emit {
#endregion
#region Public Member
-
+
#region DefineType
public override GenericParameterAttributes GenericParameterAttributes { get { return m_genParamAttributes; } }
- internal void SetInterfaces(params Type[] interfaces)
- {
+ internal void SetInterfaces(params Type[] interfaces)
+ {
ThrowIfCreated();
m_typeInterfaces = new List<Type>();
@@ -1308,8 +1310,8 @@ namespace System.Reflection.Emit {
if (names.Length == 0)
throw new ArgumentException();
Contract.EndContractBlock();
-
- for (int i = 0; i < names.Length; i ++)
+
+ for (int i = 0; i < names.Length; i++)
if (names[i] == null)
throw new ArgumentNullException(nameof(names));
@@ -1317,25 +1319,25 @@ namespace System.Reflection.Emit {
throw new InvalidOperationException();
m_inst = new GenericTypeParameterBuilder[names.Length];
- for(int i = 0; i < names.Length; i ++)
+ for (int i = 0; i < names.Length; i++)
m_inst[i] = new GenericTypeParameterBuilder(new TypeBuilder(names[i], i, this));
return m_inst;
}
-
- public override Type MakeGenericType(params Type[] typeArguments)
- {
+
+ public override Type MakeGenericType(params Type[] typeArguments)
+ {
CheckContext(typeArguments);
-
- return TypeBuilderInstantiation.MakeGenericType(this, typeArguments);
+
+ return TypeBuilderInstantiation.MakeGenericType(this, typeArguments);
}
-
+
public override Type[] GetGenericArguments() { return m_inst; }
// If a TypeBuilder is generic, it must be a generic type definition
// All instantiated generic types are TypeBuilderInstantiation.
public override bool IsGenericTypeDefinition { get { return IsGenericType; } }
- public override bool IsGenericType { get { return m_inst != null; } }
+ public override bool IsGenericType { get { return m_inst != null; } }
public override bool IsGenericParameter { get { return m_bIsGenParam; } }
public override bool IsConstructedGenericType { get { return false; } }
@@ -1347,7 +1349,7 @@ namespace System.Reflection.Emit {
#region Define Method
public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
DefineMethodOverrideNoLock(methodInfoBody, methodInfoDeclaration);
}
@@ -1363,13 +1365,13 @@ namespace System.Reflection.Emit {
Contract.EndContractBlock();
ThrowIfCreated();
-
+
if (!object.ReferenceEquals(methodInfoBody.DeclaringType, this))
// Loader restriction: body method has to be from this class
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_BadMethodImplBody"));
-
- MethodToken tkBody;
- MethodToken tkDecl;
+ throw new ArgumentException(SR.ArgumentException_BadMethodImplBody);
+
+ MethodToken tkBody;
+ MethodToken tkDecl;
tkBody = m_module.GetMethodTokenInternal(methodInfoBody);
tkDecl = m_module.GetMethodTokenInternal(methodInfoDeclaration);
@@ -1405,21 +1407,21 @@ namespace System.Reflection.Emit {
return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
-
+
public MethodBuilder DefineMethod(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
Contract.Ensures(Contract.Result<MethodBuilder>() != null);
- lock(SyncRoot)
+ lock (SyncRoot)
{
- return DefineMethodNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers,
- returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,
+ return DefineMethodNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers,
+ returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers,
parameterTypeOptionalCustomModifiers);
}
}
-
+
private MethodBuilder DefineMethodNoLock(String name, MethodAttributes attributes, CallingConventions callingConvention,
Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
@@ -1428,7 +1430,7 @@ namespace System.Reflection.Emit {
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
Contract.Ensures(Contract.Result<MethodBuilder>() != null);
Contract.EndContractBlock();
@@ -1440,10 +1442,10 @@ namespace System.Reflection.Emit {
if (parameterTypes != null)
{
if (parameterTypeOptionalCustomModifiers != null && parameterTypeOptionalCustomModifiers.Length != parameterTypes.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeOptionalCustomModifiers), nameof(parameterTypes)));
+ throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, nameof(parameterTypeOptionalCustomModifiers), nameof(parameterTypes)));
if (parameterTypeRequiredCustomModifiers != null && parameterTypeRequiredCustomModifiers.Length != parameterTypes.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", nameof(parameterTypeRequiredCustomModifiers), nameof(parameterTypes)));
+ throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, nameof(parameterTypeRequiredCustomModifiers), nameof(parameterTypes)));
}
ThrowIfCreated();
@@ -1451,21 +1453,21 @@ namespace System.Reflection.Emit {
if (!m_isHiddenGlobalType)
{
if (((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface) &&
- (attributes & MethodAttributes.Abstract) == 0 &&(attributes & MethodAttributes.Static) == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_BadAttributeOnInterfaceMethod"));
+ (attributes & MethodAttributes.Abstract) == 0 && (attributes & MethodAttributes.Static) == 0)
+ throw new ArgumentException(SR.Argument_BadAttributeOnInterfaceMethod);
}
// pass in Method attributes
MethodBuilder method = new MethodBuilder(
- name, attributes, callingConvention,
+ name, attributes, callingConvention,
returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
- parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
+ parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers,
m_module, this, false);
if (!m_isHiddenGlobalType)
{
//If this method is declared to be a constructor, increment our constructor count.
- if ((method.Attributes & MethodAttributes.SpecialName) != 0 && method.Name.Equals(ConstructorInfo.ConstructorName))
+ if ((method.Attributes & MethodAttributes.SpecialName) != 0 && method.Name.Equals(ConstructorInfo.ConstructorName))
{
m_constructorCount++;
}
@@ -1481,7 +1483,7 @@ namespace System.Reflection.Emit {
#region Define Constructor
public ConstructorBuilder DefineTypeInitializer()
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineTypeInitializerNoLock();
}
@@ -1504,10 +1506,10 @@ namespace System.Reflection.Emit {
{
if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ConstructorNotAllowedOnInterface"));
+ throw new InvalidOperationException(SR.InvalidOperation_ConstructorNotAllowedOnInterface);
}
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineDefaultConstructorNoLock(attributes);
}
@@ -1533,14 +1535,14 @@ namespace System.Reflection.Emit {
genericTypeDefinition = ((TypeBuilder)genericTypeDefinition).m_bakedRuntimeType;
if (genericTypeDefinition == null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_DynamicModule"));
+ throw new NotSupportedException(SR.NotSupported_DynamicModule);
Type inst = genericTypeDefinition.MakeGenericType(m_typeParent.GetGenericArguments());
if (inst is TypeBuilderInstantiation)
con = TypeBuilder.GetConstructor(inst, genericTypeDefinition.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null));
- else
+ else
con = inst.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
}
@@ -1551,7 +1553,7 @@ namespace System.Reflection.Emit {
}
if (con == null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NoParentDefaultConstructor"));
+ throw new NotSupportedException(SR.NotSupported_NoParentDefaultConstructor);
// Define the constructor Builder
constBuilder = DefineConstructor(attributes, CallingConventions.Standard, null);
@@ -1560,7 +1562,7 @@ namespace System.Reflection.Emit {
// generate the code to call the parent's default constructor
ILGenerator il = constBuilder.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
- il.Emit(OpCodes.Call,con);
+ il.Emit(OpCodes.Call, con);
il.Emit(OpCodes.Ret);
constBuilder.m_isDefaultConstructor = true;
@@ -1572,21 +1574,21 @@ namespace System.Reflection.Emit {
return DefineConstructor(attributes, callingConvention, parameterTypes, null, null);
}
- public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention,
+ public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
if ((m_iAttr & TypeAttributes.Interface) == TypeAttributes.Interface && (attributes & MethodAttributes.Static) != MethodAttributes.Static)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ConstructorNotAllowedOnInterface"));
+ throw new InvalidOperationException(SR.InvalidOperation_ConstructorNotAllowedOnInterface);
}
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineConstructorNoLock(attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers);
}
}
- private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention,
+ private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention,
Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
{
CheckContext(parameterTypes);
@@ -1608,8 +1610,8 @@ namespace System.Reflection.Emit {
attributes = attributes | MethodAttributes.SpecialName;
- ConstructorBuilder constBuilder =
- new ConstructorBuilder(name, attributes, callingConvention,
+ ConstructorBuilder constBuilder =
+ new ConstructorBuilder(name, attributes, callingConvention,
parameterTypes, requiredCustomModifiers, optionalCustomModifiers, m_module, this);
m_constructorCount++;
@@ -1622,7 +1624,7 @@ namespace System.Reflection.Emit {
#region Define Nested Type
public TypeBuilder DefineNestedType(String name)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineNestedTypeNoLock(name, TypeAttributes.NestedPrivate, null, null, PackingSize.Unspecified, UnspecifiedTypeSize);
}
@@ -1630,7 +1632,7 @@ namespace System.Reflection.Emit {
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, Type[] interfaces)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
// Why do we only call CheckContext here? Why don't we call it in the other overloads?
CheckContext(parent);
@@ -1642,7 +1644,7 @@ namespace System.Reflection.Emit {
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineNestedTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, UnspecifiedTypeSize);
}
@@ -1650,7 +1652,7 @@ namespace System.Reflection.Emit {
public TypeBuilder DefineNestedType(String name, TypeAttributes attr)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineNestedTypeNoLock(name, attr, null, null, PackingSize.Unspecified, UnspecifiedTypeSize);
}
@@ -1658,7 +1660,7 @@ namespace System.Reflection.Emit {
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, int typeSize)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineNestedTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typeSize);
}
@@ -1666,7 +1668,7 @@ namespace System.Reflection.Emit {
public TypeBuilder DefineNestedType(String name, TypeAttributes attr, Type parent, PackingSize packSize)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineNestedTypeNoLock(name, attr, parent, null, packSize, UnspecifiedTypeSize);
}
@@ -1688,22 +1690,22 @@ namespace System.Reflection.Emit {
#endregion
#region Define Field
- public FieldBuilder DefineField(String fieldName, Type type, FieldAttributes attributes)
+ public FieldBuilder DefineField(String fieldName, Type type, FieldAttributes attributes)
{
return DefineField(fieldName, type, null, null, attributes);
}
- public FieldBuilder DefineField(String fieldName, Type type, Type[] requiredCustomModifiers,
- Type[] optionalCustomModifiers, FieldAttributes attributes)
+ public FieldBuilder DefineField(String fieldName, Type type, Type[] requiredCustomModifiers,
+ Type[] optionalCustomModifiers, FieldAttributes attributes)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineFieldNoLock(fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes);
}
}
- private FieldBuilder DefineFieldNoLock(String fieldName, Type type, Type[] requiredCustomModifiers,
- Type[] optionalCustomModifiers, FieldAttributes attributes)
+ private FieldBuilder DefineFieldNoLock(String fieldName, Type type, Type[] requiredCustomModifiers,
+ Type[] optionalCustomModifiers, FieldAttributes attributes)
{
ThrowIfCreated();
CheckContext(type);
@@ -1715,7 +1717,7 @@ namespace System.Reflection.Emit {
{
// remember the underlying type for enum type
m_enumUnderlyingType = type;
- }
+ }
}
return new FieldBuilder(this, fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes);
@@ -1723,7 +1725,7 @@ namespace System.Reflection.Emit {
public FieldBuilder DefineInitializedData(String name, byte[] data, FieldAttributes attributes)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineInitializedDataNoLock(name, data, attributes);
}
@@ -1744,7 +1746,7 @@ namespace System.Reflection.Emit {
public FieldBuilder DefineUninitializedData(String name, int size, FieldAttributes attributes)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineUninitializedDataNoLock(name, size, attributes);
}
@@ -1763,44 +1765,44 @@ namespace System.Reflection.Emit {
#region Define Properties and Events
public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, Type returnType, Type[] parameterTypes)
{
- return DefineProperty(name, attributes, returnType, null, null, parameterTypes, null, null);
+ return DefineProperty(name, attributes, returnType, null, null, parameterTypes, null, null);
}
- public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes,
+ public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes,
CallingConventions callingConvention, Type returnType, Type[] parameterTypes)
{
- return DefineProperty(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
+ return DefineProperty(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null);
}
- public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
+ public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes,
+ Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
- return DefineProperty(name, attributes, (CallingConventions)0, returnType,
- returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
- parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
+ return DefineProperty(name, attributes, (CallingConventions)0, returnType,
+ returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
+ parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
}
- public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
+ public PropertyBuilder DefineProperty(String name, PropertyAttributes attributes, CallingConventions callingConvention,
+ Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
- return DefinePropertyNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
+ return DefinePropertyNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers,
parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers);
}
}
private PropertyBuilder DefinePropertyNoLock(String name, PropertyAttributes attributes, CallingConventions callingConvention,
- Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
+ Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers,
Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
Contract.EndContractBlock();
CheckContext(returnType);
@@ -1809,8 +1811,8 @@ namespace System.Reflection.Emit {
CheckContext(parameterTypeOptionalCustomModifiers);
SignatureHelper sigHelper;
- int sigLength;
- byte[] sigBytes;
+ int sigLength;
+ byte[] sigBytes;
ThrowIfCreated();
@@ -1844,7 +1846,7 @@ namespace System.Reflection.Emit {
public EventBuilder DefineEvent(String name, EventAttributes attributes, Type eventtype)
{
- lock(SyncRoot)
+ lock (SyncRoot)
{
return DefineEventNoLock(name, attributes, eventtype);
}
@@ -1855,19 +1857,19 @@ namespace System.Reflection.Emit {
if (name == null)
throw new ArgumentNullException(nameof(name));
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Argument_IllegalName"), nameof(name));
+ throw new ArgumentException(SR.Argument_IllegalName, nameof(name));
Contract.EndContractBlock();
int tkType;
- EventToken evToken;
-
+ EventToken evToken;
+
CheckContext(eventtype);
ThrowIfCreated();
- tkType = m_module.GetTypeTokenInternal( eventtype ).Token;
+ tkType = m_module.GetTypeTokenInternal(eventtype).Token;
// Internal helpers to define property records
evToken = new EventToken(DefineEvent(
@@ -1909,7 +1911,7 @@ namespace System.Reflection.Emit {
internal void CheckContext(params Type[][] typess)
{
- m_module.CheckContext(typess);
+ m_module.CheckContext(typess);
}
internal void CheckContext(params Type[] types)
{
@@ -1927,7 +1929,7 @@ namespace System.Reflection.Emit {
m_typeInterfaces = new List<Type>();
int[] interfaceTokens = new int[m_typeInterfaces.Count];
- for(int i = 0; i < m_typeInterfaces.Count; i++)
+ for (int i = 0; i < m_typeInterfaces.Count; i++)
{
interfaceTokens[i] = m_module.GetTypeTokenInternal(m_typeInterfaces[i]).Token;
}
@@ -1976,16 +1978,16 @@ namespace System.Reflection.Emit {
// Check for global typebuilder
if (((m_tdType.Token & 0x00FFFFFF) != 0) && ((tkParent & 0x00FFFFFF) != 0))
SetParentType(m_module.GetNativeHandle(), m_tdType.Token, tkParent);
-
+
if (m_inst != null)
foreach (Type tb in m_inst)
if (tb is GenericTypeParameterBuilder)
((GenericTypeParameterBuilder)tb).m_type.CreateType();
}
- byte [] body;
+ byte[] body;
MethodAttributes methodAttrs;
-
+
if (!m_isHiddenGlobalType)
{
// create a public default constructor if this class has no constructor.
@@ -1998,7 +2000,7 @@ namespace System.Reflection.Emit {
int size = m_listMethods.Count;
- for(int i = 0; i < size; i++)
+ for (int i = 0; i < size; i++)
{
MethodBuilder meth = m_listMethods[i];
@@ -2009,19 +2011,19 @@ namespace System.Reflection.Emit {
methodAttrs = meth.Attributes;
// Any of these flags in the implemenation flags is set, we will not attach the IL method body
- if (((meth.GetMethodImplementationFlags() &(MethodImplAttributes.CodeTypeMask|MethodImplAttributes.PreserveSig|MethodImplAttributes.Unmanaged)) != MethodImplAttributes.IL) ||
- ((methodAttrs & MethodAttributes.PinvokeImpl) !=(MethodAttributes) 0))
+ if (((meth.GetMethodImplementationFlags() & (MethodImplAttributes.CodeTypeMask | MethodImplAttributes.PreserveSig | MethodImplAttributes.Unmanaged)) != MethodImplAttributes.IL) ||
+ ((methodAttrs & MethodAttributes.PinvokeImpl) != (MethodAttributes)0))
{
continue;
}
int sigLength;
byte[] localSig = meth.GetLocalSignature(out sigLength);
-
+
// Check that they haven't declared an abstract method on a non-abstract class
- if (((methodAttrs & MethodAttributes.Abstract) != 0) &&((m_iAttr & TypeAttributes.Abstract) == 0))
+ if (((methodAttrs & MethodAttributes.Abstract) != 0) && ((m_iAttr & TypeAttributes.Abstract) == 0))
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadTypeAttributesNotAbstract"));
+ throw new InvalidOperationException(SR.InvalidOperation_BadTypeAttributesNotAbstract);
}
body = meth.GetBody();
@@ -2036,7 +2038,7 @@ namespace System.Reflection.Emit {
//((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface))
if (body != null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadMethodBody"));
+ throw new InvalidOperationException(SR.InvalidOperation_BadMethodBody);
}
else if (body == null || body.Length == 0)
{
@@ -2051,7 +2053,7 @@ namespace System.Reflection.Emit {
if ((body == null || body.Length == 0) && !meth.m_canBeRuntimeImpl)
throw new InvalidOperationException(
- Environment.GetResourceString("InvalidOperation_BadEmptyMethodBody", meth.Name) );
+ SR.Format(SR.InvalidOperation_BadEmptyMethodBody, meth.Name));
}
int maxStack = meth.GetMaxStack();
@@ -2059,7 +2061,7 @@ namespace System.Reflection.Emit {
ExceptionHandler[] exceptions = meth.GetExceptionHandlers();
int[] tokenFixups = meth.GetTokenFixups();
- SetMethodIL(m_module.GetNativeHandle(), meth.GetToken().Token, meth.InitLocals,
+ SetMethodIL(m_module.GetNativeHandle(), meth.GetToken().Token, meth.InitLocals,
body, (body != null) ? body.Length : 0,
localSig, sigLength, maxStack,
exceptions, (exceptions != null) ? exceptions.Length : 0,
@@ -2086,7 +2088,7 @@ namespace System.Reflection.Emit {
// if this type is a nested type, we need to invalidate the cached nested runtime type on the nesting type
if (m_DeclaringType != null && m_DeclaringType.m_bakedRuntimeType != null)
{
- m_DeclaringType.m_bakedRuntimeType.InvalidateCachedNestedType();
+ m_DeclaringType.m_bakedRuntimeType.InvalidateCachedNestedType();
}
return cls;
@@ -2104,8 +2106,8 @@ namespace System.Reflection.Emit {
{
get { return m_iTypeSize; }
}
-
- public PackingSize PackingSize
+
+ public PackingSize PackingSize
{
get { return m_iPackingSize; }
}
@@ -2119,7 +2121,7 @@ namespace System.Reflection.Emit {
CheckContext(parent);
if (parent.IsInterface)
- throw new ArgumentException(Environment.GetResourceString("Argument_CannotSetParentToInterface"));
+ throw new ArgumentException(SR.Argument_CannotSetParentToInterface);
m_typeParent = parent;
}
@@ -2132,7 +2134,7 @@ namespace System.Reflection.Emit {
else
{
if ((m_iAttr & TypeAttributes.Abstract) == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_BadInterfaceNotAbstract"));
+ throw new InvalidOperationException(SR.InvalidOperation_BadInterfaceNotAbstract);
// there is no extends for interface class
m_typeParent = null;
@@ -2149,7 +2151,7 @@ namespace System.Reflection.Emit {
Contract.EndContractBlock();
CheckContext(interfaceType);
-
+
ThrowIfCreated();
TypeToken tkInterface = m_module.GetTypeTokenInternal(interfaceType);
@@ -2158,14 +2160,14 @@ namespace System.Reflection.Emit {
m_typeInterfaces.Add(interfaceType);
}
-public TypeToken TypeToken
+ public TypeToken TypeToken
{
- get
+ get
{
if (IsGenericParameter)
ThrowIfCreated();
- return m_tdType;
+ return m_tdType;
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
index da5a56ba28..6d46362f91 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
@@ -4,18 +4,19 @@
//
+using System;
+using System.Reflection;
+using System.Collections;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
internal sealed class TypeBuilderInstantiation : TypeInfo
{
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ {
+ if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
@@ -34,9 +35,9 @@ namespace System.Reflection.Emit
foreach (Type t in typeArguments)
{
if (t == null)
- throw new ArgumentNullException(nameof(typeArguments));
+ throw new ArgumentNullException(nameof(typeArguments));
}
-
+
return new TypeBuilderInstantiation(type, typeArguments);
}
@@ -77,26 +78,26 @@ namespace System.Reflection.Emit
#endregion
#region Type Overrides
- public override Type MakePointerType()
- {
- return SymbolType.FormCompoundType("*", this, 0);
+ public override Type MakePointerType()
+ {
+ return SymbolType.FormCompoundType("*", this, 0);
}
- public override Type MakeByRefType()
+ public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
- public override Type MakeArrayType()
+ public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
- public override Type MakeArrayType(int rank)
+ public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string comma = "";
- for(int i = 1; i < rank; i++)
+ for (int i = 1; i < rank; i++)
comma += ",";
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", comma);
@@ -106,14 +107,14 @@ namespace System.Reflection.Emit
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
- public override String FullName
- {
- get
- {
+ public override String FullName
+ {
+ get
+ {
if (m_strFullQualName == null)
- m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
+ m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName);
return m_strFullQualName;
- }
+ }
}
public override String Namespace { get { return m_type.Namespace; } }
public override String AssemblyQualifiedName { get { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); } }
@@ -125,7 +126,7 @@ namespace System.Reflection.Emit
for (int i = 0; i < instSubstituted.Length; i++)
{
Type t = inst[i];
-
+
if (t is TypeBuilderInstantiation)
{
instSubstituted[i] = (t as TypeBuilderInstantiation).Substitute(substitutes);
@@ -147,7 +148,7 @@ namespace System.Reflection.Emit
{
// B<A,B,C>
// D<T,S> : B<S,List<T>,char>
-
+
// D<string,int> : B<int,List<string>,char>
// D<S,T> : B<T,List<S>,char>
// D<S,string> : B<string,List<S>,char>
@@ -159,7 +160,7 @@ namespace System.Reflection.Emit
return null;
TypeBuilderInstantiation typeBldrBaseAs = typeBldrBase as TypeBuilderInstantiation;
-
+
if (typeBldrBaseAs == null)
return typeBldrBase;
@@ -167,7 +168,7 @@ namespace System.Reflection.Emit
}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
-
+
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
@@ -187,6 +188,9 @@ namespace System.Reflection.Emit
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; }
+
+ public override bool IsSZArray => false;
+
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
@@ -217,7 +221,7 @@ namespace System.Reflection.Emit
}
public override MethodBase DeclaringMethod { get { return null; } }
public override Type GetGenericTypeDefinition() { return m_type; }
- public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
+ public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Arg_NotGenericTypeDefinition); }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[Pure]
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
index 4fa851c529..4f0c1b3dac 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeToken.cs
@@ -12,33 +12,36 @@
**
**
===========================================================*/
-namespace System.Reflection.Emit {
-
- using System;
- using System.Reflection;
- using System.Threading;
+using System;
+using System.Reflection;
+using System.Threading;
+
+namespace System.Reflection.Emit
+{
[Serializable]
- public struct TypeToken {
-
+ public struct TypeToken
+ {
public static readonly TypeToken Empty = new TypeToken();
internal int m_class;
-
-
- internal TypeToken(int str) {
- m_class=str;
+
+
+ internal TypeToken(int str)
+ {
+ m_class = str;
}
-
- public int Token {
+
+ public int Token
+ {
get { return m_class; }
}
-
+
public override int GetHashCode()
{
return m_class;
}
-
+
public override bool Equals(Object obj)
{
if (obj is TypeToken)
@@ -46,22 +49,21 @@ namespace System.Reflection.Emit {
else
return false;
}
-
+
public bool Equals(TypeToken obj)
{
return obj.m_class == m_class;
}
-
+
public static bool operator ==(TypeToken a, TypeToken b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(TypeToken a, TypeToken b)
{
return !(a == b);
}
-
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
index ca0faf31ca..78238c02b7 100644
--- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
@@ -4,16 +4,16 @@
//
+using System;
+using System.Reflection;
+using System.Collections;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Reflection.Emit
{
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
{
#region Private Static Members
@@ -37,21 +37,21 @@ namespace System.Reflection.Emit
m_type = type;
}
#endregion
-
+
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberInfo Overrides
- public override MemberTypes MemberType { get { return m_method.MemberType; } }
+ public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override String Name { get { return m_method.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
- public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
+ public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
- public override Module Module { get { return m_method.Module; } }
+ public override Module Module { get { return m_method.Module; } }
#endregion
#region MethodBase Members
@@ -65,21 +65,21 @@ namespace System.Reflection.Emit
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_method.CallingConvention; } }
- public override Type [] GetGenericArguments() { return m_method.GetGenericArguments(); }
+ public override Type[] GetGenericArguments() { return m_method.GetGenericArguments(); }
public override MethodInfo GetGenericMethodDefinition() { return m_method; }
public override bool IsGenericMethodDefinition { get { return m_method.IsGenericMethodDefinition; } }
public override bool ContainsGenericParameters { get { return m_method.ContainsGenericParameters; } }
public override MethodInfo MakeGenericMethod(params Type[] typeArgs)
{
if (!IsGenericMethodDefinition)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericMethodDefinition"));
+ throw new InvalidOperationException(SR.Arg_NotGenericMethodDefinition);
Contract.EndContractBlock();
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
public override bool IsGenericMethod { get { return m_method.IsGenericMethod; } }
-
+
#endregion
#region Public Abstract\Virtual Members
@@ -113,7 +113,7 @@ namespace System.Reflection.Emit
m_type = type;
}
#endregion
-
+
internal override Type[] GetParameterTypes()
{
return m_ctor.GetParameterTypes();
@@ -129,7 +129,7 @@ namespace System.Reflection.Emit
public override String Name { get { return m_ctor.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
- public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
+ public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
@@ -147,7 +147,7 @@ namespace System.Reflection.Emit
}
}
}
- public override Module Module { get { return m_ctor.Module; } }
+ public override Module Module { get { return m_ctor.Module; } }
#endregion
#region MethodBase Members
@@ -195,10 +195,12 @@ namespace System.Reflection.Emit
// We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
- if (type.m_hashtable.Contains(Field)) {
+ if (type.m_hashtable.Contains(Field))
+ {
m = type.m_hashtable[Field] as FieldInfo;
}
- else {
+ else
+ {
m = new FieldOnTypeBuilderInstantiation(Field, type);
type.m_hashtable[Field] = m;
}
@@ -225,11 +227,11 @@ namespace System.Reflection.Emit
internal FieldInfo FieldInfo { get { return m_field; } }
#region MemberInfo Overrides
- public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
+ public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
public override String Name { get { return m_field.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
- public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
+ public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
@@ -247,7 +249,7 @@ namespace System.Reflection.Emit
}
}
}
- public override Module Module { get { return m_field.Module; } }
+ public override Module Module { get { return m_field.Module; } }
#endregion
#region Public Abstract\Virtual Members
@@ -260,15 +262,15 @@ namespace System.Reflection.Emit
public override Object GetValueDirect(TypedReference obj)
{
throw new NotImplementedException();
- }
- public override RuntimeFieldHandle FieldHandle
+ }
+ public override RuntimeFieldHandle FieldHandle
{
get { throw new NotImplementedException(); }
- }
+ }
public override Type FieldType { get { throw new NotImplementedException(); } }
public override Object GetValue(Object obj) { throw new InvalidOperationException(); }
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); }
- public override FieldAttributes Attributes { get { return m_field.Attributes; } }
+ public override FieldAttributes Attributes { get { return m_field.Attributes; } }
#endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/EventAttributes.cs b/src/mscorlib/src/System/Reflection/EventAttributes.cs
deleted file mode 100644
index 4cc08f62d3..0000000000
--- a/src/mscorlib/src/System/Reflection/EventAttributes.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// EventAttributes are an enum defining the attributes associated with
-//
-// and Event. These are defined in CorHdr.h and are a combination of
-// bits and enums.
-//
-//
-namespace System.Reflection {
-
- using System;
- [Serializable]
- [Flags]
- public enum EventAttributes {
- None = 0x0000,
-
- // This Enum matchs the CorEventAttr defined in CorHdr.h
- SpecialName = 0x0200, // event is special. Name describes how.
-
- // Reserved flags for Runtime use only.
- ReservedMask = 0x0400,
- RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding.
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/EventInfo.cs b/src/mscorlib/src/System/Reflection/EventInfo.cs
deleted file mode 100644
index 9b529c2960..0000000000
--- a/src/mscorlib/src/System/Reflection/EventInfo.cs
+++ /dev/null
@@ -1,401 +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.
-
-//
-
-namespace System.Reflection
-{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.ConstrainedExecution;
- using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
-
- [Serializable]
- public abstract class EventInfo : MemberInfo
- {
- #region Constructor
- protected EventInfo() { }
- #endregion
-
- public static bool operator ==(EventInfo left, EventInfo right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimeEventInfo || right is RuntimeEventInfo)
- {
- return false;
- }
- return left.Equals(right);
- }
-
- public static bool operator !=(EventInfo left, EventInfo right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return MemberTypes.Event; } }
- #endregion
-
- #region Public Abstract\Virtual Members
- public virtual MethodInfo[] GetOtherMethods(bool nonPublic)
- {
- throw new NotImplementedException();
- }
-
- public abstract MethodInfo GetAddMethod(bool nonPublic);
-
- public abstract MethodInfo GetRemoveMethod(bool nonPublic);
-
- public abstract MethodInfo GetRaiseMethod(bool nonPublic);
-
- public abstract EventAttributes Attributes { get; }
- #endregion
-
- #region Public Members
- public virtual MethodInfo AddMethod
- {
- get
- {
- return GetAddMethod(true);
- }
- }
-
- public virtual MethodInfo RemoveMethod
- {
- get
- {
- return GetRemoveMethod(true);
- }
- }
-
- public virtual MethodInfo RaiseMethod
- {
- get
- {
- return GetRaiseMethod(true);
- }
- }
-
- public MethodInfo[] GetOtherMethods() { return GetOtherMethods(false); }
-
- public MethodInfo GetAddMethod() { return GetAddMethod(false); }
-
- public MethodInfo GetRemoveMethod() { return GetRemoveMethod(false); }
-
- public MethodInfo GetRaiseMethod() { return GetRaiseMethod(false); }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public virtual void AddEventHandler(Object target, Delegate handler)
- {
- MethodInfo addMethod = GetAddMethod();
-
- if (addMethod == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod"));
-
-#if FEATURE_COMINTEROP
- if (addMethod.ReturnType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
-
- // Must be a normal non-WinRT event
- Debug.Assert(addMethod.ReturnType == typeof(void));
-#endif // FEATURE_COMINTEROP
-
- addMethod.Invoke(target, new object[] { handler });
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public virtual void RemoveEventHandler(Object target, Delegate handler)
- {
- MethodInfo removeMethod = GetRemoveMethod();
-
- if (removeMethod == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicRemoveMethod"));
-
-#if FEATURE_COMINTEROP
- ParameterInfo[] parameters = removeMethod.GetParametersNoCopy();
- Debug.Assert(parameters != null && parameters.Length == 1);
-
- if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent"));
-
- // Must be a normal non-WinRT event
- Debug.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate));
-#endif // FEATURE_COMINTEROP
-
- removeMethod.Invoke(target, new object[] { handler });
- }
-
- public virtual Type EventHandlerType
- {
- get
- {
- MethodInfo m = GetAddMethod(true);
-
- ParameterInfo[] p = m.GetParametersNoCopy();
-
- Type del = typeof(Delegate);
-
- for (int i = 0; i < p.Length; i++)
- {
- Type c = p[i].ParameterType;
-
- if (c.IsSubclassOf(del))
- return c;
- }
- return null;
- }
- }
- public bool IsSpecialName
- {
- get
- {
- return(Attributes & EventAttributes.SpecialName) != 0;
- }
- }
-
- public virtual bool IsMulticast
- {
- get
- {
- Type cl = EventHandlerType;
- Type mc = typeof(MulticastDelegate);
- return mc.IsAssignableFrom(cl);
- }
- }
- #endregion
- }
-
- [Serializable]
- internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable
- {
- #region Private Data Members
- private int m_token;
- private EventAttributes m_flags;
- private string m_name;
- private void* m_utf8name;
- private RuntimeTypeCache m_reflectedTypeCache;
- private RuntimeMethodInfo m_addMethod;
- private RuntimeMethodInfo m_removeMethod;
- private RuntimeMethodInfo m_raiseMethod;
- private MethodInfo[] m_otherMethod;
- private RuntimeType m_declaringType;
- private BindingFlags m_bindingFlags;
- #endregion
-
- #region Constructor
- internal RuntimeEventInfo()
- {
- // Used for dummy head node during population
- }
- internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
- {
- Contract.Requires(declaredType != null);
- Contract.Requires(reflectedTypeCache != null);
- Debug.Assert(!reflectedTypeCache.IsGlobal);
-
- MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
-
- m_token = tkEvent;
- m_reflectedTypeCache = reflectedTypeCache;
- m_declaringType = declaredType;
-
-
- RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType();
-
- scope.GetEventProps(tkEvent, out m_utf8name, out m_flags);
-
- RuntimeMethodInfo dummy;
- Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType,
- out m_addMethod, out m_removeMethod, out m_raiseMethod,
- out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags);
- }
- #endregion
-
- #region Internal Members
- internal override bool CacheEquals(object o)
- {
- RuntimeEventInfo m = o as RuntimeEventInfo;
-
- if ((object)m == null)
- return false;
-
- return m.m_token == m_token &&
- RuntimeTypeHandle.GetModule(m_declaringType).Equals(
- RuntimeTypeHandle.GetModule(m.m_declaringType));
- }
-
- internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
- #endregion
-
- #region Object Overrides
- public override String ToString()
- {
- if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod"));
-
- return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name;
- }
- #endregion
-
- #region ICustomAttributeProvider
- public override Object[] GetCustomAttributes(bool inherit)
- {
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
- }
-
- public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
-
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
-
- return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
- }
-
- public override bool IsDefined(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
-
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
-
- return CustomAttribute.IsDefined(this, attributeRuntimeType);
- }
-
- public override IList<CustomAttributeData> GetCustomAttributesData()
- {
- return CustomAttributeData.GetCustomAttributesInternal(this);
- }
- #endregion
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return MemberTypes.Event; } }
- public override String Name
- {
- get
- {
- if (m_name == null)
- m_name = new Utf8String(m_utf8name).ToString();
-
- return m_name;
- }
- }
- public override Type DeclaringType { get { return m_declaringType; } }
- public override Type ReflectedType
- {
- get
- {
- return ReflectedTypeInternal;
- }
- }
-
- private RuntimeType ReflectedTypeInternal
- {
- get
- {
- return m_reflectedTypeCache.GetRuntimeType();
- }
- }
-
- public override int MetadataToken { get { return m_token; } }
- public override Module Module { get { return GetRuntimeModule(); } }
- internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
- #endregion
-
- #region ISerializable
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- MemberInfoSerializationHolder.GetSerializationInfo(
- info,
- Name,
- ReflectedTypeInternal,
- null,
- MemberTypes.Event);
- }
- #endregion
-
- #region EventInfo Overrides
- public override MethodInfo[] GetOtherMethods(bool nonPublic)
- {
- List<MethodInfo> ret = new List<MethodInfo>();
-
- if ((object)m_otherMethod == null)
- return new MethodInfo[0];
-
- for(int i = 0; i < m_otherMethod.Length; i ++)
- {
- if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic))
- ret.Add(m_otherMethod[i]);
- }
-
- return ret.ToArray();
- }
-
- public override MethodInfo GetAddMethod(bool nonPublic)
- {
- if (!Associates.IncludeAccessor(m_addMethod, nonPublic))
- return null;
-
- return m_addMethod;
- }
-
- public override MethodInfo GetRemoveMethod(bool nonPublic)
- {
- if (!Associates.IncludeAccessor(m_removeMethod, nonPublic))
- return null;
-
- return m_removeMethod;
- }
-
- public override MethodInfo GetRaiseMethod(bool nonPublic)
- {
- if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic))
- return null;
-
- return m_raiseMethod;
- }
-
- public override EventAttributes Attributes
- {
- get
- {
- return m_flags;
- }
- }
- #endregion
- }
-
-}
diff --git a/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs b/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs
new file mode 100644
index 0000000000..9bb45aebb2
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.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;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection
+{
+ public class ExceptionHandlingClause
+ {
+ #region costructor
+ // This class can only be created from inside the EE.
+ protected ExceptionHandlingClause() { }
+ #endregion
+
+ #region Private Data Members
+ private MethodBody m_methodBody;
+ [ContractPublicPropertyName("Flags")]
+ private ExceptionHandlingClauseOptions m_flags;
+ private int m_tryOffset;
+ private int m_tryLength;
+ private int m_handlerOffset;
+ private int m_handlerLength;
+ private int m_catchMetadataToken;
+ private int m_filterOffset;
+ #endregion
+
+ #region Public Members
+ public virtual ExceptionHandlingClauseOptions Flags { get { return m_flags; } }
+ public virtual int TryOffset { get { return m_tryOffset; } }
+ public virtual int TryLength { get { return m_tryLength; } }
+ public virtual int HandlerOffset { get { return m_handlerOffset; } }
+ public virtual int HandlerLength { get { return m_handlerLength; } }
+
+ public virtual int FilterOffset
+ {
+ get
+ {
+ if (m_flags != ExceptionHandlingClauseOptions.Filter)
+ throw new InvalidOperationException(SR.Arg_EHClauseNotFilter);
+
+ return m_filterOffset;
+ }
+ }
+
+ public virtual Type CatchType
+ {
+ get
+ {
+ if (m_flags != ExceptionHandlingClauseOptions.Clause)
+ throw new InvalidOperationException(SR.Arg_EHClauseNotClause);
+
+ Type type = null;
+
+ if (!MetadataToken.IsNullToken(m_catchMetadataToken))
+ {
+ Type declaringType = m_methodBody.m_methodBase.DeclaringType;
+ Module module = (declaringType == null) ? m_methodBody.m_methodBase.Module : declaringType.Module;
+ type = module.ResolveType(m_catchMetadataToken, (declaringType == null) ? null : declaringType.GetGenericArguments(),
+ m_methodBody.m_methodBase is MethodInfo ? m_methodBody.m_methodBase.GetGenericArguments() : null);
+ }
+
+ return type;
+ }
+ }
+ #endregion
+
+ #region Object Overrides
+ public override string ToString()
+ {
+ if (Flags == ExceptionHandlingClauseOptions.Clause)
+ {
+ return String.Format(CultureInfo.CurrentUICulture,
+ "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, CatchType={5}",
+ Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, CatchType);
+ }
+
+ if (Flags == ExceptionHandlingClauseOptions.Filter)
+ {
+ return String.Format(CultureInfo.CurrentUICulture,
+ "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, FilterOffset={5}",
+ Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, FilterOffset);
+ }
+
+ return String.Format(CultureInfo.CurrentUICulture,
+ "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}",
+ Flags, TryOffset, TryLength, HandlerOffset, HandlerLength);
+ }
+ #endregion
+ }
+}
+
diff --git a/src/mscorlib/src/System/Reflection/FieldAttributes.cs b/src/mscorlib/src/System/Reflection/FieldAttributes.cs
deleted file mode 100644
index e49a0a45b1..0000000000
--- a/src/mscorlib/src/System/Reflection/FieldAttributes.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.
-
-namespace System.Reflection
-{
- using System;
- // This Enum matchs the CorFieldAttr defined in CorHdr.h
- [Serializable]
- [Flags()]
- public enum FieldAttributes
- {
- // member access mask - Use this mask to retrieve accessibility information.
- FieldAccessMask = 0x0007,
- PrivateScope = 0x0000, // Member not referenceable.
- Private = 0x0001, // Accessible only by the parent type.
- FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly.
- Assembly = 0x0003, // Accessibly by anyone in the Assembly.
- Family = 0x0004, // Accessible only by type and sub-types.
- FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly.
- Public = 0x0006, // Accessibly by anyone who has visibility to this scope.
- // end member access mask
-
- // field contract attributes.
- Static = 0x0010, // Defined on type, else per instance.
- InitOnly = 0x0020, // Field may only be initialized, not written to after init.
- Literal = 0x0040, // Value is compile time constant.
- NotSerialized = 0x0080, // Field does not have to be serialized when type is remoted.
-
- SpecialName = 0x0200, // field is special. Name describes how.
-
- // interop attributes
- PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke.
-
- // Reserved flags for runtime use only.
- ReservedMask = 0x9500,
- RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding.
- HasFieldMarshal = 0x1000, // Field has marshalling information.
- HasDefault = 0x8000, // Field has default.
- HasFieldRVA = 0x0100, // Field has RVA.
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs b/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs
new file mode 100644
index 0000000000..bcda3418fa
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/FieldInfo.CoreCLR.cs
@@ -0,0 +1,35 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Globalization;
+
+namespace System.Reflection
+{
+ public abstract partial class FieldInfo : MemberInfo
+ {
+ public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
+ {
+ if (handle.IsNullHandle())
+ throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
+
+ FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
+
+ Type declaringType = f.DeclaringType;
+ if (declaringType != null && declaringType.IsGenericType)
+ throw new ArgumentException(String.Format(
+ CultureInfo.CurrentCulture, SR.Argument_FieldDeclaringTypeGeneric,
+ f.Name, declaringType.GetGenericTypeDefinition()));
+
+ return f;
+ }
+
+ public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
+ {
+ if (handle.IsNullHandle())
+ throw new ArgumentException(SR.Argument_InvalidHandle);
+
+ return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo());
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/FieldInfo.cs b/src/mscorlib/src/System/Reflection/FieldInfo.cs
deleted file mode 100644
index 7b6517c2bb..0000000000
--- a/src/mscorlib/src/System/Reflection/FieldInfo.cs
+++ /dev/null
@@ -1,862 +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.
-
-//
-
-namespace System.Reflection
-{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Threading;
- using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
-
- [Serializable]
- public abstract class FieldInfo : MemberInfo
- {
- #region Static Members
- public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle)
- {
- if (handle.IsNullHandle())
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"), nameof(handle));
-
- FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo());
-
- Type declaringType = f.DeclaringType;
- if (declaringType != null && declaringType.IsGenericType)
- throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"),
- f.Name, declaringType.GetGenericTypeDefinition()));
-
- return f;
- }
-
- public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType)
- {
- if (handle.IsNullHandle())
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
-
- return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo());
- }
- #endregion
-
- #region Constructor
- protected FieldInfo() { }
- #endregion
-
- public static bool operator ==(FieldInfo left, FieldInfo right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimeFieldInfo || right is RuntimeFieldInfo)
- {
- return false;
- }
- return left.Equals(right);
- }
-
- public static bool operator !=(FieldInfo left, FieldInfo right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
- #endregion
-
- #region Public Abstract\Virtual Members
-
- public virtual Type[] GetRequiredCustomModifiers()
- {
- throw new NotImplementedException();
- }
-
- public virtual Type[] GetOptionalCustomModifiers()
- {
- throw new NotImplementedException();
- }
-
- [CLSCompliant(false)]
- public virtual void SetValueDirect(TypedReference obj, Object value)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
- }
-
- [CLSCompliant(false)]
- public virtual Object GetValueDirect(TypedReference obj)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS"));
- }
-
- public abstract RuntimeFieldHandle FieldHandle { get; }
-
- public abstract Type FieldType { get; }
-
- public abstract Object GetValue(Object obj);
-
- public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); }
-
- public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture);
-
- public abstract FieldAttributes Attributes { get; }
- #endregion
-
- #region Public Members
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public void SetValue(Object obj, Object value)
- {
- // Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
- // But to maintain backward compatibility we can't switch to calling an
- // internal overload that takes a stack mark.
- // Fortunately the stack walker skips all the reflection invocation frames including this one.
- // So this method will never be returned by the stack walker as the caller.
- // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
- SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null);
- }
-
- public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } }
-
- public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } }
-
- public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } }
-
- public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } }
-
- public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } }
-
- public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } }
-
- public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } }
-
- public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } }
-
- public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } }
-
- public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } }
-
- public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } }
-
- public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } }
-
- public virtual bool IsSecurityCritical
- {
- get { return FieldHandle.IsSecurityCritical(); }
- }
-
- public virtual bool IsSecuritySafeCritical
- {
- get { return FieldHandle.IsSecuritySafeCritical(); }
- }
-
- public virtual bool IsSecurityTransparent
- {
- get { return FieldHandle.IsSecurityTransparent(); }
- }
-
- #endregion
- }
-
- [Serializable]
- internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable
- {
- #region Private Data Members
- private BindingFlags m_bindingFlags;
- protected RuntimeTypeCache m_reflectedTypeCache;
- protected RuntimeType m_declaringType;
- #endregion
-
- #region Constructor
- protected RuntimeFieldInfo()
- {
- // Used for dummy head node during population
- }
- protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags)
- {
- m_bindingFlags = bindingFlags;
- m_declaringType = declaringType;
- m_reflectedTypeCache = reflectedTypeCache;
- }
- #endregion
-
- #region NonPublic Members
- internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
- private RuntimeType ReflectedTypeInternal
- {
- get
- {
- return m_reflectedTypeCache.GetRuntimeType();
- }
- }
-
- internal RuntimeType GetDeclaringTypeInternal()
- {
- return m_declaringType;
- }
-
- internal RuntimeType GetRuntimeType() { return m_declaringType; }
- internal abstract RuntimeModule GetRuntimeModule();
- #endregion
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return MemberTypes.Field; } }
- public override Type ReflectedType
- {
- get
- {
- return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
- }
- }
-
- public override Type DeclaringType
- {
- get
- {
- return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
- }
- }
-
- public override Module Module { get { return GetRuntimeModule(); } }
- #endregion
-
- #region Object Overrides
- public unsafe override String ToString()
- {
- return FieldType.FormatTypeName() + " " + Name;
- }
- #endregion
-
- #region ICustomAttributeProvider
- public override Object[] GetCustomAttributes(bool inherit)
- {
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
- }
-
- public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
-
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
-
- return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
- }
-
- public override bool IsDefined(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
-
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
-
- return CustomAttribute.IsDefined(this, attributeRuntimeType);
- }
-
- public override IList<CustomAttributeData> GetCustomAttributesData()
- {
- return CustomAttributeData.GetCustomAttributesInternal(this);
- }
- #endregion
-
- #region FieldInfo Overrides
- // All implemented on derived classes
- #endregion
-
- #region ISerializable Implementation
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
- MemberInfoSerializationHolder.GetSerializationInfo(
- info,
- Name,
- ReflectedTypeInternal,
- ToString(),
- MemberTypes.Field);
- }
- #endregion
- }
-
- [Serializable]
- 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;
- private FieldAttributes m_fieldAttributes;
- // lazy caching
- private string m_name;
- private RuntimeType m_fieldType;
- private INVOCATION_FLAGS m_invocationFlags;
-
-#if FEATURE_APPX
- private bool IsNonW8PFrameworkAPI()
- {
- if (GetRuntimeType().IsNonW8PFrameworkAPI())
- return true;
-
- // Allow "value__"
- if (m_declaringType.IsEnum)
- return false;
-
- RuntimeAssembly rtAssembly = GetRuntimeAssembly();
- if (rtAssembly.IsFrameworkAssembly())
- {
- int ctorToken = rtAssembly.InvocableAttributeCtorToken;
- if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
- !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
- return true;
- }
-
- return false;
- }
-#endif
-
- internal INVOCATION_FLAGS InvocationFlags
- {
- get
- {
- if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
- {
- Type declaringType = DeclaringType;
- bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
-
- INVOCATION_FLAGS invocationFlags = 0;
-
- // first take care of all the NO_INVOKE cases
- if (
- (declaringType != null && declaringType.ContainsGenericParameters) ||
- (declaringType == null && Module.Assembly.ReflectionOnly) ||
- (fIsReflectionOnlyType)
- )
- {
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
- }
-
- // If the invocationFlags are still 0, then
- // this should be an usable field, determine the other flags
- if (invocationFlags == 0)
- {
- if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
-
- 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)
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
- }
-
-#if FEATURE_APPX
- if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
-#endif // FEATURE_APPX
-
- // must be last to avoid threading problems
- m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
- }
-
- return m_invocationFlags;
- }
- }
- #endregion
-
- private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
-
- #region Constructor
- internal RtFieldInfo(
- RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
- : base(reflectedTypeCache, declaringType, bindingFlags)
- {
- m_fieldHandle = handle.Value;
- m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
- }
- #endregion
-
- #region Private Members
- RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
- {
- get
- {
- return new RuntimeFieldHandleInternal(m_fieldHandle);
- }
- }
-
- #endregion
-
- #region Internal Members
- internal void CheckConsistency(Object target)
- {
- // only test instance fields
- if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
- {
- if (!m_declaringType.IsInstanceOfType(target))
- {
- if (target == null)
- {
- throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg"));
- }
- else
- {
- throw new ArgumentException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"),
- Name, m_declaringType, target.GetType()));
- }
- }
- }
- }
-
- internal override bool CacheEquals(object o)
- {
- RtFieldInfo m = o as RtFieldInfo;
-
- if ((object)m == null)
- return false;
-
- return m.m_fieldHandle == m_fieldHandle;
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
- {
- INVOCATION_FLAGS invocationFlags = InvocationFlags;
- RuntimeType declaringType = DeclaringType as RuntimeType;
-
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
- {
- if (declaringType != null && declaringType.ContainsGenericParameters)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
-
- if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
-
- throw new FieldAccessException();
- }
-
- CheckConsistency(obj);
-
- RuntimeType fieldType = (RuntimeType)FieldType;
- value = fieldType.CheckValue(value, binder, culture, invokeAttr);
-
- #region Security Check
-#if FEATURE_APPX
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
- }
-#endif
-
- 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)
- {
- RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
- }
- else
- {
- domainInitialized = declaringType.DomainInitialized;
- RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
- declaringType.DomainInitialized = domainInitialized;
- }
- }
-
- // UnsafeSetValue doesn't perform any consistency or visibility check.
- // It is the caller's responsibility to ensure the operation is safe.
- // When the caller needs to perform visibility checks they should call
- // InternalSetValue() instead. When the caller needs to perform
- // consistency checks they should call CheckConsistency() before
- // calling this method.
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
- {
- RuntimeType declaringType = DeclaringType as RuntimeType;
- RuntimeType fieldType = (RuntimeType)FieldType;
- value = fieldType.CheckValue(value, binder, culture, invokeAttr);
-
- bool domainInitialized = false;
- if (declaringType == null)
- {
- RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
- }
- else
- {
- domainInitialized = declaringType.DomainInitialized;
- RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
- declaringType.DomainInitialized = domainInitialized;
- }
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
- {
- INVOCATION_FLAGS invocationFlags = InvocationFlags;
- RuntimeType declaringType = DeclaringType as RuntimeType;
-
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
- {
- if (declaringType != null && DeclaringType.ContainsGenericParameters)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField"));
-
- if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField"));
-
- throw new FieldAccessException();
- }
-
- CheckConsistency(obj);
-
-#if FEATURE_APPX
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
- }
-#endif
-
- 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);
- }
-
- // UnsafeGetValue doesn't perform any consistency or visibility check.
- // It is the caller's responsibility to ensure the operation is safe.
- // When the caller needs to perform visibility checks they should call
- // InternalGetValue() instead. When the caller needs to perform
- // consistency checks they should call CheckConsistency() before
- // calling this method.
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- internal Object UnsafeGetValue(Object obj)
- {
- RuntimeType declaringType = DeclaringType as RuntimeType;
-
- RuntimeType fieldType = (RuntimeType)FieldType;
-
- bool domainInitialized = false;
- if (declaringType == null)
- {
- return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
- }
- else
- {
- domainInitialized = declaringType.DomainInitialized;
- object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
- declaringType.DomainInitialized = domainInitialized;
- return retVal;
- }
- }
-
- #endregion
-
- #region MemberInfo Overrides
- public override String Name
- {
- get
- {
- if (m_name == null)
- m_name = RuntimeFieldHandle.GetName(this);
-
- return m_name;
- }
- }
-
- internal String FullName
- {
- get
- {
- return String.Format("{0}.{1}", DeclaringType.FullName, Name);
- }
- }
-
- public override int MetadataToken
- {
- get { return RuntimeFieldHandle.GetToken(this); }
- }
-
- internal override RuntimeModule GetRuntimeModule()
- {
- return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
- }
-
- #endregion
-
- #region FieldInfo Overrides
- public override Object GetValue(Object obj)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalGetValue(obj, ref stackMark);
- }
-
- public override object GetRawConstantValue() { throw new InvalidOperationException(); }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public override Object GetValueDirect(TypedReference obj)
- {
- if (obj.IsNull)
- throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
- Contract.EndContractBlock();
-
- unsafe
- {
- // Passing TypedReference by reference is easier to make correct in native code
- return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
- }
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public override void SetValueDirect(TypedReference obj, Object value)
- {
- if (obj.IsNull)
- throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null"));
- Contract.EndContractBlock();
-
- unsafe
- {
- // Passing TypedReference by reference is easier to make correct in native code
- RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
- }
- }
-
- public override RuntimeFieldHandle FieldHandle
- {
- get
- {
- Type declaringType = DeclaringType;
- if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
- return new RuntimeFieldHandle(this);
- }
- }
-
- internal IntPtr GetFieldHandle()
- {
- return m_fieldHandle;
- }
-
- public override FieldAttributes Attributes
- {
- get
- {
- return m_fieldAttributes;
- }
- }
-
- public override Type FieldType
- {
- get
- {
- if (m_fieldType == null)
- m_fieldType = new Signature(this, m_declaringType).FieldType;
-
- return m_fieldType;
- }
- }
-
- public override Type[] GetRequiredCustomModifiers()
- {
- return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
- }
-
- public override Type[] GetOptionalCustomModifiers()
- {
- return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
- }
-
- #endregion
- }
-
- [Serializable]
- internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable
- {
- #region Private Data Members
- private int m_tkField;
- private string m_name;
- private RuntimeType m_fieldType;
- private FieldAttributes m_fieldAttributes;
- #endregion
-
- #region Constructor
- internal MdFieldInfo(
- int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
- : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags)
- {
- m_tkField = tkField;
- m_name = null;
- m_fieldAttributes = fieldAttributes;
- }
- #endregion
-
- #region Internal Members
- internal override bool CacheEquals(object o)
- {
- MdFieldInfo m = o as MdFieldInfo;
-
- if ((object)m == null)
- return false;
-
- return m.m_tkField == m_tkField &&
- m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(
- m.m_declaringType.GetTypeHandleInternal().GetModuleHandle());
- }
- #endregion
-
- #region MemberInfo Overrides
- public override String Name
- {
- get
- {
- if (m_name == null)
- m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
-
- return m_name;
- }
- }
-
- public override int MetadataToken { get { return m_tkField; } }
- internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
- #endregion
-
- #region FieldInfo Overrides
- public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } }
- public override FieldAttributes Attributes { get { return m_fieldAttributes; } }
-
- public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } }
- public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } }
- public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public override Object GetValueDirect(TypedReference obj)
- {
- return GetValue(null);
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public override void SetValueDirect(TypedReference obj,Object value)
- {
- throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public unsafe override Object GetValue(Object obj)
- {
- return GetValue(false);
- }
-
- public unsafe override Object GetRawConstantValue() { return GetValue(true); }
-
- private unsafe Object GetValue(bool raw)
- {
- // Cannot cache these because they could be user defined non-agile enumerations
-
- Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
-
- if (value == DBNull.Value)
- throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
-
- return value;
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
- {
- throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly"));
- }
-
- public override Type FieldType
- {
- get
- {
- if (m_fieldType == null)
- {
- ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField);
-
- m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
- (int)fieldMarshal.Length, m_declaringType).FieldType;
- }
-
- return m_fieldType;
- }
- }
-
- public override Type[] GetRequiredCustomModifiers()
- {
- return EmptyArray<Type>.Value;
- }
-
- public override Type[] GetOptionalCustomModifiers()
- {
- return EmptyArray<Type>.Value;
- }
-
- #endregion
- }
-
-}
diff --git a/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs b/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs
deleted file mode 100644
index d954b2e0f2..0000000000
--- a/src/mscorlib/src/System/Reflection/GenericParameterAttributes.cs
+++ /dev/null
@@ -1,22 +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.
-
-//
-
-namespace System.Reflection
-{
- [Flags()]
- public enum GenericParameterAttributes
- {
- None = 0x0000,
- VarianceMask = 0x0003,
- Covariant = 0x0001,
- Contravariant = 0x0002,
- SpecialConstraintMask = 0x001C,
- ReferenceTypeConstraint = 0x0004,
- NotNullableValueTypeConstraint = 0x0008,
- DefaultConstructorConstraint = 0x0010,
- }
-}
-
diff --git a/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs b/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.cs
deleted file mode 100644
index faea91a81e..0000000000
--- a/src/mscorlib/src/System/Reflection/ICustomAttributeProvider.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// ICustomAttributeProvider is an interface that is implemented by reflection
-//
-// objects which support custom attributes.
-//
-//
-namespace System.Reflection {
-
- using System;
-
- // Interface does not need to be marked with the serializable attribute
- public interface ICustomAttributeProvider
- {
-
- // Return an array of custom attributes identified by Type
- Object[] GetCustomAttributes(Type attributeType, bool inherit);
-
-
- // Return an array of all of the custom attributes (named attributes are not included)
- Object[] GetCustomAttributes(bool inherit);
-
-
- // Returns true if one or more instance of attributeType is defined on this member.
- bool IsDefined (Type attributeType, bool inherit);
-
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs b/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs
new file mode 100644
index 0000000000..6ffc3e968b
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs
@@ -0,0 +1,38 @@
+// 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
+{
+ //
+ // Invocation cached flags. Those are used in unmanaged code as well
+ // so be careful if you change them
+ //
+ [Flags]
+ internal enum INVOCATION_FLAGS : uint
+ {
+ INVOCATION_FLAGS_UNKNOWN = 0x00000000,
+ 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,
+ // 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,
+ // because field and method are different we can reuse the same bits
+ // method
+ INVOCATION_FLAGS_IS_CTOR = 0x00000010,
+ INVOCATION_FLAGS_RISKY_METHOD = 0x00000020,
+ /* unused 0x00000040 */
+ INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080,
+ INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100,
+ // field
+ INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010,
+ INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020,
+
+ // temporary flag used for flagging invocation of method vs ctor
+ // this flag never appears on the instance m_invocationFlag and is simply
+ // passed down from within ConstructorInfo.Invoke()
+ INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000,
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/IReflect.cs b/src/mscorlib/src/System/Reflection/IReflect.cs
deleted file mode 100644
index 1c3c57613b..0000000000
--- a/src/mscorlib/src/System/Reflection/IReflect.cs
+++ /dev/null
@@ -1,116 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// IReflect is an interface that defines a subset of the Type reflection methods.
-//
-// This interface is used to access and invoke members of a Type. It can be either
-// type based (like Type) or instance based (like Expando). This interface is used in
-// combination with IExpando to model the IDispatchEx expando capibilities in
-// the interop layer.
-//
-//
-namespace System.Reflection {
- using System;
- using System.Runtime.InteropServices;
- using CultureInfo = System.Globalization.CultureInfo;
-
- // Interface does not need to be marked with the serializable attribute
- [Guid("AFBF15E5-C37C-11d2-B88E-00A0C9B471B8")]
- public interface IReflect
- {
- // Return the requested method if it is implemented by the Reflection object. The
- // match is based upon the name and DescriptorInfo which describes the signature
- // of the method.
- MethodInfo GetMethod(String name,BindingFlags bindingAttr,Binder binder,
- Type[] types,ParameterModifier[] modifiers);
-
- // Return the requested method if it is implemented by the Reflection object. The
- // match is based upon the name of the method. If the object implementes multiple methods
- // with the same name an AmbiguousMatchException is thrown.
- MethodInfo GetMethod(String name,BindingFlags bindingAttr);
-
- MethodInfo[] GetMethods(BindingFlags bindingAttr);
-
- // Return the requestion field if it is implemented by the Reflection object. The
- // match is based upon a name. There cannot be more than a single field with
- // a name.
- FieldInfo GetField(
- String name,
- BindingFlags bindingAttr);
-
- FieldInfo[] GetFields(
- BindingFlags bindingAttr);
-
- // Return the property based upon name. If more than one property has the given
- // name an AmbiguousMatchException will be thrown. Returns null if no property
- // is found.
- PropertyInfo GetProperty(
- String name,
- BindingFlags bindingAttr);
-
- // Return the property based upon the name and Descriptor info describing the property
- // indexing. Return null if no property is found.
- PropertyInfo GetProperty(
- String name,
- BindingFlags bindingAttr,
- Binder binder,
- Type returnType,
- Type[] types,
- ParameterModifier[] modifiers);
-
- // Returns an array of PropertyInfos for all the properties defined on
- // the Reflection object.
- PropertyInfo[] GetProperties(
- BindingFlags bindingAttr);
-
- // Return an array of members which match the passed in name.
- MemberInfo[] GetMember(
- String name,
- BindingFlags bindingAttr);
-
- // Return an array of all of the members defined for this object.
- MemberInfo[] GetMembers(
- BindingFlags bindingAttr);
-
- // Description of the Binding Process.
- // We must invoke a method that is accessable 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
- // 2. The type of each argument can be converted by the binder to the
- // type of the type of the parameter.
- //
- // The binder will find all of the matching methods. These method are found based
- // upon the type of binding requested (MethodInvoke, Get/Set Properties). The set
- // 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
- // at that point. The search may be control which set of methods are searched based
- // upon the accessibility attribute associated with the method.
- //
- // The BindToMethod method is responsible for selecting the method to be invoked.
- // For the default binder, the most specific method will be selected.
- //
- // This will invoke a specific member...
- Object InvokeMember(
- String name,
- BindingFlags invokeAttr,
- Binder binder,
- Object target,
- Object[] args,
- ParameterModifier[] modifiers,
- CultureInfo culture,
- String[] namedParameters);
-
- // Return the underlying Type that represents the IReflect Object. For expando object,
- // this is the (Object) IReflectInstance.GetType(). For Type object it is this.
- Type UnderlyingSystemType {
- get;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/IReflectableType.cs b/src/mscorlib/src/System/Reflection/IReflectableType.cs
deleted file mode 100644
index 7d4936868b..0000000000
--- a/src/mscorlib/src/System/Reflection/IReflectableType.cs
+++ /dev/null
@@ -1,20 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// IReflectableType is an interface that is implemented by a Type produced
-// by a ReflectionContext
-//
-
-//
-namespace System.Reflection {
-
- using System;
-
- public interface IReflectableType {
- TypeInfo GetTypeInfo();
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/InterfaceMapping.cs b/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
deleted file mode 100644
index bf994f7b47..0000000000
--- a/src/mscorlib/src/System/Reflection/InterfaceMapping.cs
+++ /dev/null
@@ -1,22 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-//
-// Interface Map. This struct returns the mapping of an interface into the actual methods on a class
-// that implement that interface.
-//
-//
-namespace System.Reflection {
- using System;
-
- public struct InterfaceMapping {
- public Type TargetType; // The type implementing the interface
- public Type InterfaceType; // The type representing the interface
- public MethodInfo[] TargetMethods; // The methods implementing the interface
- public MethodInfo[] InterfaceMethods; // The methods defined on the interface
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs b/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
deleted file mode 100644
index 49819a942f..0000000000
--- a/src/mscorlib/src/System/Reflection/IntrospectionExtensions.cs
+++ /dev/null
@@ -1,28 +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: Get the underlying TypeInfo from a Type
-**
-**
-=============================================================================*/
-namespace System.Reflection
-{
- public static class IntrospectionExtensions
- {
- public static TypeInfo GetTypeInfo(this Type type)
- {
- if (type == null)
- throw new ArgumentNullException(nameof(type));
-
- var rcType=(IReflectableType)type;
- return rcType.GetTypeInfo();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs b/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
deleted file mode 100644
index 8b8c06d9cf..0000000000
--- a/src/mscorlib/src/System/Reflection/InvalidFilterCriteriaException.cs
+++ /dev/null
@@ -1,39 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// InvalidFilterCriteriaException is thrown in FindMembers when the
-//
-// filter criteria is not valid for the type of filter being used.
-//
-//
-//
-//
-namespace System.Reflection {
-
- using System;
- using System.Runtime.Serialization;
- using ApplicationException = System.ApplicationException;
- [Serializable]
- public class InvalidFilterCriteriaException : ApplicationException {
- public InvalidFilterCriteriaException()
- : base(Environment.GetResourceString("Arg_InvalidFilterCriteriaException")) {
- SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
- }
-
- public InvalidFilterCriteriaException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
- }
-
- public InvalidFilterCriteriaException(String message, Exception inner) : base(message, inner) {
- SetErrorCode(__HResults.COR_E_INVALIDFILTERCRITERIA);
- }
-
- protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/LoaderAllocator.cs b/src/mscorlib/src/System/Reflection/LoaderAllocator.cs
index 7c6c6bd0e8..035f158251 100644
--- a/src/mscorlib/src/System/Reflection/LoaderAllocator.cs
+++ b/src/mscorlib/src/System/Reflection/LoaderAllocator.cs
@@ -49,7 +49,6 @@ namespace System.Reflection
if (!Environment.HasShutdownStarted &&
!AppDomain.CurrentDomain.IsFinalizingForUnload())
{
-
// Destroy returns false if the managed LoaderAllocator is still alive.
if (!Destroy(m_nativeLoaderAllocator))
{
@@ -63,9 +62,9 @@ namespace System.Reflection
internal sealed class LoaderAllocator
{
- LoaderAllocator()
+ private LoaderAllocator()
{
- m_slots = new object [5];
+ m_slots = new object[5];
// m_slotsUsed = 0;
m_scout = new LoaderAllocatorScout();
@@ -73,10 +72,10 @@ namespace System.Reflection
#pragma warning disable 169
#pragma warning disable 414
- LoaderAllocatorScout m_scout;
- object [] m_slots;
+ private LoaderAllocatorScout m_scout;
+ private object[] m_slots;
internal CerHashtable<RuntimeMethodInfo, RuntimeMethodInfo> m_methodInstantiations;
- int m_slotsUsed;
+ private int m_slotsUsed;
#pragma warning restore 414
#pragma warning restore 169
}
diff --git a/src/mscorlib/src/System/Reflection/LocalVariableInfo.cs b/src/mscorlib/src/System/Reflection/LocalVariableInfo.cs
new file mode 100644
index 0000000000..241a3c4de6
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/LocalVariableInfo.cs
@@ -0,0 +1,40 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+
+namespace System.Reflection
+{
+ public class LocalVariableInfo
+ {
+ #region Private Data Members
+ private RuntimeType m_type;
+ private int m_isPinned;
+ private int m_localIndex;
+ #endregion
+
+ #region Constructor
+ protected LocalVariableInfo() { }
+ #endregion
+
+ #region Object Overrides
+ public override string ToString()
+ {
+ string toString = LocalType.ToString() + " (" + LocalIndex + ")";
+
+ if (IsPinned)
+ toString += " (pinned)";
+
+ return toString;
+ }
+ #endregion
+
+ #region Public Members
+ public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } }
+ public virtual bool IsPinned { get { return m_isPinned != 0; } }
+ public virtual int LocalIndex { get { return m_localIndex; } }
+ #endregion
+ }
+}
+
diff --git a/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs b/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
deleted file mode 100644
index 91c7ceb2ea..0000000000
--- a/src/mscorlib/src/System/Reflection/ManifestResourceInfo.cs
+++ /dev/null
@@ -1,65 +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: For info regarding a manifest resource's topology.
-**
-**
-=============================================================================*/
-
-namespace System.Reflection {
- using System;
-
- public class ManifestResourceInfo {
- private Assembly _containingAssembly;
- private String _containingFileName;
- private ResourceLocation _resourceLocation;
-
- public ManifestResourceInfo(Assembly containingAssembly,
- String containingFileName,
- ResourceLocation resourceLocation)
- {
- _containingAssembly = containingAssembly;
- _containingFileName = containingFileName;
- _resourceLocation = resourceLocation;
- }
-
- public virtual Assembly ReferencedAssembly
- {
- get {
- return _containingAssembly;
- }
- }
-
- public virtual String FileName
- {
- get {
- return _containingFileName;
- }
- }
-
- public virtual ResourceLocation ResourceLocation
- {
- get {
- return _resourceLocation;
- }
- }
- }
-
- // The ResourceLocation is a combination of these flags, set or not.
- // Linked means not Embedded.
-[Serializable]
- [Flags]
- public enum ResourceLocation
- {
- Embedded = 0x1,
- ContainedInAnotherAssembly = 0x2,
- ContainedInManifestFile = 0x4
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/MdConstant.cs b/src/mscorlib/src/System/Reflection/MdConstant.cs
index e59244f109..8e5b65724d 100644
--- a/src/mscorlib/src/System/Reflection/MdConstant.cs
+++ b/src/mscorlib/src/System/Reflection/MdConstant.cs
@@ -4,10 +4,10 @@
//
+using System;
+
namespace System.Reflection
{
- using System;
-
internal static class MdConstant
{
public static unsafe Object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw)
@@ -67,13 +67,13 @@ namespace System.Reflection
case CorElementType.U8:
defaultValue = buffer;
break;
-
+
default:
- throw new FormatException(Environment.GetResourceString("Arg_BadLiteralFormat"));
- #endregion
+ throw new FormatException(SR.Arg_BadLiteralFormat);
+ #endregion
}
- return RuntimeType.CreateEnum(fieldType, defaultValue);
+ return RuntimeType.CreateEnum(fieldType, defaultValue);
}
else if (fieldType == typeof(DateTime))
{
@@ -85,7 +85,7 @@ namespace System.Reflection
case CorElementType.Void:
return DBNull.Value;
-
+
case CorElementType.I8:
defaultValue = buffer;
break;
@@ -93,10 +93,10 @@ namespace System.Reflection
case CorElementType.U8:
defaultValue = buffer;
break;
-
+
default:
- throw new FormatException(Environment.GetResourceString("Arg_BadLiteralFormat"));
- #endregion
+ throw new FormatException(SR.Arg_BadLiteralFormat);
+ #endregion
}
return new DateTime(defaultValue);
@@ -136,14 +136,14 @@ namespace System.Reflection
case CorElementType.U8:
return (ulong)buffer;
-
- case CorElementType.Boolean :
+
+ case CorElementType.Boolean:
// The boolean value returned from the metadata engine is stored as a
// BOOL, which actually maps to an int. We need to read it out as an int
// to avoid problems on big-endian machines.
return (*(int*)&buffer != 0);
- case CorElementType.R4 :
+ case CorElementType.R4:
return *(float*)&buffer;
case CorElementType.R8:
@@ -156,13 +156,12 @@ namespace System.Reflection
case CorElementType.Class:
return null;
-
+
default:
- throw new FormatException(Environment.GetResourceString("Arg_BadLiteralFormat"));
- #endregion
+ throw new FormatException(SR.Arg_BadLiteralFormat);
+ #endregion
}
}
- }
+ }
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/MdFieldInfo.cs b/src/mscorlib/src/System/Reflection/MdFieldInfo.cs
new file mode 100644
index 0000000000..41ee4d9297
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/MdFieldInfo.cs
@@ -0,0 +1,141 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.Serialization;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
+
+namespace System.Reflection
+{
+ [Serializable]
+ internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable
+ {
+ #region Private Data Members
+ private int m_tkField;
+ private string m_name;
+ private RuntimeType m_fieldType;
+ private FieldAttributes m_fieldAttributes;
+ #endregion
+
+ #region Constructor
+ internal MdFieldInfo(
+ int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
+ : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags)
+ {
+ m_tkField = tkField;
+ m_name = null;
+ m_fieldAttributes = fieldAttributes;
+ }
+ #endregion
+
+ #region Internal Members
+ internal override bool CacheEquals(object o)
+ {
+ MdFieldInfo m = o as MdFieldInfo;
+
+ if ((object)m == null)
+ return false;
+
+ return m.m_tkField == m_tkField &&
+ m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(
+ m.m_declaringType.GetTypeHandleInternal().GetModuleHandle());
+ }
+ #endregion
+
+ #region MemberInfo Overrides
+ public override String Name
+ {
+ get
+ {
+ if (m_name == null)
+ m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString();
+
+ return m_name;
+ }
+ }
+
+ public override int MetadataToken { get { return m_tkField; } }
+ internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
+ #endregion
+
+ #region FieldInfo Overrides
+ public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } }
+ public override FieldAttributes Attributes { get { return m_fieldAttributes; } }
+
+ public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } }
+ public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } }
+ public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public override Object GetValueDirect(TypedReference obj)
+ {
+ return GetValue(null);
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public override void SetValueDirect(TypedReference obj, Object value)
+ {
+ throw new FieldAccessException(SR.Acc_ReadOnly);
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public unsafe override Object GetValue(Object obj)
+ {
+ return GetValue(false);
+ }
+
+ public unsafe override Object GetRawConstantValue() { return GetValue(true); }
+
+ private unsafe Object GetValue(bool raw)
+ {
+ // Cannot cache these because they could be user defined non-agile enumerations
+
+ Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw);
+
+ if (value == DBNull.Value)
+ throw new NotSupportedException(SR.Arg_EnumLitValueNotFound);
+
+ return value;
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ {
+ throw new FieldAccessException(SR.Acc_ReadOnly);
+ }
+
+ public override Type FieldType
+ {
+ get
+ {
+ if (m_fieldType == null)
+ {
+ ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField);
+
+ m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(),
+ (int)fieldMarshal.Length, m_declaringType).FieldType;
+ }
+
+ return m_fieldType;
+ }
+ }
+
+ public override Type[] GetRequiredCustomModifiers()
+ {
+ return Array.Empty<Type>();
+ }
+
+ public override Type[] GetOptionalCustomModifiers()
+ {
+ return Array.Empty<Type>();
+ }
+
+ #endregion
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/MdImport.cs b/src/mscorlib/src/System/Reflection/MdImport.cs
index b1d9c5eae8..a224a50513 100644
--- a/src/mscorlib/src/System/Reflection/MdImport.cs
+++ b/src/mscorlib/src/System/Reflection/MdImport.cs
@@ -21,149 +21,149 @@ using System.Diagnostics.Contracts;
namespace System.Reflection
{
[Serializable]
- internal enum CorElementType : byte
+ internal enum CorElementType : byte
{
- End = 0x00,
- Void = 0x01,
- Boolean = 0x02,
- Char = 0x03,
- I1 = 0x04,
- U1 = 0x05,
- I2 = 0x06,
- U2 = 0x07,
- I4 = 0x08,
- U4 = 0x09,
- I8 = 0x0A,
- U8 = 0x0B,
- R4 = 0x0C,
- R8 = 0x0D,
- String = 0x0E,
- Ptr = 0x0F,
- ByRef = 0x10,
- ValueType = 0x11,
- Class = 0x12,
- Var = 0x13,
- Array = 0x14,
- GenericInst = 0x15,
- TypedByRef = 0x16,
- I = 0x18,
- U = 0x19,
- FnPtr = 0x1B,
- Object = 0x1C,
- SzArray = 0x1D,
- MVar = 0x1E,
- CModReqd = 0x1F,
- CModOpt = 0x20,
- Internal = 0x21,
- Max = 0x22,
- Modifier = 0x40,
- Sentinel = 0x41,
- Pinned = 0x45,
+ End = 0x00,
+ Void = 0x01,
+ Boolean = 0x02,
+ Char = 0x03,
+ I1 = 0x04,
+ U1 = 0x05,
+ I2 = 0x06,
+ U2 = 0x07,
+ I4 = 0x08,
+ U4 = 0x09,
+ I8 = 0x0A,
+ U8 = 0x0B,
+ R4 = 0x0C,
+ R8 = 0x0D,
+ String = 0x0E,
+ Ptr = 0x0F,
+ ByRef = 0x10,
+ ValueType = 0x11,
+ Class = 0x12,
+ Var = 0x13,
+ Array = 0x14,
+ GenericInst = 0x15,
+ TypedByRef = 0x16,
+ I = 0x18,
+ U = 0x19,
+ FnPtr = 0x1B,
+ Object = 0x1C,
+ SzArray = 0x1D,
+ MVar = 0x1E,
+ CModReqd = 0x1F,
+ CModOpt = 0x20,
+ Internal = 0x21,
+ Max = 0x22,
+ Modifier = 0x40,
+ Sentinel = 0x41,
+ Pinned = 0x45,
}
-[Serializable]
-[Flags()]
- internal enum MdSigCallingConvention: byte
+ [Serializable]
+ [Flags()]
+ internal enum MdSigCallingConvention : byte
{
- CallConvMask = 0x0f, // Calling convention is bottom 4 bits
-
- Default = 0x00,
- C = 0x01,
- StdCall = 0x02,
- ThisCall = 0x03,
- FastCall = 0x04,
- Vararg = 0x05,
- Field = 0x06,
- LocalSig = 0x07,
- Property = 0x08,
- Unmgd = 0x09,
- GenericInst = 0x0a, // generic method instantiation
-
- Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
- HasThis = 0x20, // Top bit indicates a 'this' parameter
- ExplicitThis = 0x40, // This parameter is explicitly in the signature
+ CallConvMask = 0x0f, // Calling convention is bottom 4 bits
+
+ Default = 0x00,
+ C = 0x01,
+ StdCall = 0x02,
+ ThisCall = 0x03,
+ FastCall = 0x04,
+ Vararg = 0x05,
+ Field = 0x06,
+ LocalSig = 0x07,
+ Property = 0x08,
+ Unmgd = 0x09,
+ GenericInst = 0x0a, // generic method instantiation
+
+ Generic = 0x10, // Generic method sig with explicit number of type arguments (precedes ordinary parameter count)
+ HasThis = 0x20, // Top bit indicates a 'this' parameter
+ ExplicitThis = 0x40, // This parameter is explicitly in the signature
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
internal enum PInvokeAttributes
- {
- NoMangle = 0x0001,
-
-
- CharSetMask = 0x0006,
- CharSetNotSpec = 0x0000,
- CharSetAnsi = 0x0002,
- CharSetUnicode = 0x0004,
- CharSetAuto = 0x0006,
-
-
- BestFitUseAssem = 0x0000,
- BestFitEnabled = 0x0010,
- BestFitDisabled = 0x0020,
- BestFitMask = 0x0030,
-
- ThrowOnUnmappableCharUseAssem = 0x0000,
- ThrowOnUnmappableCharEnabled = 0x1000,
- ThrowOnUnmappableCharDisabled = 0x2000,
- ThrowOnUnmappableCharMask = 0x3000,
-
- SupportsLastError = 0x0040,
-
- CallConvMask = 0x0700,
- CallConvWinapi = 0x0100,
- CallConvCdecl = 0x0200,
- CallConvStdcall = 0x0300,
- CallConvThiscall = 0x0400,
- CallConvFastcall = 0x0500,
-
- MaxValue = 0xFFFF,
+ {
+ NoMangle = 0x0001,
+
+
+ CharSetMask = 0x0006,
+ CharSetNotSpec = 0x0000,
+ CharSetAnsi = 0x0002,
+ CharSetUnicode = 0x0004,
+ CharSetAuto = 0x0006,
+
+
+ BestFitUseAssem = 0x0000,
+ BestFitEnabled = 0x0010,
+ BestFitDisabled = 0x0020,
+ BestFitMask = 0x0030,
+
+ ThrowOnUnmappableCharUseAssem = 0x0000,
+ ThrowOnUnmappableCharEnabled = 0x1000,
+ ThrowOnUnmappableCharDisabled = 0x2000,
+ ThrowOnUnmappableCharMask = 0x3000,
+
+ SupportsLastError = 0x0040,
+
+ CallConvMask = 0x0700,
+ CallConvWinapi = 0x0100,
+ CallConvCdecl = 0x0200,
+ CallConvStdcall = 0x0300,
+ CallConvThiscall = 0x0400,
+ CallConvFastcall = 0x0500,
+
+ MaxValue = 0xFFFF,
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
internal enum MethodSemanticsAttributes
{
- Setter = 0x0001,
- Getter = 0x0002,
- Other = 0x0004,
- AddOn = 0x0008,
- RemoveOn = 0x0010,
- Fire = 0x0020,
+ Setter = 0x0001,
+ Getter = 0x0002,
+ Other = 0x0004,
+ AddOn = 0x0008,
+ RemoveOn = 0x0010,
+ Fire = 0x0020,
}
[Serializable]
internal enum MetadataTokenType
{
- Module = 0x00000000,
- TypeRef = 0x01000000,
- TypeDef = 0x02000000,
- FieldDef = 0x04000000,
- MethodDef = 0x06000000,
- ParamDef = 0x08000000,
- InterfaceImpl = 0x09000000,
- MemberRef = 0x0a000000,
- CustomAttribute = 0x0c000000,
- Permission = 0x0e000000,
- Signature = 0x11000000,
- Event = 0x14000000,
- Property = 0x17000000,
- ModuleRef = 0x1a000000,
- TypeSpec = 0x1b000000,
- Assembly = 0x20000000,
- AssemblyRef = 0x23000000,
- File = 0x26000000,
- ExportedType = 0x27000000,
- ManifestResource = 0x28000000,
- GenericPar = 0x2a000000,
- MethodSpec = 0x2b000000,
- String = 0x70000000,
- Name = 0x71000000,
- BaseType = 0x72000000,
- Invalid = 0x7FFFFFFF,
+ Module = 0x00000000,
+ TypeRef = 0x01000000,
+ TypeDef = 0x02000000,
+ FieldDef = 0x04000000,
+ MethodDef = 0x06000000,
+ ParamDef = 0x08000000,
+ InterfaceImpl = 0x09000000,
+ MemberRef = 0x0a000000,
+ CustomAttribute = 0x0c000000,
+ Permission = 0x0e000000,
+ Signature = 0x11000000,
+ Event = 0x14000000,
+ Property = 0x17000000,
+ ModuleRef = 0x1a000000,
+ TypeSpec = 0x1b000000,
+ Assembly = 0x20000000,
+ AssemblyRef = 0x23000000,
+ File = 0x26000000,
+ ExportedType = 0x27000000,
+ ManifestResource = 0x28000000,
+ GenericPar = 0x2a000000,
+ MethodSpec = 0x2b000000,
+ String = 0x70000000,
+ Name = 0x71000000,
+ BaseType = 0x72000000,
+ Invalid = 0x7FFFFFFF,
}
[Serializable]
@@ -179,7 +179,7 @@ namespace System.Reflection
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
- unsafe
+ unsafe
{
return ((byte*)m_constArray.ToPointer())[index];
}
@@ -190,7 +190,7 @@ namespace System.Reflection
internal int m_length;
internal IntPtr m_constArray;
}
-
+
[Serializable]
internal struct MetadataToken
{
@@ -211,9 +211,9 @@ namespace System.Reflection
return false;
}
- public static bool IsNullToken(int token)
- {
- return (token & 0x00FFFFFF) == 0;
+ public static bool IsNullToken(int token)
+ {
+ return (token & 0x00FFFFFF) == 0;
}
#endregion
@@ -222,11 +222,11 @@ namespace System.Reflection
#endregion
#region Constructor
- public MetadataToken(int token) { Value = token; }
+ public MetadataToken(int token) { Value = token; }
#endregion
-
+
#region Public Members
- public bool IsGlobalTypeDefToken { get { return (Value == 0x02000001); } }
+ public bool IsGlobalTypeDefToken { get { return (Value == 0x02000001); } }
public MetadataTokenType TokenType { get { return (MetadataTokenType)(Value & 0xFF000000); } }
public bool IsTypeRef { get { return TokenType == MetadataTokenType.TypeRef; } }
public bool IsTypeDef { get { return TokenType == MetadataTokenType.TypeDef; } }
@@ -288,7 +288,7 @@ namespace System.Reflection
#region Override methods from Object
internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null);
-
+
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(m_metadataImport2);
@@ -296,11 +296,11 @@ namespace System.Reflection
public override bool Equals(object obj)
{
- if(!(obj is MetadataImport))
+ if (!(obj is MetadataImport))
return false;
return Equals((MetadataImport)obj);
}
-
+
private bool Equals(MetadataImport import)
{
return import.m_metadataImport2 == m_metadataImport2;
@@ -310,18 +310,18 @@ namespace System.Reflection
#region Static Members
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType,
+ private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType,
out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
out int iidParamIndex);
- internal static void GetMarshalAs(ConstArray nativeType,
- out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType,
+ internal static void GetMarshalAs(ConstArray nativeType,
+ out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType,
out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie,
out int iidParamIndex)
{
int _unmanagedType, _safeArraySubType, _arraySubType;
_GetMarshalAs(nativeType.Signature, (int)nativeType.Length,
- out _unmanagedType, out _safeArraySubType, out safeArrayUserDefinedSubType,
+ out _unmanagedType, out _safeArraySubType, out safeArrayUserDefinedSubType,
out _arraySubType, out sizeParamIndex, out sizeConst, out marshalType, out marshalCookie,
out iidParamIndex);
unmanagedType = (UnmanagedType)_unmanagedType;
@@ -339,32 +339,32 @@ namespace System.Reflection
#region Constructor
internal MetadataImport(IntPtr metadataImport2, object keepalive)
- {
+ {
m_metadataImport2 = metadataImport2;
m_keepalive = keepalive;
}
#endregion
#region FCalls
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result);
- public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result)
- {
+ public unsafe void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result)
+ {
_Enum(m_metadataImport2, (int)type, parent, out result);
}
- public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result)
+ public unsafe void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.TypeDef, mdTypeDef, out result);
}
- public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result)
+ public unsafe void EnumCustomAttributes(int mdToken, out MetadataEnumResult result)
{
Enum(MetadataTokenType.CustomAttribute, mdToken, out result);
}
- public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result)
+ public unsafe void EnumParams(int mdMethodDef, out MetadataEnumResult result)
{
Enum(MetadataTokenType.ParamDef, mdMethodDef, out result);
}
@@ -384,30 +384,30 @@ namespace System.Reflection
Enum(MetadataTokenType.Event, mdTypeDef, out result);
}
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern String _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType);
- public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
- {
- int _corElementType;
+ public String GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType)
+ {
+ int _corElementType;
String stringVal;
- stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType);
+ stringVal = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out _corElementType);
corElementType = (CorElementType)_corElementType;
return stringVal;
}
-
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length);
- public unsafe String GetUserString(int mdToken)
- {
+ public unsafe String GetUserString(int mdToken)
+ {
void* name;
int length;
- _GetUserString(m_metadataImport2, mdToken, &name, out length);
+ _GetUserString(m_metadataImport2, mdToken, &name, out length);
if (name == null)
return null;
char[] c = new char[length];
- for (int i = 0; i < c.Length; i ++)
+ for (int i = 0; i < c.Length; i++)
{
#if ALIGN_ACCESS
c[i] = (char)Marshal.ReadInt16( (IntPtr) (((char*)name) + i) );
@@ -419,87 +419,87 @@ namespace System.Reflection
return new String(c);
}
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern void _GetName(IntPtr scope, int mdToken, void** name);
- public unsafe Utf8String GetName(int mdToken)
- {
+ public unsafe Utf8String GetName(int mdToken)
+ {
void* name;
- _GetName(m_metadataImport2, mdToken, &name);
-
+ _GetName(m_metadataImport2, mdToken, &name);
+
return new Utf8String(name);
}
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private static unsafe extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp);
- public unsafe Utf8String GetNamespace(int mdToken)
- {
+ public unsafe Utf8String GetNamespace(int mdToken)
+ {
void* namesp;
_GetNamespace(m_metadataImport2, mdToken, &namesp);
-
+
return new Utf8String(namesp);
}
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes);
- public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes)
- {
- int _eventAttributes;
+ public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes)
+ {
+ int _eventAttributes;
void* _name;
_GetEventProps(m_metadataImport2, mdToken, &_name, out _eventAttributes);
name = _name;
eventAttributes = (EventAttributes)_eventAttributes;
}
-
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes);
- public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes)
- {
- int _fieldAttributes;
+ public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes)
+ {
+ int _fieldAttributes;
_GetFieldDefProps(m_metadataImport2, mdToken, out _fieldAttributes);
fieldAttributes = (FieldAttributes)_fieldAttributes;
}
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
- private unsafe static extern void _GetPropertyProps(IntPtr scope,
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private unsafe static extern void _GetPropertyProps(IntPtr scope,
int mdToken, void** name, out int propertyAttributes, out ConstArray signature);
- public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature)
- {
- int _propertyAttributes;
+ public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature)
+ {
+ int _propertyAttributes;
void* _name;
- _GetPropertyProps(m_metadataImport2, mdToken, &_name, out _propertyAttributes, out signature);
+ _GetPropertyProps(m_metadataImport2, mdToken, &_name, out _propertyAttributes, out signature);
name = _name;
propertyAttributes = (PropertyAttributes)_propertyAttributes;
}
- [MethodImplAttribute (MethodImplOptions.InternalCall)]
- private static extern void _GetParentToken(IntPtr scope,
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private static extern void _GetParentToken(IntPtr scope,
int mdToken, out int tkParent);
- public int GetParentToken(int tkToken)
- {
+ public int GetParentToken(int tkToken)
+ {
int tkParent;
- _GetParentToken(m_metadataImport2, tkToken, out tkParent);
+ _GetParentToken(m_metadataImport2, tkToken, out tkParent);
return tkParent;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetParamDefProps(IntPtr scope,
+ private static extern void _GetParamDefProps(IntPtr scope,
int parameterToken, out int sequence, out int attributes);
public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes)
{
int _attributes;
_GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out _attributes);
-
+
attributes = (ParameterAttributes)_attributes;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetGenericParamProps(IntPtr scope,
- int genericParameter,
+ private static extern void _GetGenericParamProps(IntPtr scope,
+ int genericParameter,
out int flags);
-
+
public void GetGenericParamProps(
- int genericParameter,
+ int genericParameter,
out GenericParameterAttributes attributes)
{
int _attributes;
@@ -508,9 +508,9 @@ namespace System.Reflection
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetScopeProps(IntPtr scope,
+ private static extern void _GetScopeProps(IntPtr scope,
out Guid mvid);
-
+
public void GetScopeProps(
out Guid mvid)
{
@@ -522,15 +522,15 @@ namespace System.Reflection
{
if (token.IsMemberRef)
return GetMemberRefProps(token);
-
+
return GetSigOfMethodDef(token);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetSigOfMethodDef(IntPtr scope,
- int methodToken,
+ private static extern void _GetSigOfMethodDef(IntPtr scope,
+ int methodToken,
ref ConstArray signature);
-
+
public ConstArray GetSigOfMethodDef(int methodToken)
{
ConstArray signature = new ConstArray();
@@ -541,10 +541,10 @@ namespace System.Reflection
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetSignatureFromToken(IntPtr scope,
- int methodToken,
+ private static extern void _GetSignatureFromToken(IntPtr scope,
+ int methodToken,
ref ConstArray signature);
-
+
public ConstArray GetSignatureFromToken(int token)
{
ConstArray signature = new ConstArray();
@@ -555,61 +555,61 @@ namespace System.Reflection
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetMemberRefProps(IntPtr scope,
- int memberTokenRef,
+ private static extern void _GetMemberRefProps(IntPtr scope,
+ int memberTokenRef,
out ConstArray signature);
-
+
public ConstArray GetMemberRefProps(int memberTokenRef)
{
ConstArray signature = new ConstArray();
-
+
_GetMemberRefProps(m_metadataImport2, memberTokenRef, out signature);
return signature;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetCustomAttributeProps(IntPtr scope,
- int customAttributeToken,
- out int constructorToken,
+ private static extern void _GetCustomAttributeProps(IntPtr scope,
+ int customAttributeToken,
+ out int constructorToken,
out ConstArray signature);
-
- public void GetCustomAttributeProps(
- int customAttributeToken,
- out int constructorToken,
+
+ public void GetCustomAttributeProps(
+ int customAttributeToken,
+ out int constructorToken,
out ConstArray signature)
{
- _GetCustomAttributeProps(m_metadataImport2, customAttributeToken,
+ _GetCustomAttributeProps(m_metadataImport2, customAttributeToken,
out constructorToken, out signature);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetClassLayout(IntPtr scope,
+ private static extern void _GetClassLayout(IntPtr scope,
int typeTokenDef, out int packSize, out int classSize);
public void GetClassLayout(
- int typeTokenDef,
- out int packSize,
+ int typeTokenDef,
+ out int packSize,
out int classSize)
{
_GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool _GetFieldOffset(IntPtr scope,
+ private static extern bool _GetFieldOffset(IntPtr scope,
int typeTokenDef, int fieldTokenDef, out int offset);
public bool GetFieldOffset(
- int typeTokenDef,
- int fieldTokenDef,
+ int typeTokenDef,
+ int fieldTokenDef,
out int offset)
{
return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetSigOfFieldDef(IntPtr scope,
- int fieldToken,
+ private static extern void _GetSigOfFieldDef(IntPtr scope,
+ int fieldToken,
ref ConstArray fieldMarshal);
-
+
public ConstArray GetSigOfFieldDef(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
@@ -620,10 +620,10 @@ namespace System.Reflection
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern void _GetFieldMarshal(IntPtr scope,
- int fieldToken,
+ private static extern void _GetFieldMarshal(IntPtr scope,
+ int fieldToken,
ref ConstArray fieldMarshal);
-
+
public ConstArray GetFieldMarshal(int fieldToken)
{
ConstArray fieldMarshal = new ConstArray();
@@ -634,16 +634,16 @@ namespace System.Reflection
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private unsafe static extern void _GetPInvokeMap(IntPtr scope,
- int token,
- out int attributes,
- void** importName,
- void** importDll);
-
+ private unsafe static extern void _GetPInvokeMap(IntPtr scope,
+ int token,
+ out int attributes,
+ void** importName,
+ void** importDll);
+
public unsafe void GetPInvokeMap(
- int token,
- out PInvokeAttributes attributes,
- out String importName,
+ int token,
+ out PInvokeAttributes attributes,
+ out String importName,
out String importDll)
{
int _attributes;
@@ -656,10 +656,10 @@ namespace System.Reflection
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern bool _IsValidToken(IntPtr scope, int token);
- public bool IsValidToken(int token)
- {
- return _IsValidToken(m_metadataImport2, token);
+ private static extern bool _IsValidToken(IntPtr scope, int token);
+ public bool IsValidToken(int token)
+ {
+ return _IsValidToken(m_metadataImport2, token);
}
#endregion
}
diff --git a/src/mscorlib/src/System/Reflection/MemberFilter.cs b/src/mscorlib/src/System/Reflection/MemberFilter.cs
deleted file mode 100644
index 56fc9c0804..0000000000
--- a/src/mscorlib/src/System/Reflection/MemberFilter.cs
+++ /dev/null
@@ -1,18 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// MemberFilter is a delegate used to filter Members. This delegate is used
-//
-// as a callback from Type.FindMembers.
-//
-//
-namespace System.Reflection {
-
- // Define the delegate
- [Serializable]
- public delegate bool MemberFilter(MemberInfo m, Object filterCriteria);
-}
diff --git a/src/mscorlib/src/System/IObservable.cs b/src/mscorlib/src/System/Reflection/MemberInfo.Internal.cs
index aabb0b8fb4..8e7be56511 100644
--- a/src/mscorlib/src/System/IObservable.cs
+++ b/src/mscorlib/src/System/Reflection/MemberInfo.Internal.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.
-namespace System
+namespace System.Reflection
{
- public interface IObservable<out T>
+ public abstract partial class MemberInfo
{
- IDisposable Subscribe(IObserver<T> observer);
+ internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); }
}
}
diff --git a/src/mscorlib/src/System/Reflection/MemberInfo.cs b/src/mscorlib/src/System/Reflection/MemberInfo.cs
deleted file mode 100644
index 5ecbfe06a1..0000000000
--- a/src/mscorlib/src/System/Reflection/MemberInfo.cs
+++ /dev/null
@@ -1,113 +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.
-
-//
-
-namespace System.Reflection
-{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.Contracts;
- using System.Runtime;
- using System.Runtime.InteropServices;
-
- [Serializable]
- public abstract class MemberInfo : ICustomAttributeProvider
- {
- #region Constructor
- protected MemberInfo() { }
- #endregion
-
- #region Internal Methods
- internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); }
- #endregion
-
- #region Public Abstract\Virtual Members
- public abstract MemberTypes MemberType { get; }
-
- public abstract String Name { get; }
-
- public abstract Type DeclaringType { get; }
-
- public abstract Type ReflectedType { get; }
-
- public virtual IEnumerable<CustomAttributeData> CustomAttributes
- {
- get
- {
- return GetCustomAttributesData();
- }
- }
- public abstract Object[] GetCustomAttributes(bool inherit);
-
- public abstract Object[] GetCustomAttributes(Type attributeType, bool inherit);
-
- public abstract bool IsDefined(Type attributeType, bool inherit);
-
- public virtual IList<CustomAttributeData> GetCustomAttributesData()
- {
- throw new NotImplementedException();
- }
-
- public virtual int MetadataToken { get { throw new InvalidOperationException(); } }
-
- public virtual Module Module
- {
- get
- {
- if (this is Type)
- return ((Type)this).Module;
-
- throw new NotImplementedException();
- }
- }
-
-
-
- #endregion
-
- public static bool operator ==(MemberInfo left, MemberInfo right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null)
- return false;
-
- Type type1, type2;
- MethodBase method1, method2;
- FieldInfo field1, field2;
- EventInfo event1, event2;
- PropertyInfo property1, property2;
-
- if ((type1 = left as Type) != null && (type2 = right as Type) != null)
- return type1 == type2;
- else if ((method1 = left as MethodBase) != null && (method2 = right as MethodBase) != null)
- return method1 == method2;
- else if ((field1 = left as FieldInfo) != null && (field2 = right as FieldInfo) != null)
- return field1 == field2;
- else if ((event1 = left as EventInfo) != null && (event2 = right as EventInfo) != null)
- return event1 == event2;
- else if ((property1 = left as PropertyInfo) != null && (property2 = right as PropertyInfo) != null)
- return property1 == property2;
-
- return false;
- }
-
- public static bool operator !=(MemberInfo left, MemberInfo right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs b/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
deleted file mode 100644
index 20ff37650c..0000000000
--- a/src/mscorlib/src/System/Reflection/MemberInfoSerializationHolder.cs
+++ /dev/null
@@ -1,285 +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.Runtime.Remoting;
-using System.Runtime.Serialization;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-
-namespace System.Reflection
-{
- [Serializable]
- internal class MemberInfoSerializationHolder : ISerializable, IObjectReference
- {
- #region Staitc Public Members
- public static void GetSerializationInfo(SerializationInfo info, String name, RuntimeType reflectedClass, String signature, MemberTypes type)
- {
- GetSerializationInfo(info, name, reflectedClass, signature, null, type, null);
- }
-
- public static void GetSerializationInfo(
- SerializationInfo info,
- String name,
- RuntimeType reflectedClass,
- String signature,
- String signature2,
- MemberTypes type,
- Type[] genericArguments)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- String assemblyName = reflectedClass.Module.Assembly.FullName;
- String typeName = reflectedClass.FullName;
-
- info.SetType(typeof(MemberInfoSerializationHolder));
- info.AddValue("Name", name, typeof(String));
- info.AddValue("AssemblyName", assemblyName, typeof(String));
- info.AddValue("ClassName", typeName, typeof(String));
- info.AddValue("Signature", signature, typeof(String));
- info.AddValue("Signature2", signature2, typeof(String));
- info.AddValue("MemberType", (int)type);
- info.AddValue("GenericArguments", genericArguments, typeof(Type[]));
- }
- #endregion
-
- #region Private Data Members
- private String m_memberName;
- private RuntimeType m_reflectedType;
- // m_signature stores the ToString() representation of the member which is sometimes ambiguous.
- // Mulitple overloads of the same methods or properties can identical ToString().
- // m_signature2 stores the SerializationToString() representation which should be unique for each member.
- // It is only written and used by post 4.0 CLR versions.
- private String m_signature;
- private String m_signature2;
- private MemberTypes m_memberType;
- private SerializationInfo m_info;
- #endregion
-
- #region Constructor
- internal MemberInfoSerializationHolder(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- String assemblyName = info.GetString("AssemblyName");
- String typeName = info.GetString("ClassName");
-
- if (assemblyName == null || typeName == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
-
- Assembly assem = FormatterServices.LoadAssemblyFromString(assemblyName);
- m_reflectedType = assem.GetType(typeName, true, false) as RuntimeType;
- m_memberName = info.GetString("Name");
- m_signature = info.GetString("Signature");
- // Only v4.0 and later generates and consumes Signature2
- m_signature2 = (string)info.GetValueNoThrow("Signature2", typeof(string));
- m_memberType = (MemberTypes)info.GetInt32("MemberType");
- m_info = info;
- }
- #endregion
-
- #region ISerializable
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(Environment.GetResourceString(ResId.NotSupported_Method));
- }
- #endregion
-
- #region IObjectReference
- public virtual Object GetRealObject(StreamingContext context)
- {
- if (m_memberName == null || m_reflectedType == null || m_memberType == 0)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState));
-
- BindingFlags bindingFlags =
- BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic |
- BindingFlags.Static | BindingFlags.OptionalParamBinding;
-
- switch (m_memberType)
- {
- #region case MemberTypes.Field:
- case MemberTypes.Field:
- {
- FieldInfo[] fields = m_reflectedType.GetMember(m_memberName, MemberTypes.Field, bindingFlags) as FieldInfo[];
-
- if (fields.Length == 0)
- throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
-
- return fields[0];
- }
- #endregion
-
- #region case MemberTypes.Event:
- case MemberTypes.Event:
- {
- EventInfo[] events = m_reflectedType.GetMember(m_memberName, MemberTypes.Event, bindingFlags) as EventInfo[];
-
- if (events.Length == 0)
- throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
-
- return events[0];
- }
- #endregion
-
- #region case MemberTypes.Property:
- case MemberTypes.Property:
- {
- PropertyInfo[] properties = m_reflectedType.GetMember(m_memberName, MemberTypes.Property, bindingFlags) as PropertyInfo[];
-
- if (properties.Length == 0)
- throw new SerializationException(Environment.GetResourceString("Serialization_UnknownMember", m_memberName));
-
- if (properties.Length == 1)
- return properties[0];
-
- if (properties.Length > 1)
- {
- for (int i = 0; i < properties.Length; i++)
- {
- if (m_signature2 != null)
- {
- if (((RuntimePropertyInfo)properties[i]).SerializationToString().Equals(m_signature2))
- return properties[i];
- }
- else
- {
- if ((properties[i]).ToString().Equals(m_signature))
- return properties[i];
- }
- }
- }
-
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
- }
- #endregion
-
- #region case MemberTypes.Constructor:
- case MemberTypes.Constructor:
- {
- if (m_signature == null)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
-
- ConstructorInfo[] constructors = m_reflectedType.GetMember(m_memberName, MemberTypes.Constructor, bindingFlags) as ConstructorInfo[];
-
- if (constructors.Length == 1)
- return constructors[0];
-
- if (constructors.Length > 1)
- {
- for (int i = 0; i < constructors.Length; i++)
- {
- if (m_signature2 != null)
- {
- if (((RuntimeConstructorInfo)constructors[i]).SerializationToString().Equals(m_signature2))
- return constructors[i];
- }
- else
- {
- if (constructors[i].ToString().Equals(m_signature))
- return constructors[i];
- }
- }
- }
-
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
- }
- #endregion
-
- #region case MemberTypes.Method:
- case MemberTypes.Method:
- {
- MethodInfo methodInfo = null;
-
- if (m_signature == null)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NullSignature));
-
- Type[] genericArguments = m_info.GetValueNoThrow("GenericArguments", typeof(Type[])) as Type[];
-
- MethodInfo[] methods = m_reflectedType.GetMember(m_memberName, MemberTypes.Method, bindingFlags) as MethodInfo[];
-
- if (methods.Length == 1)
- methodInfo = methods[0];
-
- else if (methods.Length > 1)
- {
- for (int i = 0; i < methods.Length; i++)
- {
- if (m_signature2 != null)
- {
- if (((RuntimeMethodInfo)methods[i]).SerializationToString().Equals(m_signature2))
- {
- methodInfo = methods[i];
- break;
- }
- }
- else
- {
-
- if (methods[i].ToString().Equals(m_signature))
- {
- methodInfo = methods[i];
- break;
- }
- }
-
- // Handle generic methods specially since the signature match above probably won't work (the candidate
- // method info hasn't been instantiated). If our target method is generic as well we can skip this.
- if (genericArguments != null && methods[i].IsGenericMethod)
- {
- if (methods[i].GetGenericArguments().Length == genericArguments.Length)
- {
- MethodInfo candidateMethod = methods[i].MakeGenericMethod(genericArguments);
-
- if (m_signature2 != null)
- {
- if (((RuntimeMethodInfo)candidateMethod).SerializationToString().Equals(m_signature2))
- {
- methodInfo = candidateMethod;
- break;
- }
- }
- else
- {
- if (candidateMethod.ToString().Equals(m_signature))
- {
- methodInfo = candidateMethod;
- break;
- }
- }
- }
- }
- }
- }
-
- if (methodInfo == null)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_UnknownMember, m_memberName));
-
- if (!methodInfo.IsGenericMethodDefinition)
- return methodInfo;
-
- if (genericArguments == null)
- return methodInfo;
-
- if (genericArguments[0] == null)
- return null;
-
- return methodInfo.MakeGenericMethod(genericArguments);
- }
- #endregion
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Serialization_MemberTypeNotRecognized"));
- }
- }
- #endregion
- }
-
-
-}
diff --git a/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs b/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs
new file mode 100644
index 0000000000..d25c746a85
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/MemberSerializationStringGenerator.cs
@@ -0,0 +1,39 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Text;
+using System.Reflection;
+using System.Diagnostics;
+using System.Collections.Generic;
+
+namespace System
+{
+ internal static class MemberSerializationStringGenerator
+ {
+ //
+ // Generate the "Signature2" binary serialization string for PropertyInfos
+ //
+ // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing
+ // metadata prevents generating the string, this method throws a MissingMetadata exception.
+ //
+ public static string SerializationToString(this PropertyInfo property) => ((RuntimePropertyInfo)property).SerializationToString();
+
+ //
+ // Generate the "Signature2" binary serialization string for ConstructorInfos
+ //
+ // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing
+ // metadata prevents generating the string, this method throws a MissingMetadata exception.
+ //
+ public static string SerializationToString(this ConstructorInfo constructor) => ((RuntimeConstructorInfo)constructor).SerializationToString();
+
+ //
+ // Generate the "Signature2" binary serialization string for MethodInfos
+ //
+ // Because the string is effectively a file format for serialized Reflection objects, it must be exactly correct. If missing
+ // metadata prevents generating the string, this method throws a MissingMetadata exception.
+ //
+ public static string SerializationToString(this MethodInfo method) => ((RuntimeMethodInfo)method).SerializationToString();
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/MemberTypes.cs b/src/mscorlib/src/System/Reflection/MemberTypes.cs
deleted file mode 100644
index 95c41022f1..0000000000
--- a/src/mscorlib/src/System/Reflection/MemberTypes.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// MemberTypes is an bit mask marking each type of Member that is defined as
-//
-// a subclass of MemberInfo. These are returned by MemberInfo.MemberType and
-// are useful in switch statements.
-//
-//
-namespace System.Reflection {
-
- using System;
- // This Enum matchs the CorTypeAttr defined in CorHdr.h
- [Serializable]
- [Flags()]
- public enum MemberTypes
- {
- // The following are the known classes which extend MemberInfo
- Constructor = 0x01,
- Event = 0x02,
- Field = 0x04,
- Method = 0x08,
- Property = 0x10,
- TypeInfo = 0x20,
- Custom = 0x40,
- NestedType = 0x80,
- All = Constructor | Event | Field | Method | Property | TypeInfo | NestedType,
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/MethodAttributes.cs b/src/mscorlib/src/System/Reflection/MethodAttributes.cs
deleted file mode 100644
index 7e4391cccd..0000000000
--- a/src/mscorlib/src/System/Reflection/MethodAttributes.cs
+++ /dev/null
@@ -1,55 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-//
-
-namespace System.Reflection
-{
- using System;
- [Serializable]
- [Flags]
- public enum MethodAttributes
- {
- // NOTE: This Enum matchs the CorMethodAttr defined in CorHdr.h
-
- // member access mask - Use this mask to retrieve accessibility information.
- MemberAccessMask = 0x0007,
- PrivateScope = 0x0000, // Member not referenceable.
- Private = 0x0001, // Accessible only by the parent type.
- FamANDAssem = 0x0002, // Accessible by sub-types only in this Assembly.
- Assembly = 0x0003, // Accessibly by anyone in the Assembly.
- Family = 0x0004, // Accessible only by type and sub-types.
- FamORAssem = 0x0005, // Accessibly by sub-types anywhere, plus anyone in assembly.
- Public = 0x0006, // Accessibly by anyone who has visibility to this scope.
- // end member access mask
-
- // method contract attributes.
- Static = 0x0010, // Defined on type, else per instance.
- Final = 0x0020, // Method may not be overridden.
- Virtual = 0x0040, // Method virtual.
- HideBySig = 0x0080, // Method hides by name+sig, else just by name.
- CheckAccessOnOverride= 0x0200,
-
- // vtable layout mask - Use this mask to retrieve vtable attributes.
- VtableLayoutMask = 0x0100,
- ReuseSlot = 0x0000, // The default.
- NewSlot = 0x0100, // Method always gets a new slot in the vtable.
- // end vtable layout mask
-
- // method implementation attributes.
- Abstract = 0x0400, // Method does not provide an implementation.
- SpecialName = 0x0800, // Method is special. Name describes how.
-
- // interop attributes
- PinvokeImpl = 0x2000, // Implementation is forwarded through pinvoke.
- UnmanagedExport = 0x0008, // Managed method exported via thunk to unmanaged code.
- RTSpecialName = 0x1000, // Runtime should check name encoding.
-
- // Reserved flags for runtime use only.
- ReservedMask = 0xd000,
- HasSecurity = 0x4000, // Method has security associate with it.
- RequireSecObject = 0x8000, // Method calls another method containing security code.
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/MethodBase.CoreCLR.cs b/src/mscorlib/src/System/Reflection/MethodBase.CoreCLR.cs
new file mode 100644
index 0000000000..3afd396471
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/MethodBase.CoreCLR.cs
@@ -0,0 +1,157 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Globalization;
+using System.Text;
+using System.Threading;
+
+namespace System.Reflection
+{
+ public abstract partial class MethodBase : MemberInfo
+ {
+ #region Static Members
+ public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
+ {
+ if (handle.IsNullHandle())
+ throw new ArgumentException(SR.Argument_InvalidHandle);
+
+ MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo());
+
+ Type declaringType = m.DeclaringType;
+ if (declaringType != null && declaringType.IsGenericType)
+ throw new ArgumentException(String.Format(
+ CultureInfo.CurrentCulture, SR.Argument_MethodDeclaringTypeGeneric,
+ m, declaringType.GetGenericTypeDefinition()));
+
+ return m;
+ }
+
+ public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
+ {
+ if (handle.IsNullHandle())
+ throw new ArgumentException(SR.Argument_InvalidHandle);
+
+ return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo());
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static MethodBase GetCurrentMethod()
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark);
+ }
+ #endregion
+
+ #region Internal Members
+ // used by EE
+ private IntPtr GetMethodDesc() { return MethodHandle.Value; }
+
+ internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters(); }
+ #endregion
+
+ #region Internal Methods
+ // helper method to construct the string representation of the parameter list
+
+ internal static string ConstructParameters(Type[] parameterTypes, CallingConventions callingConvention, bool serialization)
+ {
+ StringBuilder sbParamList = new StringBuilder();
+ string comma = "";
+
+ for (int i = 0; i < parameterTypes.Length; i++)
+ {
+ Type t = parameterTypes[i];
+
+ sbParamList.Append(comma);
+
+ string typeName = t.FormatTypeName(serialization);
+
+ // Legacy: Why use "ByRef" for by ref parameters? What language is this?
+ // VB uses "ByRef" but it should precede (not follow) the parameter name.
+ // Why don't we just use "&"?
+ if (t.IsByRef && !serialization)
+ {
+ sbParamList.Append(typeName.TrimEnd('&'));
+ sbParamList.Append(" ByRef");
+ }
+ else
+ {
+ sbParamList.Append(typeName);
+ }
+
+ comma = ", ";
+ }
+
+ if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
+ {
+ sbParamList.Append(comma);
+ sbParamList.Append("...");
+ }
+
+ return sbParamList.ToString();
+ }
+
+ internal string FullName
+ {
+ get
+ {
+ return String.Format("{0}.{1}", DeclaringType.FullName, FormatNameAndSig());
+ }
+ }
+ internal string FormatNameAndSig()
+ {
+ return FormatNameAndSig(false);
+ }
+
+ internal virtual string FormatNameAndSig(bool serialization)
+ {
+ // Serialization uses ToString to resolve MethodInfo overloads.
+ StringBuilder sbName = new StringBuilder(Name);
+
+ sbName.Append("(");
+ sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
+ sbName.Append(")");
+
+ return sbName.ToString();
+ }
+
+ internal virtual Type[] GetParameterTypes()
+ {
+ ParameterInfo[] paramInfo = GetParametersNoCopy();
+
+ Type[] parameterTypes = new Type[paramInfo.Length];
+ for (int i = 0; i < paramInfo.Length; i++)
+ parameterTypes[i] = paramInfo[i].ParameterType;
+
+ return parameterTypes;
+ }
+
+ internal Object[] CheckArguments(Object[] parameters, Binder binder,
+ BindingFlags invokeAttr, CultureInfo culture, Signature sig)
+ {
+ // copy the arguments in a different array so we detach from any user changes
+ Object[] copyOfParameters = new Object[parameters.Length];
+
+ ParameterInfo[] p = null;
+ for (int i = 0; i < parameters.Length; i++)
+ {
+ Object arg = parameters[i];
+ RuntimeType argRT = sig.Arguments[i];
+
+ if (arg == Type.Missing)
+ {
+ if (p == null)
+ p = GetParametersNoCopy();
+ if (p[i].DefaultValue == System.DBNull.Value)
+ throw new ArgumentException(SR.Arg_VarMissNull, nameof(parameters));
+ arg = p[i].DefaultValue;
+ }
+ copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
+ }
+
+ return copyOfParameters;
+ }
+ #endregion
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/MethodBase.cs b/src/mscorlib/src/System/Reflection/MethodBase.cs
deleted file mode 100644
index 3109821ac9..0000000000
--- a/src/mscorlib/src/System/Reflection/MethodBase.cs
+++ /dev/null
@@ -1,330 +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.
-
-//
-
-namespace System.Reflection
-{
- using System;
- using System.Diagnostics;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
-
- //
- // Invocation cached flags. Those are used in unmanaged code as well
- // so be careful if you change them
- //
- [Flags]
- internal enum INVOCATION_FLAGS : uint
- {
- INVOCATION_FLAGS_UNKNOWN = 0x00000000,
- 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,
- // 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,
- // because field and method are different we can reuse the same bits
- // method
- INVOCATION_FLAGS_IS_CTOR = 0x00000010,
- INVOCATION_FLAGS_RISKY_METHOD = 0x00000020,
- INVOCATION_FLAGS_NON_W8P_FX_API = 0x00000040,
- INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080,
- INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100,
- // field
- INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010,
- INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020,
-
- // temporary flag used for flagging invocation of method vs ctor
- // this flag never appears on the instance m_invocationFlag and is simply
- // passed down from within ConstructorInfo.Invoke()
- INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000,
- }
-
- [Serializable]
- public abstract class MethodBase : MemberInfo
- {
- #region Static Members
- public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle)
- {
- if (handle.IsNullHandle())
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
-
- MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo());
-
- Type declaringType = m.DeclaringType;
- if (declaringType != null && declaringType.IsGenericType)
- throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"),
- m, declaringType.GetGenericTypeDefinition()));
-
- return m;
- }
-
- public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType)
- {
- if (handle.IsNullHandle())
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle"));
-
- return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo());
- }
-
- [System.Security.DynamicSecurityMethod] // Specify DynamicSecurityMethod attribute to prevent inlining of the caller.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static MethodBase GetCurrentMethod()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark);
- }
- #endregion
-
- #region Constructor
- protected MethodBase() { }
- #endregion
-
- public static bool operator ==(MethodBase left, MethodBase right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null)
- return false;
-
- MethodInfo method1, method2;
- ConstructorInfo constructor1, constructor2;
-
- if ((method1 = left as MethodInfo) != null && (method2 = right as MethodInfo) != null)
- return method1 == method2;
- else if ((constructor1 = left as ConstructorInfo) != null && (constructor2 = right as ConstructorInfo) != null)
- return constructor1 == constructor2;
-
- return false;
- }
-
- public static bool operator !=(MethodBase left, MethodBase right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- #region Internal Members
- // used by EE
- private IntPtr GetMethodDesc() { return MethodHandle.Value; }
-
-#if FEATURE_APPX
-#endif
- #endregion
-
- #region Public Abstract\Virtual Members
- internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters (); }
-
- [System.Diagnostics.Contracts.Pure]
- public abstract ParameterInfo[] GetParameters();
-
- public virtual MethodImplAttributes MethodImplementationFlags
- {
- get
- {
- return GetMethodImplementationFlags();
- }
- }
-
- public abstract MethodImplAttributes GetMethodImplementationFlags();
-
- public abstract RuntimeMethodHandle MethodHandle { get; }
-
- public abstract MethodAttributes Attributes { get; }
-
- public abstract Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
-
- public virtual CallingConventions CallingConvention { get { return CallingConventions.Standard; } }
-
- public virtual Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
-
- public virtual bool IsGenericMethodDefinition { get { return false; } }
-
- public virtual bool ContainsGenericParameters { get { return false; } }
-
- public virtual bool IsGenericMethod { get { return false; } }
-
- public virtual bool IsSecurityCritical { get { throw new NotImplementedException(); } }
-
- public virtual bool IsSecuritySafeCritical { get { throw new NotImplementedException(); } }
-
- public virtual bool IsSecurityTransparent { get { throw new NotImplementedException(); } }
-
- #endregion
-
- #region Public Members
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public Object Invoke(Object obj, Object[] parameters)
- {
- // Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
- // But to maintain backward compatibility we can't switch to calling an
- // internal overload that takes a stack mark.
- // Fortunately the stack walker skips all the reflection invocation frames including this one.
- // So this method will never be returned by the stack walker as the caller.
- // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
- return Invoke(obj, BindingFlags.Default, null, parameters, null);
- }
-
- public bool IsPublic { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } }
-
- public bool IsPrivate { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } }
-
- public bool IsFamily { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } }
-
- public bool IsAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } }
-
- public bool IsFamilyAndAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } }
-
- public bool IsFamilyOrAssembly { get {return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } }
-
- public bool IsStatic { get { return(Attributes & MethodAttributes.Static) != 0; } }
-
- public bool IsFinal { get { return(Attributes & MethodAttributes.Final) != 0; }
- }
- public bool IsVirtual { get { return(Attributes & MethodAttributes.Virtual) != 0; }
- }
- public bool IsHideBySig { get { return(Attributes & MethodAttributes.HideBySig) != 0; } }
-
- public bool IsAbstract { get { return(Attributes & MethodAttributes.Abstract) != 0; } }
-
- public bool IsSpecialName { get { return(Attributes & MethodAttributes.SpecialName) != 0; } }
-
- public bool IsConstructor
- {
- get
- {
- // To be backward compatible we only return true for instance RTSpecialName ctors.
- return (this is ConstructorInfo &&
- !IsStatic &&
- ((Attributes & MethodAttributes.RTSpecialName) == MethodAttributes.RTSpecialName));
- }
- }
-
- public virtual MethodBody GetMethodBody()
- {
- throw new InvalidOperationException();
- }
- #endregion
-
- #region Internal Methods
- // helper method to construct the string representation of the parameter list
-
- internal static string ConstructParameters(Type[] parameterTypes, CallingConventions callingConvention, bool serialization)
- {
- StringBuilder sbParamList = new StringBuilder();
- string comma = "";
-
- for (int i = 0; i < parameterTypes.Length; i++)
- {
- Type t = parameterTypes[i];
-
- sbParamList.Append(comma);
-
- string typeName = t.FormatTypeName(serialization);
-
- // Legacy: Why use "ByRef" for by ref parameters? What language is this?
- // VB uses "ByRef" but it should precede (not follow) the parameter name.
- // Why don't we just use "&"?
- if (t.IsByRef && !serialization)
- {
- sbParamList.Append(typeName.TrimEnd('&'));
- sbParamList.Append(" ByRef");
- }
- else
- {
- sbParamList.Append(typeName);
- }
-
- comma = ", ";
- }
-
- if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
- {
- sbParamList.Append(comma);
- sbParamList.Append("...");
- }
-
- return sbParamList.ToString();
- }
-
- internal string FullName
- {
- get
- {
- return String.Format("{0}.{1}", DeclaringType.FullName, FormatNameAndSig());
- }
- }
- internal string FormatNameAndSig()
- {
- return FormatNameAndSig(false);
- }
-
- internal virtual string FormatNameAndSig(bool serialization)
- {
- // Serialization uses ToString to resolve MethodInfo overloads.
- StringBuilder sbName = new StringBuilder(Name);
-
- sbName.Append("(");
- sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization));
- sbName.Append(")");
-
- return sbName.ToString();
- }
-
- internal virtual Type[] GetParameterTypes()
- {
- ParameterInfo[] paramInfo = GetParametersNoCopy();
-
- Type[] parameterTypes = new Type[paramInfo.Length];
- for (int i = 0; i < paramInfo.Length; i++)
- parameterTypes[i] = paramInfo[i].ParameterType;
-
- return parameterTypes;
- }
-
- internal Object[] CheckArguments(Object[] parameters, Binder binder,
- BindingFlags invokeAttr, CultureInfo culture, Signature sig)
- {
- // copy the arguments in a different array so we detach from any user changes
- Object[] copyOfParameters = new Object[parameters.Length];
-
- ParameterInfo[] p = null;
- for (int i = 0; i < parameters.Length; i++)
- {
- Object arg = parameters[i];
- RuntimeType argRT = sig.Arguments[i];
-
- if (arg == Type.Missing)
- {
- if (p == null)
- p = GetParametersNoCopy();
- if (p[i].DefaultValue == System.DBNull.Value)
- throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),nameof(parameters));
- arg = p[i].DefaultValue;
- }
- copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr);
- }
-
- return copyOfParameters;
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs
index 7cbaeaf9b9..4335177efb 100644
--- a/src/mscorlib/src/System/Reflection/MethodBody.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBody.cs
@@ -2,116 +2,17 @@
// 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.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
namespace System.Reflection
-{
- [Flags()]
- public enum ExceptionHandlingClauseOptions: int
- {
- Clause = 0x0,
- Filter = 0x1,
- Finally = 0x2,
- Fault = 0x4,
- }
-
- public class ExceptionHandlingClause
- {
- #region costructor
- // This class can only be created from inside the EE.
- protected ExceptionHandlingClause() { }
- #endregion
-
- #region Private Data Members
- private MethodBody m_methodBody;
- [ContractPublicPropertyName("Flags")]
- private ExceptionHandlingClauseOptions m_flags;
- private int m_tryOffset;
- private int m_tryLength;
- private int m_handlerOffset;
- private int m_handlerLength;
- private int m_catchMetadataToken;
- private int m_filterOffset;
- #endregion
-
- #region Public Members
- public virtual ExceptionHandlingClauseOptions Flags { get { return m_flags; } }
- public virtual int TryOffset { get { return m_tryOffset; } }
- public virtual int TryLength { get { return m_tryLength; } }
- public virtual int HandlerOffset { get { return m_handlerOffset; } }
- public virtual int HandlerLength { get { return m_handlerLength; } }
-
- public virtual int FilterOffset
- {
- get
- {
- if (m_flags != ExceptionHandlingClauseOptions.Filter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_EHClauseNotFilter"));
-
- return m_filterOffset;
- }
- }
-
- public virtual Type CatchType
- {
- get
- {
- if (m_flags != ExceptionHandlingClauseOptions.Clause)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_EHClauseNotClause"));
-
- Type type = null;
-
- if (!MetadataToken.IsNullToken(m_catchMetadataToken))
- {
- Type declaringType = m_methodBody.m_methodBase.DeclaringType;
- Module module = (declaringType == null) ? m_methodBody.m_methodBase.Module : declaringType.Module;
- type = module.ResolveType(m_catchMetadataToken, (declaringType == null) ? null : declaringType.GetGenericArguments(),
- m_methodBody.m_methodBase is MethodInfo ? m_methodBody.m_methodBase.GetGenericArguments() : null);
- }
-
- return type;
- }
- }
- #endregion
-
- #region Object Overrides
- public override string ToString()
- {
- if (Flags == ExceptionHandlingClauseOptions.Clause)
- {
- return String.Format(CultureInfo.CurrentUICulture,
- "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, CatchType={5}",
- Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, CatchType);
- }
-
- if (Flags == ExceptionHandlingClauseOptions.Filter)
- {
- return String.Format(CultureInfo.CurrentUICulture,
- "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, FilterOffset={5}",
- Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, FilterOffset);
- }
-
- return String.Format(CultureInfo.CurrentUICulture,
- "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}",
- Flags, TryOffset, TryLength, HandlerOffset, HandlerLength);
-
- }
- #endregion
- }
-
+{
public class MethodBody
{
#region costructor
// This class can only be created from inside the EE.
protected MethodBody() { }
#endregion
-
+
#region Private Data Members
private byte[] m_IL;
private ExceptionHandlingClause[] m_exceptionHandlingClauses;
@@ -119,7 +20,7 @@ namespace System.Reflection
internal MethodBase m_methodBase;
private int m_localSignatureMetadataToken;
private int m_maxStackSize;
- private bool m_initLocals;
+ private bool m_initLocals;
#endregion
#region Public Members
@@ -130,37 +31,6 @@ namespace System.Reflection
public virtual byte[] GetILAsByteArray() { return m_IL; }
public virtual IList<ExceptionHandlingClause> ExceptionHandlingClauses { get { return Array.AsReadOnly(m_exceptionHandlingClauses); } }
#endregion
- }
-
- public class LocalVariableInfo
- {
- #region Private Data Members
- private RuntimeType m_type;
- private int m_isPinned;
- private int m_localIndex;
- #endregion
-
- #region Constructor
- protected LocalVariableInfo() { }
- #endregion
-
- #region Object Overrides
- public override string ToString()
- {
- string toString = LocalType.ToString() + " (" + LocalIndex + ")";
-
- if (IsPinned)
- toString += " (pinned)";
-
- return toString;
- }
- #endregion
-
- #region Public Members
- public virtual Type LocalType { get { Debug.Assert(m_type != null, "type must be set!"); return m_type; } }
- public virtual bool IsPinned { get { return m_isPinned != 0; } }
- public virtual int LocalIndex { get { return m_localIndex; } }
- #endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs b/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
deleted file mode 100644
index 1bd6b9dbd1..0000000000
--- a/src/mscorlib/src/System/Reflection/MethodImplAttributes.cs
+++ /dev/null
@@ -1,43 +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.
-
-//
-
-namespace System.Reflection
-{
-
- using System;
- // This Enum matchs the CorMethodImpl defined in CorHdr.h
- [Serializable]
- public enum MethodImplAttributes
- {
- // code impl mask
- CodeTypeMask = 0x0003, // Flags about code type.
- IL = 0x0000, // Method impl is IL.
- Native = 0x0001, // Method impl is native.
- /// <internalonly/>
- OPTIL = 0x0002, // Method impl is OPTIL
- Runtime = 0x0003, // Method impl is provided by the runtime.
- // end code impl mask
-
- // managed mask
- ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged.
- Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed.
- Managed = 0x0000, // Method impl is managed.
- // end managed mask
-
- // implementation info and interop
- ForwardRef = 0x0010, // Indicates method is not defined; used primarily in merge scenarios.
- PreserveSig = 0x0080, // Indicates method sig is exported exactly as declared.
-
- InternalCall = 0x1000, // Internal Call...
-
- Synchronized = 0x0020, // Method is single threaded through the body.
- NoInlining = 0x0008, // Method may not be inlined.
- AggressiveInlining = 0x0100, // Method should be inlined if possible.
- NoOptimization = 0x0040, // Method may not be optimized.
-
- MaxMethodImplVal = 0xFFFF, // Range check value
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Missing.cs b/src/mscorlib/src/System/Reflection/Missing.cs
deleted file mode 100644
index f62c5b538c..0000000000
--- a/src/mscorlib/src/System/Reflection/Missing.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.
-
-//
-
-namespace System.Reflection
-{
- using System;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
-
- // This is not serializable because it is a reflection command.
- [Serializable]
- public sealed class Missing : ISerializable
- {
- public static readonly Missing Value = new Missing();
-
- #region Constructor
- private Missing() { }
- #endregion
-
- #region ISerializable
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- UnitySerializationHolder.GetUnitySerializationInfo(info, this);
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Module.cs b/src/mscorlib/src/System/Reflection/Module.cs
deleted file mode 100644
index bdf95fca26..0000000000
--- a/src/mscorlib/src/System/Reflection/Module.cs
+++ /dev/null
@@ -1,1120 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-//
-
-namespace System.Reflection
-{
- using System;
- using System.Diagnostics.SymbolStore;
- using System.Runtime.Remoting;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Collections;
- using System.Collections.Generic;
- using System.Threading;
- using System.Runtime.CompilerServices;
- using System.Security;
- using System.IO;
- using System.Globalization;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- [Flags]
- public enum PortableExecutableKinds
- {
- NotAPortableExecutableImage = 0x0,
-
- ILOnly = 0x1,
-
- Required32Bit = 0x2,
-
- PE32Plus = 0x4,
-
- Unmanaged32Bit = 0x8,
-
- Preferred32Bit = 0x10,
- }
-
- [Serializable]
- public enum ImageFileMachine
- {
- I386 = 0x014c,
-
- IA64 = 0x0200,
-
- AMD64 = 0x8664,
-
- ARM = 0x01c4,
- }
-
- [Serializable]
- public abstract class Module : ISerializable, ICustomAttributeProvider
- {
- #region Static Constructor
- static Module()
- {
- __Filters _fltObj;
- _fltObj = new __Filters();
- FilterTypeName = new TypeFilter(_fltObj.FilterTypeName);
- FilterTypeNameIgnoreCase = new TypeFilter(_fltObj.FilterTypeNameIgnoreCase);
- }
- #endregion
-
- #region Constructor
- protected Module()
- {
- }
- #endregion
-
- #region Public Statics
- public static readonly TypeFilter FilterTypeName;
- public static readonly TypeFilter FilterTypeNameIgnoreCase;
-
- public static bool operator ==(Module left, Module right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimeModule || right is RuntimeModule)
- {
- return false;
- }
-
- return left.Equals(right);
- }
-
- public static bool operator !=(Module left, Module right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object o)
- {
- return base.Equals(o);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
- #endregion
-
- #region Literals
- private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
- #endregion
-
- #region object overrides
- public override String ToString()
- {
- return ScopeName;
- }
- #endregion
-
- public virtual IEnumerable<CustomAttributeData> CustomAttributes
- {
- get
- {
- return GetCustomAttributesData();
- }
- }
- #region ICustomAttributeProvider Members
- public virtual Object[] GetCustomAttributes(bool inherit)
- {
- throw new NotImplementedException();
- }
-
- public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- throw new NotImplementedException();
- }
-
- public virtual bool IsDefined(Type attributeType, bool inherit)
- {
- throw new NotImplementedException();
- }
-
- public virtual IList<CustomAttributeData> GetCustomAttributesData()
- {
- throw new NotImplementedException();
- }
- #endregion
-
- #region public instances members
- public MethodBase ResolveMethod(int metadataToken)
- {
- return ResolveMethod(metadataToken, null, null);
- }
-
- public virtual MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
-
- throw new NotImplementedException();
- }
-
- public FieldInfo ResolveField(int metadataToken)
- {
- return ResolveField(metadataToken, null, null);
- }
-
- public virtual FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
-
- throw new NotImplementedException();
- }
-
- public Type ResolveType(int metadataToken)
- {
- return ResolveType(metadataToken, null, null);
- }
-
- public virtual Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
-
- throw new NotImplementedException();
- }
-
- public MemberInfo ResolveMember(int metadataToken)
- {
- return ResolveMember(metadataToken, null, null);
- }
-
- public virtual MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments);
-
- throw new NotImplementedException();
- }
-
- public virtual byte[] ResolveSignature(int metadataToken)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ResolveSignature(metadataToken);
-
- throw new NotImplementedException();
- }
-
- public virtual string ResolveString(int metadataToken)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ResolveString(metadataToken);
-
- throw new NotImplementedException();
- }
-
- public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- rtModule.GetPEKind(out peKind, out machine);
-
- throw new NotImplementedException();
- }
-
- public virtual int MDStreamVersion
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.MDStreamVersion;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotImplementedException();
- }
-
- public virtual Type GetType(String className, bool ignoreCase)
- {
- return GetType(className, false, ignoreCase);
- }
-
- public virtual Type GetType(String className) {
- return GetType(className, false, false);
- }
-
- public virtual Type GetType(String className, bool throwOnError, bool ignoreCase)
- {
- throw new NotImplementedException();
- }
-
- public virtual String FullyQualifiedName
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual Type[] FindTypes(TypeFilter filter,Object filterCriteria)
- {
- Type[] c = GetTypes();
- int cnt = 0;
- for (int i = 0;i<c.Length;i++) {
- if (filter!=null && !filter(c[i],filterCriteria))
- c[i] = null;
- else
- cnt++;
- }
- if (cnt == c.Length)
- return c;
-
- Type[] ret = new Type[cnt];
- cnt=0;
- for (int i=0;i<c.Length;i++) {
- if (c[i] != null)
- ret[cnt++] = c[i];
- }
- return ret;
- }
-
- public virtual Type[] GetTypes()
- {
- throw new NotImplementedException();
- }
-
- public virtual Guid ModuleVersionId
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ModuleVersionId;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual int MetadataToken
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.MetadataToken;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual bool IsResource()
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.IsResource();
-
- throw new NotImplementedException();
- }
-
- public FieldInfo[] GetFields()
- {
- return GetFields(Module.DefaultLookup);
- }
-
- public virtual FieldInfo[] GetFields(BindingFlags bindingFlags)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.GetFields(bindingFlags);
-
- throw new NotImplementedException();
- }
-
- public FieldInfo GetField(String name)
- {
- return GetField(name,Module.DefaultLookup);
- }
-
- public virtual FieldInfo GetField(String name, BindingFlags bindingAttr)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.GetField(name, bindingAttr);
-
- throw new NotImplementedException();
- }
-
- public MethodInfo[] GetMethods()
- {
- return GetMethods(Module.DefaultLookup);
- }
-
- public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags)
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.GetMethods(bindingFlags);
-
- throw new NotImplementedException();
- }
-
- public MethodInfo GetMethod(
- String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
-
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
-
- for (int i = 0; i < types.Length; i++)
- {
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- }
-
- return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
- }
-
- public MethodInfo GetMethod(String name, Type[] types)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
-
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
-
- for (int i = 0; i < types.Length; i++)
- {
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- }
-
- return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any, types, null);
- }
-
- public MethodInfo GetMethod(String name)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
-
- return GetMethodImpl(name, Module.DefaultLookup, null, CallingConventions.Any,
- null, null);
- }
-
- protected virtual MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
- {
- throw new NotImplementedException();
- }
-
- public virtual String ScopeName
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.ScopeName;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual String Name
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.Name;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual Assembly Assembly
- {
- [Pure]
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeModule rtModule = this as RuntimeModule;
- if (rtModule != null)
- return rtModule.Assembly;
-
- throw new NotImplementedException();
- }
- }
-
- // This API never fails, it will return an empty handle for non-runtime handles and
- // a valid handle for reflection only modules.
- public ModuleHandle ModuleHandle
- {
- get
- {
- return GetModuleHandle();
- }
- }
-
- // Used to provide implementation and overriding point for ModuleHandle.
- // To get a module handle inside mscorlib, use GetNativeHandle instead.
- internal virtual ModuleHandle GetModuleHandle()
- {
- return ModuleHandle.EmptyHandle;
- }
- #endregion
- }
-
- [Serializable]
- internal class RuntimeModule : Module
- {
- internal RuntimeModule() { throw new NotSupportedException(); }
-
- #region FCalls
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void GetType(RuntimeModule module, String className, bool ignoreCase, bool throwOnError, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
-
- [DllImport(JitHelpers.QCall)]
- [SuppressUnmanagedCodeSecurity]
- private static extern bool nIsTransientInternal(RuntimeModule module);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
-
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
- private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern static RuntimeType[] GetTypes(RuntimeModule module);
-
- internal RuntimeType[] GetDefinedTypes()
- {
- return GetTypes(GetNativeHandle());
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern static bool IsResource(RuntimeModule module);
- #endregion
-
- #region Module overrides
- private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
- {
- if (genericArguments == null)
- return null;
-
- int size = genericArguments.Length;
- RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
- for (int i = 0; i < size; i++)
- {
- Type typeArg = genericArguments[i];
- if (typeArg == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
- typeArg = typeArg.UnderlyingSystemType;
- if (typeArg == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
- if (!(typeArg is RuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidGenericInstArray"));
- typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
- }
- return typeHandleArgs;
- }
-
- public override byte[] ResolveSignature(int metadataToken)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
-
- if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- Environment.GetResourceString("Argument_InvalidToken", tk, this));
-
- if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidToken", tk, this),
- nameof(metadataToken));
-
- ConstArray signature;
- if (tk.IsMemberRef)
- signature = MetadataImport.GetMemberRefProps(metadataToken);
- else
- signature = MetadataImport.GetSignatureFromToken(metadataToken);
-
- byte[] sig = new byte[signature.Length];
-
- for (int i = 0; i < signature.Length; i++)
- sig[i] = signature[i];
-
- return sig;
- }
-
- public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
-
- if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- Environment.GetResourceString("Argument_InvalidToken", tk, this));
-
- RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
- RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
-
- try
- {
- if (!tk.IsMethodDef && !tk.IsMethodSpec)
- {
- if (!tk.IsMemberRef)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
- nameof(metadataToken));
-
- unsafe
- {
- ConstArray sig = MetadataImport.GetMemberRefProps(tk);
-
- if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMethod", tk, this),
- nameof(metadataToken));
- }
- }
-
- IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
- Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
-
- if (declaringType.IsGenericType || declaringType.IsArray)
- {
- MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
-
- if (tk.IsMethodSpec)
- tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
-
- declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
- }
-
- return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);
- }
- catch (BadImageFormatException e)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
- }
- }
-
- private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
-
- if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
-
- int tkDeclaringType;
- string fieldName;
-
- fieldName = MetadataImport.GetName(tk).ToString();
- tkDeclaringType = MetadataImport.GetParentToken(tk);
-
- Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
-
- declaringType.GetFields();
-
- try
- {
- return declaringType.GetField(fieldName,
- BindingFlags.Static | BindingFlags.Instance |
- BindingFlags.Public | BindingFlags.NonPublic |
- BindingFlags.DeclaredOnly);
- }
- catch
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this), nameof(metadataToken));
- }
- }
-
- public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
-
- if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- Environment.GetResourceString("Argument_InvalidToken", tk, this));
-
- RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
- RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
-
- try
- {
- IRuntimeFieldInfo fieldHandle = null;
-
- if (!tk.IsFieldDef)
- {
- if (!tk.IsMemberRef)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
- nameof(metadataToken));
-
- unsafe
- {
- ConstArray sig = MetadataImport.GetMemberRefProps(tk);
-
- if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveField", tk, this),
- nameof(metadataToken));
- }
-
- fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
- }
-
- fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
- RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
-
- if (declaringType.IsGenericType || declaringType.IsArray)
- {
- int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
- declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
- }
-
- return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
- }
- catch(MissingFieldException)
- {
- return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
- }
- catch (BadImageFormatException e)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
- }
- }
-
- public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
-
- if (tk.IsGlobalTypeDefToken)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveModuleType", tk), nameof(metadataToken));
-
- if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- Environment.GetResourceString("Argument_InvalidToken", tk, this));
-
- if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));
-
- RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
- RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
-
- try
- {
- Type t = GetModuleHandle().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
-
- if (t == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveType", tk, this), nameof(metadataToken));
-
- return t;
- }
- catch (BadImageFormatException e)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_BadImageFormatExceptionResolve"), e);
- }
- }
-
- public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
-
- if (tk.IsProperty)
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_PropertyInfoNotAvailable"));
-
- if (tk.IsEvent)
- throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EventInfoNotAvailable"));
-
- if (tk.IsMethodSpec || tk.IsMethodDef)
- return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
-
- if (tk.IsFieldDef)
- return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
-
- if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
- return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
-
- if (tk.IsMemberRef)
- {
- if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- Environment.GetResourceString("Argument_InvalidToken", tk, this));
-
- ConstArray sig = MetadataImport.GetMemberRefProps(tk);
-
- unsafe
- {
- if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
- {
- return ResolveField(tk, genericTypeArguments, genericMethodArguments);
- }
- else
- {
- return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
- }
- }
- }
-
- throw new ArgumentException(Environment.GetResourceString("Argument_ResolveMember", tk, this),
- nameof(metadataToken));
- }
-
- public override string ResolveString(int metadataToken)
- {
- MetadataToken tk = new MetadataToken(metadataToken);
- if (!tk.IsString)
- throw new ArgumentException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
-
- if (!MetadataImport.IsValidToken(tk))
- throw new ArgumentOutOfRangeException(nameof(metadataToken),
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_InvalidToken", tk, this)));
-
- string str = MetadataImport.GetUserString(metadataToken);
-
- if (str == null)
- throw new ArgumentException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Argument_ResolveString"), metadataToken, ToString()));
-
- return str;
- }
-
- public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
- {
- ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
- }
-
- public override int MDStreamVersion
- {
- get
- {
- return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
- }
- }
- #endregion
-
- #region Data Members
- #pragma warning disable 169
- // If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
- private RuntimeType m_runtimeType;
- private RuntimeAssembly m_runtimeAssembly;
- private IntPtr m_pRefClass;
- private IntPtr m_pData;
- private IntPtr m_pGlobals;
- private IntPtr m_pFields;
-#pragma warning restore 169
- #endregion
-
- #region Protected Virtuals
- protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
- {
- return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
- }
-
- internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder,
- CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
- {
- if (RuntimeType == null)
- return null;
-
- if (types == null)
- {
- return RuntimeType.GetMethod(name, bindingAttr);
- }
- else
- {
- return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
- }
- }
- #endregion
-
- #region Internal Members
- internal RuntimeType RuntimeType
- {
- get
- {
- if (m_runtimeType == null)
- m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle());
-
- return m_runtimeType;
- }
- }
-
- internal bool IsTransientInternal()
- {
- return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
- }
-
- internal MetadataImport MetadataImport
- {
- get
- {
- unsafe
- {
- return ModuleHandle.GetMetadataImport(GetNativeHandle());
- }
- }
- }
- #endregion
-
- #region ICustomAttributeProvider Members
- public override Object[] GetCustomAttributes(bool inherit)
- {
- return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
- }
-
- public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
-
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
-
- return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
- }
-
- public override bool IsDefined(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
-
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
-
- return CustomAttribute.IsDefined(this, attributeRuntimeType);
- }
-
- public override IList<CustomAttributeData> GetCustomAttributesData()
- {
- return CustomAttributeData.GetCustomAttributesInternal(this);
- }
- #endregion
-
- #region Public Virtuals
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
- }
-
- public override Type GetType(String className, bool throwOnError, bool ignoreCase)
- {
- // throw on null strings regardless of the value of "throwOnError"
- if (className == null)
- throw new ArgumentNullException(nameof(className));
-
- RuntimeType retType = null;
- Object keepAlive = null;
- GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
- GC.KeepAlive(keepAlive);
- return retType;
- }
-
- internal string GetFullyQualifiedName()
- {
- String fullyQualifiedName = null;
- GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
- return fullyQualifiedName;
- }
-
- public override String FullyQualifiedName
- {
- get
- {
- return GetFullyQualifiedName();
- }
- }
-
- public override Type[] GetTypes()
- {
- return GetTypes(GetNativeHandle());
- }
-
- #endregion
-
- #region Public Members
-
- public override Guid ModuleVersionId
- {
- get
- {
- unsafe
- {
- Guid mvid;
- MetadataImport.GetScopeProps(out mvid);
- return mvid;
- }
- }
- }
-
- public override int MetadataToken
- {
- get
- {
- return ModuleHandle.GetToken(GetNativeHandle());
- }
- }
-
- public override bool IsResource()
- {
- return IsResource(GetNativeHandle());
- }
-
- public override FieldInfo[] GetFields(BindingFlags bindingFlags)
- {
- if (RuntimeType == null)
- return new FieldInfo[0];
-
- return RuntimeType.GetFields(bindingFlags);
- }
-
- public override FieldInfo GetField(String name, BindingFlags bindingAttr)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
-
- if (RuntimeType == null)
- return null;
-
- return RuntimeType.GetField(name, bindingAttr);
- }
-
- public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
- {
- if (RuntimeType == null)
- return new MethodInfo[0];
-
- return RuntimeType.GetMethods(bindingFlags);
- }
-
- public override String ScopeName
- {
- get
- {
- string scopeName = null;
- GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName));
- return scopeName;
- }
- }
-
- public override String Name
- {
- get
- {
- String s = GetFullyQualifiedName();
-
-#if !FEATURE_PAL
- int i = s.LastIndexOf('\\');
-#else
- int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
-#endif
- if (i == -1)
- return s;
-
- return s.Substring(i + 1);
- }
- }
-
- public override Assembly Assembly
- {
- [Pure]
- get
- {
- return GetRuntimeAssembly();
- }
- }
-
- internal RuntimeAssembly GetRuntimeAssembly()
- {
- return m_runtimeAssembly;
- }
-
-
- internal override ModuleHandle GetModuleHandle()
- {
- return new ModuleHandle(this);
- }
-
- internal RuntimeModule GetNativeHandle()
- {
- return this;
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs b/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
deleted file mode 100644
index 787f37bced..0000000000
--- a/src/mscorlib/src/System/Reflection/ObfuscateAssemblyAttribute.cs
+++ /dev/null
@@ -1,45 +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.Reflection
-{
- [AttributeUsage (AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
- public sealed class ObfuscateAssemblyAttribute : Attribute
- {
- private bool m_assemblyIsPrivate;
- private bool m_strip = true;
-
- public ObfuscateAssemblyAttribute(bool assemblyIsPrivate)
- {
- m_assemblyIsPrivate = assemblyIsPrivate;
- }
-
- public bool AssemblyIsPrivate
- {
- get
- {
- return m_assemblyIsPrivate;
- }
- }
-
- public bool StripAfterObfuscation
- {
- get
- {
- return m_strip;
- }
- set
- {
- m_strip = value;
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs b/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
deleted file mode 100644
index c7c7c18550..0000000000
--- a/src/mscorlib/src/System/Reflection/ObfuscationAttribute.cs
+++ /dev/null
@@ -1,74 +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.Reflection
-{
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Delegate,
- AllowMultiple = true, Inherited = false)]
- public sealed class ObfuscationAttribute: Attribute
- {
- private bool m_strip = true;
- private bool m_exclude = true;
- private bool m_applyToMembers = true;
- private string m_feature = "all";
-
- public ObfuscationAttribute()
- {
- }
-
- public bool StripAfterObfuscation
- {
- get
- {
- return m_strip;
- }
- set
- {
- m_strip = value;
- }
- }
-
- public bool Exclude
- {
- get
- {
- return m_exclude;
- }
- set
- {
- m_exclude = value;
- }
- }
-
- public bool ApplyToMembers
- {
- get
- {
- return m_applyToMembers;
- }
- set
- {
- m_applyToMembers = value;
- }
- }
-
- public string Feature
- {
- get
- {
- return m_feature;
- }
- set
- {
- m_feature = value;
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Reflection/ParameterAttributes.cs b/src/mscorlib/src/System/Reflection/ParameterAttributes.cs
deleted file mode 100644
index acae3a6ec1..0000000000
--- a/src/mscorlib/src/System/Reflection/ParameterAttributes.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// ParameterAttributes is an enum defining the attributes that may be
-//
-// associated with a Parameter. These are defined in CorHdr.h.
-//
-//
-namespace System.Reflection {
-
- using System;
- // This Enum matchs the CorParamAttr defined in CorHdr.h
-[Serializable]
- [Flags]
- public enum ParameterAttributes
- {
- None = 0x0000, // no flag is specified
- In = 0x0001, // Param is [In]
- Out = 0x0002, // Param is [Out]
- Lcid = 0x0004, // Param is [lcid]
- Retval = 0x0008, // Param is [Retval]
- Optional = 0x0010, // Param is optional
-
- // Reserved flags for Runtime use only.
- ReservedMask = 0xf000,
- HasDefault = 0x1000, // Param has default value.
- HasFieldMarshal = 0x2000, // Param has FieldMarshal.
- Reserved3 = 0x4000, // reserved bit
- Reserved4 = 0x8000 // reserved bit
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/ParameterModifier.cs b/src/mscorlib/src/System/Reflection/ParameterModifier.cs
deleted file mode 100644
index a2bfeab934..0000000000
--- a/src/mscorlib/src/System/Reflection/ParameterModifier.cs
+++ /dev/null
@@ -1,45 +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.Diagnostics.Contracts;
-namespace System.Reflection
-{
- using System;
-
- [Serializable]
- public struct ParameterModifier
- {
- #region Private Data Members
- private bool[] _byRef;
- #endregion
-
- #region Constructor
- public ParameterModifier(int parameterCount)
- {
- if (parameterCount <= 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_ParmArraySize"));
- Contract.EndContractBlock();
-
- _byRef = new bool[parameterCount];
- }
- #endregion
-
- #region Internal Members
- internal bool[] IsByRefArray { get { return _byRef; } }
- #endregion
-
- #region Public Members
- public bool this[int index]
- {
- get
- {
- return _byRef[index];
- }
- set
- {
- _byRef[index] = value;
- }
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/Pointer.cs b/src/mscorlib/src/System/Reflection/Pointer.cs
deleted file mode 100644
index 9f1a38366a..0000000000
--- a/src/mscorlib/src/System/Reflection/Pointer.cs
+++ /dev/null
@@ -1,75 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-//
-// This is a wrapper class for Pointers
-//
-//
-//
-//
-//
-namespace System.Reflection {
- using System;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Diagnostics.Contracts;
-
- [CLSCompliant(false)]
- [Serializable]
- public sealed class Pointer : ISerializable
- {
- unsafe private void* _ptr;
- private RuntimeType _ptrType;
-
- private Pointer() {}
-
- private unsafe Pointer(SerializationInfo info, StreamingContext context)
- {
- _ptr = ((IntPtr)(info.GetValue("_ptr", typeof(IntPtr)))).ToPointer();
- _ptrType = (RuntimeType)info.GetValue("_ptrType", typeof(RuntimeType));
- }
-
- // This method will box an pointer. We save both the
- // value and the type so we can access it from the native code
- // during an Invoke.
- public static unsafe Object Box(void *ptr,Type type) {
- if (type == null)
- throw new ArgumentNullException(nameof(type));
- if (!type.IsPointer)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
- Contract.EndContractBlock();
-
- RuntimeType rt = type as RuntimeType;
- if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"), nameof(ptr));
-
- Pointer x = new Pointer();
- x._ptr = ptr;
- x._ptrType = rt;
- return x;
- }
-
- // Returned the stored pointer.
- public static unsafe void* Unbox(Object ptr) {
- if (!(ptr is Pointer))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBePointer"),nameof(ptr));
- return ((Pointer)ptr)._ptr;
- }
-
- internal RuntimeType GetPointerType() {
- return _ptrType;
- }
-
- internal unsafe Object GetPointerValue() {
- return (IntPtr)_ptr;
- }
-
- unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
- info.AddValue("_ptr", new IntPtr(_ptr));
- info.AddValue("_ptrType", _ptrType);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/PropertyAttributes.cs b/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
deleted file mode 100644
index 4a5617ba5e..0000000000
--- a/src/mscorlib/src/System/Reflection/PropertyAttributes.cs
+++ /dev/null
@@ -1,32 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// PropertyAttributes is an enum which defines the attributes that may be associated
-//
-// with a property. The values here are defined in Corhdr.h.
-//
-//
-namespace System.Reflection {
-
- using System;
- // This Enum matchs the CorPropertyAttr defined in CorHdr.h
-[Serializable]
-[Flags]
- public enum PropertyAttributes
- {
- None = 0x0000,
- SpecialName = 0x0200, // property is special. Name describes how.
-
- // Reserved flags for Runtime use only.
- ReservedMask = 0xf400,
- RTSpecialName = 0x0400, // Runtime(metadata internal APIs) should check name encoding.
- HasDefault = 0x1000, // Property has default
- Reserved2 = 0x2000, // reserved bit
- Reserved3 = 0x4000, // reserved bit
- Reserved4 = 0x8000 // reserved bit
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/ReflectionContext.cs b/src/mscorlib/src/System/Reflection/ReflectionContext.cs
deleted file mode 100644
index 34f692166c..0000000000
--- a/src/mscorlib/src/System/Reflection/ReflectionContext.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: For Assembly-related stuff.
-**
-**
-=============================================================================*/
-
-namespace System.Reflection
-{
- using System;
-
- public abstract class ReflectionContext
- {
- protected ReflectionContext() { }
-
- public abstract Assembly MapAssembly(Assembly assembly);
-
- public abstract TypeInfo MapType(TypeInfo type);
-
- public virtual TypeInfo GetTypeForObject(object value)
- {
- if (value == null)
- throw new ArgumentNullException(nameof(value));
-
- return MapType(value.GetType().GetTypeInfo());
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
deleted file mode 100644
index cccf060645..0000000000
--- a/src/mscorlib/src/System/Reflection/ReflectionTypeLoadException.cs
+++ /dev/null
@@ -1,72 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// ReflectionTypeLoadException is thrown when multiple TypeLoadExceptions may occur.
-//
-// Specifically, when you call Module.GetTypes() this causes multiple class loads to occur.
-// If there are failures, we continue to load classes and build an array of the successfully
-// loaded classes. We also build an array of the errors that occur. Then we throw this exception
-// which exposes both the array of classes and the array of TypeLoadExceptions.
-//
-//
-//
-//
-namespace System.Reflection {
-
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
- [Serializable]
- public sealed class ReflectionTypeLoadException : SystemException, ISerializable {
- private Type[] _classes;
- private Exception[] _exceptions;
-
- // private constructor. This is not called.
- private ReflectionTypeLoadException()
- : base(Environment.GetResourceString("ReflectionTypeLoad_LoadFailed")) {
- SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
- }
-
- public ReflectionTypeLoadException(Type[] classes, Exception[] exceptions) : base(null)
- {
- _classes = classes;
- _exceptions = exceptions;
- SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
- }
-
- public ReflectionTypeLoadException(Type[] classes, Exception[] exceptions, String message) : base(message)
- {
- _classes = classes;
- _exceptions = exceptions;
- SetErrorCode(__HResults.COR_E_REFLECTIONTYPELOAD);
- }
-
- internal ReflectionTypeLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
- _classes = (Type[])(info.GetValue("Types", typeof(Type[])));
- _exceptions = (Exception[])(info.GetValue("Exceptions", typeof(Exception[])));
- }
-
- public Type[] Types {
- get {return _classes;}
- }
-
- public Exception[] LoaderExceptions {
- get {return _exceptions;}
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- base.GetObjectData(info, context);
- info.AddValue("Types", _classes, typeof(Type[]));
- info.AddValue("Exceptions", _exceptions, typeof(Exception[]));
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/ResourceAttributes.cs b/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
deleted file mode 100644
index 5c419ebb2d..0000000000
--- a/src/mscorlib/src/System/Reflection/ResourceAttributes.cs
+++ /dev/null
@@ -1,23 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// ResourceAttributes is an enum which defines the attributes that may be associated
-//
-// with a manifest resource. The values here are defined in Corhdr.h.
-//
-//
-namespace System.Reflection {
-
- using System;
-[Serializable]
-[Flags]
- public enum ResourceAttributes
- {
- Public = 0x0001,
- Private = 0x0002,
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
new file mode 100644
index 0000000000..20d6e6392f
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
@@ -0,0 +1,390 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Threading;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
+
+namespace System.Reflection
+{
+ [Serializable]
+ 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;
+ private FieldAttributes m_fieldAttributes;
+ // lazy caching
+ private string m_name;
+ private RuntimeType m_fieldType;
+ private INVOCATION_FLAGS m_invocationFlags;
+
+ internal INVOCATION_FLAGS InvocationFlags
+ {
+ get
+ {
+ if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
+ {
+ Type declaringType = DeclaringType;
+ bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType);
+
+ INVOCATION_FLAGS invocationFlags = 0;
+
+ // first take care of all the NO_INVOKE cases
+ if (
+ (declaringType != null && declaringType.ContainsGenericParameters) ||
+ (declaringType == null && Module.Assembly.ReflectionOnly) ||
+ (fIsReflectionOnlyType)
+ )
+ {
+ invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
+ }
+
+ // If the invocationFlags are still 0, then
+ // this should be an usable field, determine the other flags
+ if (invocationFlags == 0)
+ {
+ if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0)
+ invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
+
+ 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)
+ invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST;
+ }
+
+ // must be last to avoid threading problems
+ m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
+ }
+
+ return m_invocationFlags;
+ }
+ }
+ #endregion
+
+ private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); }
+
+ #region Constructor
+ internal RtFieldInfo(
+ RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags)
+ : base(reflectedTypeCache, declaringType, bindingFlags)
+ {
+ m_fieldHandle = handle.Value;
+ m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle);
+ }
+ #endregion
+
+ #region Private Members
+ RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
+ {
+ get
+ {
+ return new RuntimeFieldHandleInternal(m_fieldHandle);
+ }
+ }
+
+ #endregion
+
+ #region Internal Members
+ internal void CheckConsistency(Object target)
+ {
+ // only test instance fields
+ if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static)
+ {
+ if (!m_declaringType.IsInstanceOfType(target))
+ {
+ if (target == null)
+ {
+ throw new TargetException(SR.RFLCT_Targ_StatFldReqTarg);
+ }
+ else
+ {
+ throw new ArgumentException(
+ String.Format(CultureInfo.CurrentUICulture, SR.Arg_FieldDeclTarget,
+ Name, m_declaringType, target.GetType()));
+ }
+ }
+ }
+ }
+
+ internal override bool CacheEquals(object o)
+ {
+ RtFieldInfo m = o as RtFieldInfo;
+
+ if ((object)m == null)
+ return false;
+
+ return m.m_fieldHandle == m_fieldHandle;
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark)
+ {
+ INVOCATION_FLAGS invocationFlags = InvocationFlags;
+ RuntimeType declaringType = DeclaringType as RuntimeType;
+
+ if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
+ {
+ if (declaringType != null && declaringType.ContainsGenericParameters)
+ throw new InvalidOperationException(SR.Arg_UnboundGenField);
+
+ if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
+ throw new InvalidOperationException(SR.Arg_ReflectionOnlyField);
+
+ throw new FieldAccessException();
+ }
+
+ CheckConsistency(obj);
+
+ 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)
+ {
+ RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
+ }
+ else
+ {
+ domainInitialized = declaringType.DomainInitialized;
+ RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
+ declaringType.DomainInitialized = domainInitialized;
+ }
+ }
+
+ // UnsafeSetValue doesn't perform any consistency or visibility check.
+ // It is the caller's responsibility to ensure the operation is safe.
+ // When the caller needs to perform visibility checks they should call
+ // InternalSetValue() instead. When the caller needs to perform
+ // consistency checks they should call CheckConsistency() before
+ // calling this method.
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ {
+ RuntimeType declaringType = DeclaringType as RuntimeType;
+ RuntimeType fieldType = (RuntimeType)FieldType;
+ value = fieldType.CheckValue(value, binder, culture, invokeAttr);
+
+ bool domainInitialized = false;
+ if (declaringType == null)
+ {
+ RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized);
+ }
+ else
+ {
+ domainInitialized = declaringType.DomainInitialized;
+ RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized);
+ declaringType.DomainInitialized = domainInitialized;
+ }
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark)
+ {
+ INVOCATION_FLAGS invocationFlags = InvocationFlags;
+ RuntimeType declaringType = DeclaringType as RuntimeType;
+
+ if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
+ {
+ if (declaringType != null && DeclaringType.ContainsGenericParameters)
+ throw new InvalidOperationException(SR.Arg_UnboundGenField);
+
+ if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
+ throw new InvalidOperationException(SR.Arg_ReflectionOnlyField);
+
+ throw new FieldAccessException();
+ }
+
+ 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);
+ }
+
+ // UnsafeGetValue doesn't perform any consistency or visibility check.
+ // It is the caller's responsibility to ensure the operation is safe.
+ // When the caller needs to perform visibility checks they should call
+ // InternalGetValue() instead. When the caller needs to perform
+ // consistency checks they should call CheckConsistency() before
+ // calling this method.
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ internal Object UnsafeGetValue(Object obj)
+ {
+ RuntimeType declaringType = DeclaringType as RuntimeType;
+
+ RuntimeType fieldType = (RuntimeType)FieldType;
+
+ bool domainInitialized = false;
+ if (declaringType == null)
+ {
+ return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized);
+ }
+ else
+ {
+ domainInitialized = declaringType.DomainInitialized;
+ object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized);
+ declaringType.DomainInitialized = domainInitialized;
+ return retVal;
+ }
+ }
+
+ #endregion
+
+ #region MemberInfo Overrides
+ public override String Name
+ {
+ get
+ {
+ if (m_name == null)
+ m_name = RuntimeFieldHandle.GetName(this);
+
+ return m_name;
+ }
+ }
+
+ internal String FullName
+ {
+ get
+ {
+ return String.Format("{0}.{1}", DeclaringType.FullName, Name);
+ }
+ }
+
+ public override int MetadataToken
+ {
+ get { return RuntimeFieldHandle.GetToken(this); }
+ }
+
+ internal override RuntimeModule GetRuntimeModule()
+ {
+ return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this));
+ }
+
+ #endregion
+
+ #region FieldInfo Overrides
+ public override Object GetValue(Object obj)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return InternalGetValue(obj, ref stackMark);
+ }
+
+ public override object GetRawConstantValue() { throw new InvalidOperationException(); }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public override Object GetValueDirect(TypedReference obj)
+ {
+ if (obj.IsNull)
+ throw new ArgumentException(SR.Arg_TypedReference_Null);
+ Contract.EndContractBlock();
+
+ unsafe
+ {
+ // Passing TypedReference by reference is easier to make correct in native code
+ return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType);
+ }
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark);
+ }
+
+ [DebuggerStepThroughAttribute]
+ [Diagnostics.DebuggerHidden]
+ public override void SetValueDirect(TypedReference obj, Object value)
+ {
+ if (obj.IsNull)
+ throw new ArgumentException(SR.Arg_TypedReference_Null);
+ Contract.EndContractBlock();
+
+ unsafe
+ {
+ // Passing TypedReference by reference is easier to make correct in native code
+ RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType);
+ }
+ }
+
+ public override RuntimeFieldHandle FieldHandle
+ {
+ get
+ {
+ Type declaringType = DeclaringType;
+ if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
+ throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
+ return new RuntimeFieldHandle(this);
+ }
+ }
+
+ internal IntPtr GetFieldHandle()
+ {
+ return m_fieldHandle;
+ }
+
+ public override FieldAttributes Attributes
+ {
+ get
+ {
+ return m_fieldAttributes;
+ }
+ }
+
+ public override Type FieldType
+ {
+ get
+ {
+ if (m_fieldType == null)
+ m_fieldType = new Signature(this, m_declaringType).FieldType;
+
+ return m_fieldType;
+ }
+ }
+
+ public override Type[] GetRequiredCustomModifiers()
+ {
+ return new Signature(this, m_declaringType).GetCustomModifiers(1, true);
+ }
+
+ public override Type[] GetOptionalCustomModifiers()
+ {
+ return new Signature(this, m_declaringType).GetCustomModifiers(1, false);
+ }
+
+ #endregion
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/Assembly.cs b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
index eaedc6ded4..4632525453 100644
--- a/src/mscorlib/src/System/Reflection/Assembly.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
@@ -2,763 +2,22 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*=============================================================================
-**
-**
-**
-**
-**
-**
-** Purpose: For Assembly-related stuff.
-**
-**
-=============================================================================*/
-
-namespace System.Reflection
+using System.Collections.Generic;
+using CultureInfo = System.Globalization.CultureInfo;
+using System.Security;
+using System.Security.Policy;
+using System.IO;
+using StringBuilder = System.Text.StringBuilder;
+using System.Configuration.Assemblies;
+using StackCrawlMark = System.Threading.StackCrawlMark;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Threading;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection
{
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using CultureInfo = System.Globalization.CultureInfo;
- using System.Security;
- using System.Security.Policy;
- using System.IO;
- using StringBuilder = System.Text.StringBuilder;
- using System.Configuration.Assemblies;
- using StackCrawlMark = System.Threading.StackCrawlMark;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using Microsoft.Win32;
- using System.Threading;
- using __HResults = System.__HResults;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
- using System.Runtime.Loader;
-
- [Serializable]
- public delegate Module ModuleResolveEventHandler(Object sender, ResolveEventArgs e);
-
-
- [Serializable]
- public abstract class Assembly : ICustomAttributeProvider, ISerializable
- {
- protected Assembly() {}
-
-#region public static methods
-
- public static String CreateQualifiedName(String assemblyName, String typeName)
- {
- return typeName + ", " + assemblyName;
- }
-
- public static Assembly GetAssembly(Type type)
- {
- if (type == null)
- throw new ArgumentNullException(nameof(type));
- Contract.EndContractBlock();
-
- Module m = type.Module;
- if (m == null)
- return null;
- else
- return m.Assembly;
- }
-
- public static bool operator ==(Assembly left, Assembly right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimeAssembly || right is RuntimeAssembly)
- {
- return false;
- }
- return left.Equals(right);
- }
-
- public static bool operator !=(Assembly left, Assembly right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object o)
- {
- return base.Equals(o);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- public static Assembly LoadFrom(String assemblyFile)
- {
- if(assemblyFile == null)
- throw new ArgumentNullException(nameof(assemblyFile));
- string fullPath = Path.GetFullPath(assemblyFile);
- return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath);
- }
-
- // Locate an assembly for reflection by the name of the file containing the manifest.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly ReflectionOnlyLoadFrom(String assemblyFile)
- {
- if (assemblyFile == null)
- throw new ArgumentNullException(nameof(assemblyFile));
- if (assemblyFile.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyLoad"));
- }
-
- // Evidence is protected in Assembly.Load()
- [Obsolete("This method is obsolete and will be removed in a future release of the .NET Framework. Please use an overload of LoadFrom which does not take an Evidence parameter. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- internal static Assembly LoadFrom(String assemblyFile,
- Evidence securityEvidence)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- return RuntimeAssembly.InternalLoadFrom(
- assemblyFile,
- securityEvidence,
- null, // hashValue
- AssemblyHashAlgorithm.None,
- false,// forIntrospection);
- ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly LoadFrom(String assemblyFile,
- byte[] hashValue,
- AssemblyHashAlgorithm hashAlgorithm)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadFromHash"));
- }
-
- public static Assembly UnsafeLoadFrom(string assemblyFile)
- {
- return LoadFrom(assemblyFile);
- }
-
- // Locate an assembly by the long form of the assembly name.
- // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly Load(String assemblyString)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoad(assemblyString, null, ref stackMark, false /*forIntrospection*/);
- }
-
- // Returns type from the assembly while keeping compatibility with Assembly.Load(assemblyString).GetType(typeName) for managed types.
- // Calls Type.GetType for WinRT types.
- // Note: Type.GetType fails for assembly names that start with weird characters like '['. By calling it for managed types we would
- // break AppCompat.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- internal static Type GetType_Compat(String assemblyString, String typeName)
- {
- // Normally we would get the stackMark only in public APIs. This is internal API, but it is AppCompat replacement of public API
- // call Assembly.Load(assemblyString).GetType(typeName), therefore we take the stackMark here as well, to be fully compatible with
- // the call sequence.
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- RuntimeAssembly assembly;
- AssemblyName assemblyName = RuntimeAssembly.CreateAssemblyName(
- assemblyString,
- false /*forIntrospection*/,
- out assembly);
-
- if (assembly == null) {
- if (assemblyName.ContentType == AssemblyContentType.WindowsRuntime) {
- return Type.GetType(typeName + ", " + assemblyString, true /*throwOnError*/, false /*ignoreCase*/);
- }
-
- assembly = RuntimeAssembly.InternalLoadAssemblyName(
- assemblyName, null, null, ref stackMark,
- true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
- }
- return assembly.GetType(typeName, true /*throwOnError*/, false /*ignoreCase*/);
- }
-
- // Locate an assembly for reflection by the long form of the assembly name.
- // eg. "Toolbox.dll, version=1.1.10.1220, locale=en, publickey=1234567890123456789012345678901234567890"
- //
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly ReflectionOnlyLoad(String assemblyString)
- {
- if (assemblyString == null)
- throw new ArgumentNullException(nameof(assemblyString));
- if (assemblyString.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyLoad"));
- }
-
- // Locate an assembly by its name. The name can be strong or
- // weak. The assembly is loaded into the domain of the caller.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly Load(AssemblyName assemblyRef)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- if (assemblyRef != null && assemblyRef.CodeBase != null)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadCodeBase"));
- }
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/);
- }
-
- // Locate an assembly by its name. The name can be strong or
- // weak. The assembly is loaded into the domain of the caller.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- internal static Assembly Load(AssemblyName assemblyRef, IntPtr ptrLoadContextBinder)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- if (assemblyRef != null && assemblyRef.CodeBase != null)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_AssemblyLoadCodeBase"));
- }
-
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.InternalLoadAssemblyName(assemblyRef, null, null, ref stackMark, true /*thrownOnFileNotFound*/, false /*forIntrospection*/, ptrLoadContextBinder);
- }
-
- [Obsolete("This method has been deprecated. Please use Assembly.Load() instead. http://go.microsoft.com/fwlink/?linkid=14202")]
- public static Assembly LoadWithPartialName(String partialName)
- {
- if(partialName == null)
- throw new ArgumentNullException(nameof(partialName));
- return Load(partialName);
- }
-
- // Loads the assembly with a COFF based IMAGE containing
- // an emitted assembly. The assembly is loaded into the domain
- // of the caller.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly Load(byte[] rawAssembly)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- AppDomain.CheckLoadByteArraySupported();
-
- return Load(rawAssembly, null);
- }
-
- // Loads the assembly for reflection with a COFF based IMAGE containing
- // an emitted assembly. The assembly is loaded into the domain
- // of the caller.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly ReflectionOnlyLoad(byte[] rawAssembly)
- {
- if (rawAssembly == null)
- throw new ArgumentNullException(nameof(rawAssembly));
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyLoad"));
- }
-
- // Loads the assembly with a COFF based IMAGE containing
- // an emitted assembly. The assembly is loaded into the domain
- // of the caller. The second parameter is the raw bytes
- // representing the symbol store that matches the assembly.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly Load(byte[] rawAssembly,
- byte[] rawSymbolStore)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- AppDomain.CheckLoadByteArraySupported();
-
- if(rawAssembly == null)
- throw new ArgumentNullException(nameof(rawAssembly));
- AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
- MemoryStream assemblyStream = new MemoryStream(rawAssembly);
- MemoryStream symbolStream = (rawSymbolStore!=null)?new MemoryStream(rawSymbolStore):null;
- return alc.LoadFromStream(assemblyStream, symbolStream);
- }
-
- private static Dictionary<string, Assembly> s_loadfile = new Dictionary<string, Assembly>();
-
- public static Assembly LoadFile(String path)
- {
- Contract.Ensures(Contract.Result<Assembly>() != null);
- Contract.Ensures(!Contract.Result<Assembly>().ReflectionOnly);
-
- AppDomain.CheckLoadFileSupported();
-
- Assembly result = null;
- if(path == null)
- throw new ArgumentNullException(nameof(path));
-
- if (PathInternal.IsPartiallyQualified(path))
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(path));
- }
-
- string normalizedPath = Path.GetFullPath(path);
-
- lock(s_loadfile)
- {
- if(s_loadfile.TryGetValue(normalizedPath, out result))
- return result;
- AssemblyLoadContext alc = new IndividualAssemblyLoadContext();
- result = alc.LoadFromAssemblyPath(normalizedPath);
- s_loadfile.Add(normalizedPath, result);
- }
- return result;
- }
-
- /*
- * Get the assembly that the current code is running from.
- */
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly GetExecutingAssembly()
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Assembly GetCallingAssembly()
- {
- // LookForMyCallersCaller is not guarantee to return the correct stack frame
- // because of inlining, tail calls, etc. As a result GetCallingAssembly is not
- // ganranteed to return the correct result. We should document it as such.
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller;
- return RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- }
-
- public static Assembly GetEntryAssembly() {
- AppDomainManager domainManager = AppDomain.CurrentDomain.DomainManager;
- if (domainManager == null)
- domainManager = new AppDomainManager();
- return domainManager.EntryAssembly;
- }
-
-#endregion // public static methods
-
-#region public methods
- public virtual event ModuleResolveEventHandler ModuleResolve
- {
- add
- {
- throw new NotImplementedException();
- }
- remove
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual String CodeBase
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual String EscapedCodeBase
- {
- get
- {
- return AssemblyName.EscapeCodeBase(CodeBase);
- }
- }
-
- public virtual AssemblyName GetName()
- {
- return GetName(false);
- }
-
- public virtual AssemblyName GetName(bool copiedName)
- {
- throw new NotImplementedException();
- }
-
- public virtual String FullName
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual MethodInfo EntryPoint
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual Type GetType(String name)
- {
- return GetType(name, false, false);
- }
-
- public virtual Type GetType(String name, bool throwOnError)
- {
- return GetType(name, throwOnError, false);
- }
-
- public virtual Type GetType(String name, bool throwOnError, bool ignoreCase)
- {
- throw new NotImplementedException();
- }
-
- public virtual IEnumerable<Type> ExportedTypes
- {
- get
- {
- return GetExportedTypes();
- }
- }
-
- public virtual Type[] GetExportedTypes()
- {
- throw new NotImplementedException();
- }
-
- public virtual IEnumerable<TypeInfo> DefinedTypes
- {
- get
- {
- Type[] types = GetTypes();
-
- TypeInfo[] typeinfos = new TypeInfo[types.Length];
-
- for (int i = 0; i < types.Length; i++)
- {
-
- TypeInfo typeinfo = types[i].GetTypeInfo();
- if (typeinfo == null)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NoTypeInfo", types[i].FullName));
-
- typeinfos[i] = typeinfo;
- }
-
- return typeinfos;
- }
- }
-
- public virtual Type[] GetTypes()
- {
- Module[] m = GetModules(false);
-
- int iFinalLength = 0;
- Type[][] ModuleTypes = new Type[m.Length][];
-
- for (int i = 0; i < ModuleTypes.Length; i++)
- {
- ModuleTypes[i] = m[i].GetTypes();
- iFinalLength += ModuleTypes[i].Length;
- }
-
- int iCurrent = 0;
- Type[] ret = new Type[iFinalLength];
- for (int i = 0; i < ModuleTypes.Length; i++)
- {
- int iLength = ModuleTypes[i].Length;
- Array.Copy(ModuleTypes[i], 0, ret, iCurrent, iLength);
- iCurrent += iLength;
- }
-
- return ret;
- }
-
- // Load a resource based on the NameSpace of the type.
- public virtual Stream GetManifestResourceStream(Type type, String name)
- {
- throw new NotImplementedException();
- }
-
- public virtual Stream GetManifestResourceStream(String name)
- {
- throw new NotImplementedException();
- }
-
- public virtual Assembly GetSatelliteAssembly(CultureInfo culture)
- {
- throw new NotImplementedException();
- }
-
- // Useful for binding to a very specific version of a satellite assembly
- public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
- {
- throw new NotImplementedException();
- }
-
- public bool IsFullyTrusted
- {
- get
- {
- return true;
- }
- }
-
- public virtual SecurityRuleSet SecurityRuleSet
- {
- get
- {
- return SecurityRuleSet.None;
- }
- }
-
- // ISerializable implementation
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotImplementedException();
- }
-
- public virtual Module ManifestModule
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeAssembly rtAssembly = this as RuntimeAssembly;
- if (rtAssembly != null)
- return rtAssembly.ManifestModule;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual IEnumerable<CustomAttributeData> CustomAttributes
- {
- get
- {
- return GetCustomAttributesData();
- }
- }
- public virtual Object[] GetCustomAttributes(bool inherit)
- {
- Contract.Ensures(Contract.Result<Object[]>() != null);
- throw new NotImplementedException();
- }
-
- public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- Contract.Ensures(Contract.Result<Object[]>() != null);
- throw new NotImplementedException();
- }
-
- public virtual bool IsDefined(Type attributeType, bool inherit)
- {
- throw new NotImplementedException();
- }
-
- public virtual IList<CustomAttributeData> GetCustomAttributesData()
- {
- throw new NotImplementedException();
- }
-
- public virtual bool ReflectionOnly
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public Module LoadModule(String moduleName,
- byte[] rawModule)
- {
- return LoadModule(moduleName, rawModule, null);
- }
-
- public virtual Module LoadModule(String moduleName,
- byte[] rawModule,
- byte[] rawSymbolStore)
- {
- throw new NotImplementedException();
- }
-
- //
- // Locates a type from this assembly and creates an instance of it using
- // the system activator.
- //
- public Object CreateInstance(String typeName)
- {
- return CreateInstance(typeName,
- false, // ignore case
- BindingFlags.Public | BindingFlags.Instance,
- null, // binder
- null, // args
- null, // culture
- null); // activation attributes
- }
-
- public Object CreateInstance(String typeName,
- bool ignoreCase)
- {
- return CreateInstance(typeName,
- ignoreCase,
- BindingFlags.Public | BindingFlags.Instance,
- null, // binder
- null, // args
- null, // culture
- null); // activation attributes
- }
-
- public virtual Object CreateInstance(String typeName,
- bool ignoreCase,
- BindingFlags bindingAttr,
- Binder binder,
- Object[] args,
- CultureInfo culture,
- Object[] activationAttributes)
- {
- Type t = GetType(typeName, false, ignoreCase);
- if (t == null) return null;
- return Activator.CreateInstance(t,
- bindingAttr,
- binder,
- args,
- culture,
- activationAttributes);
- }
-
- public virtual IEnumerable<Module> Modules
- {
- get
- {
- return GetLoadedModules(true);
- }
- }
-
- public Module[] GetLoadedModules()
- {
- return GetLoadedModules(false);
- }
-
- public virtual Module[] GetLoadedModules(bool getResourceModules)
- {
- throw new NotImplementedException();
- }
-
- public Module[] GetModules()
- {
- return GetModules(false);
- }
-
- public virtual Module[] GetModules(bool getResourceModules)
- {
- throw new NotImplementedException();
- }
-
- public virtual Module GetModule(String name)
- {
- throw new NotImplementedException();
- }
-
- // Returns the file in the File table of the manifest that matches the
- // given name. (Name should not include path.)
- public virtual FileStream GetFile(String name)
- {
- throw new NotImplementedException();
- }
-
- public virtual FileStream[] GetFiles()
- {
- return GetFiles(false);
- }
-
- public virtual FileStream[] GetFiles(bool getResourceModules)
- {
- throw new NotImplementedException();
- }
-
- // Returns the names of all the resources
- public virtual String[] GetManifestResourceNames()
- {
- throw new NotImplementedException();
- }
-
- public virtual AssemblyName[] GetReferencedAssemblies()
- {
- throw new NotImplementedException();
- }
-
- public virtual ManifestResourceInfo GetManifestResourceInfo(String resourceName)
- {
- throw new NotImplementedException();
- }
-
- public override String ToString()
- {
- String displayName = FullName;
- if (displayName == null)
- return base.ToString();
- else
- return displayName;
- }
-
- public virtual String Location
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual String ImageRuntimeVersion
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- /*
- Returns true if the assembly was loaded from the global assembly cache.
- */
- public virtual bool GlobalAssemblyCache
- {
- get
- {
- throw new NotImplementedException();
- }
- }
-
- public virtual Int64 HostContext
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeAssembly rtAssembly = this as RuntimeAssembly;
- if (rtAssembly != null)
- return rtAssembly.HostContext;
-
- throw new NotImplementedException();
- }
- }
-
- public virtual bool IsDynamic
- {
- get
- {
- return false;
- }
- }
-#endregion // public methods
-
- }
-
[Serializable]
internal class RuntimeAssembly : Assembly
{
@@ -767,11 +26,10 @@ namespace System.Reflection
// the cached ctor token of [DynamicallyInvocableAttribute].
private enum ASSEMBLY_FLAGS : uint
{
- ASSEMBLY_FLAGS_UNKNOWN = 0x00000000,
- ASSEMBLY_FLAGS_INITIALIZED = 0x01000000,
- ASSEMBLY_FLAGS_FRAMEWORK = 0x02000000,
- ASSEMBLY_FLAGS_SAFE_REFLECTION = 0x04000000,
- ASSEMBLY_FLAGS_TOKEN_MASK = 0x00FFFFFF,
+ ASSEMBLY_FLAGS_UNKNOWN = 0x00000000,
+ ASSEMBLY_FLAGS_INITIALIZED = 0x01000000,
+ ASSEMBLY_FLAGS_FRAMEWORK = 0x02000000,
+ ASSEMBLY_FLAGS_TOKEN_MASK = 0x00FFFFFF,
}
#endif // FEATURE_APPX
@@ -779,7 +37,7 @@ namespace System.Reflection
internal RuntimeAssembly() { throw new NotSupportedException(); }
-#region private data members
+ #region private data members
private event ModuleResolveEventHandler _ModuleResolve;
private string m_fullname;
private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit
@@ -788,19 +46,9 @@ namespace System.Reflection
#if FEATURE_APPX
private ASSEMBLY_FLAGS m_flags;
#endif
-#endregion
+ #endregion
#if FEATURE_APPX
- internal int InvocableAttributeCtorToken
- {
- get
- {
- int token = (int)(Flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_TOKEN_MASK);
-
- return token | (int)MetadataTokenType.MethodDef;
- }
- }
-
private ASSEMBLY_FLAGS Flags
{
get
@@ -808,7 +56,7 @@ namespace System.Reflection
if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0)
{
ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN
- | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION;
+ | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK;
m_flags = flags | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED;
}
@@ -829,7 +77,7 @@ namespace System.Reflection
return m_syncRoot;
}
}
-
+
public override event ModuleResolveEventHandler ModuleResolve
{
add
@@ -846,8 +94,8 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private static extern void GetCodeBase(RuntimeAssembly assembly,
- bool copiedName,
+ private static extern void GetCodeBase(RuntimeAssembly assembly,
+ bool copiedName,
StringHandleOnStack retString);
internal String GetCodeBase(bool copiedName)
@@ -859,7 +107,8 @@ namespace System.Reflection
public override String CodeBase
{
- get {
+ get
+ {
String codeBase = GetCodeBase(false);
return codeBase;
}
@@ -879,7 +128,7 @@ namespace System.Reflection
String codeBase = GetCodeBase(copiedName);
- an.Init(GetSimpleName(),
+ an.Init(GetSimpleName(),
GetPublicKey(),
null, // public key token
GetVersion(),
@@ -892,14 +141,14 @@ namespace System.Reflection
PortableExecutableKinds pek;
ImageFileMachine ifm;
-
+
Module manifestModule = ManifestModule;
if (manifestModule != null)
{
if (manifestModule.MDStreamVersion > 0x10000)
{
ManifestModule.GetPEKind(out pek, out ifm);
- an.SetProcArchIndex(pek,ifm);
+ an.SetProcArchIndex(pek, ifm);
}
}
return an;
@@ -911,7 +160,8 @@ namespace System.Reflection
public override String FullName
{
- get {
+ get
+ {
// If called by Object.ToString(), return val may be NULL.
if (m_fullname == null)
{
@@ -927,30 +177,31 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod);
-
+
public override MethodInfo EntryPoint
{
- get {
+ get
+ {
IRuntimeMethodInfo methodHandle = null;
GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle));
if (methodHandle == null)
return null;
- return (MethodInfo)RuntimeType.GetMethodBase(methodHandle);
+ return (MethodInfo)RuntimeType.GetMethodBase(methodHandle);
}
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private static extern void GetType(RuntimeAssembly assembly,
- String name,
- bool throwOnError,
+ private static extern void GetType(RuntimeAssembly assembly,
+ String name,
+ bool throwOnError,
bool ignoreCase,
ObjectHandleOnStack type,
ObjectHandleOnStack keepAlive);
-
- public override Type GetType(String name, bool throwOnError, bool ignoreCase)
+
+ public override Type GetType(String name, bool throwOnError, bool ignoreCase)
{
// throw on null strings regardless of the value of "throwOnError"
if (name == null)
@@ -960,14 +211,14 @@ namespace System.Reflection
Object keepAlive = null;
GetType(GetNativeHandle(), name, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
GC.KeepAlive(keepAlive);
-
+
return type;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
-
+ private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes);
+
public override Type[] GetExportedTypes()
{
Type[] types = null;
@@ -993,14 +244,14 @@ namespace System.Reflection
}
// Load a resource based on the NameSpace of the type.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Stream GetManifestResourceStream(Type type, String name)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return GetManifestResourceStream(type, name, false, ref stackMark);
}
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Stream GetManifestResourceStream(String name)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1010,14 +261,14 @@ namespace System.Reflection
// ISerializable implementation
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info==null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
UnitySerializationHolder.GetUnitySerializationInfo(info,
- UnitySerializationHolder.AssemblyUnity,
- this.FullName,
+ UnitySerializationHolder.AssemblyUnity,
+ this.FullName,
this);
}
@@ -1044,8 +295,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -1058,8 +309,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -1069,10 +320,10 @@ namespace System.Reflection
return CustomAttributeData.GetCustomAttributesInternal(this);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- internal static RuntimeAssembly InternalLoadFrom(String assemblyFile,
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ internal static RuntimeAssembly InternalLoadFrom(String assemblyFile,
Evidence securityEvidence,
- byte[] hashValue,
+ byte[] hashValue,
AssemblyHashAlgorithm hashAlgorithm,
bool forIntrospection,
ref StackCrawlMark stackMark)
@@ -1095,10 +346,10 @@ namespace System.Reflection
ref StackCrawlMark stackMark,
bool forIntrospection)
{
- return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection);
+ return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal static RuntimeAssembly InternalLoad(String assemblyString,
Evidence assemblySecurity,
ref StackCrawlMark stackMark,
@@ -1108,20 +359,21 @@ namespace System.Reflection
RuntimeAssembly assembly;
AssemblyName an = CreateAssemblyName(assemblyString, forIntrospection, out assembly);
- if (assembly != null) {
+ if (assembly != null)
+ {
// The assembly was returned from ResolveAssemblyEvent
return assembly;
}
- return InternalLoadAssemblyName(an, assemblySecurity, null, ref stackMark,
+ return InternalLoadAssemblyName(an, assemblySecurity, null, ref stackMark,
pPrivHostBinder,
true /*thrownOnFileNotFound*/, forIntrospection);
}
-
+
// Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised.
internal static AssemblyName CreateAssemblyName(
- String assemblyString,
- bool forIntrospection,
+ String assemblyString,
+ bool forIntrospection,
out RuntimeAssembly assemblyFromResolveEvent)
{
if (assemblyString == null)
@@ -1130,7 +382,7 @@ namespace System.Reflection
if ((assemblyString.Length == 0) ||
(assemblyString[0] == '\0'))
- throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
+ throw new ArgumentException(SR.Format_StringZeroLength);
if (forIntrospection)
AppDomain.CheckReflectionOnlyLoadSupported();
@@ -1139,10 +391,10 @@ namespace System.Reflection
an.Name = assemblyString;
an.nInit(out assemblyFromResolveEvent, forIntrospection, true);
-
+
return an;
}
-
+
// Wrapper function to wrap the typical use of InternalLoadAssemblyName.
internal static RuntimeAssembly InternalLoadAssemblyName(
AssemblyName assemblyRef,
@@ -1157,16 +409,15 @@ namespace System.Reflection
}
internal static RuntimeAssembly InternalLoadAssemblyName(
- AssemblyName assemblyRef,
+ AssemblyName assemblyRef,
Evidence assemblySecurity,
RuntimeAssembly reqAssembly,
ref StackCrawlMark stackMark,
IntPtr pPrivHostBinder,
- bool throwOnFileNotFound,
+ bool throwOnFileNotFound,
bool forIntrospection,
IntPtr ptrLoadContextBinder = default(IntPtr))
{
-
if (assemblyRef == null)
throw new ArgumentNullException(nameof(assemblyRef));
Contract.EndContractBlock();
@@ -1178,7 +429,8 @@ namespace System.Reflection
assemblyRef = (AssemblyName)assemblyRef.Clone();
if (!forIntrospection &&
- (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None)) {
+ (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None))
+ {
// PA does not have a semantics for by-name binds for execution
assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None;
}
@@ -1194,7 +446,7 @@ namespace System.Reflection
// on behalf of user code. We allow framework code to invoke non-W8P
// framework APIs but don't want user code to gain that privilege
// through these assemblies. So we blaklist them.
- static string[] s_unsafeFrameworkAssemblyNames = new string[] {
+ private static string[] s_unsafeFrameworkAssemblyNames = new string[] {
"System.Reflection.Context",
"Microsoft.VisualBasic"
};
@@ -1205,14 +457,6 @@ namespace System.Reflection
ASSEMBLY_FLAGS flags = Flags;
return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK) != 0;
}
-
- // Returns true if we want to allow this assembly to invoke non-W8P
- // framework APIs through reflection.
- internal bool IsSafeForReflection()
- {
- ASSEMBLY_FLAGS flags = Flags;
- return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_SAFE_REFLECTION) != 0;
- }
#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1314,7 +558,7 @@ namespace System.Reflection
GetExecutingAssembly(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly));
return retAssembly;
}
-
+
// Returns the names of all the resources
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly);
@@ -1332,13 +576,13 @@ namespace System.Reflection
StringHandleOnStack retFileName,
StackCrawlMarkHandle stackMark);
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override ManifestResourceInfo GetManifestResourceInfo(String resourceName)
{
RuntimeAssembly retAssembly = null;
String fileName = null;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- int location = GetManifestResourceInfo(GetNativeHandle(), resourceName,
+ int location = GetManifestResourceInfo(GetNativeHandle(), resourceName,
JitHelpers.GetObjectHandleOnStack(ref retAssembly),
JitHelpers.GetStringHandleOnStack(ref fileName),
JitHelpers.GetStackCrawlMarkHandle(ref stackMark));
@@ -1347,7 +591,7 @@ namespace System.Reflection
return null;
return new ManifestResourceInfo(retAssembly, fileName,
- (ResourceLocation) location);
+ (ResourceLocation)location);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1356,7 +600,8 @@ namespace System.Reflection
public override String Location
{
- get {
+ get
+ {
String location = null;
GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location));
@@ -1371,7 +616,8 @@ namespace System.Reflection
public override String ImageRuntimeVersion
{
- get{
+ get
+ {
String s = null;
GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s));
return s;
@@ -1396,7 +642,7 @@ namespace System.Reflection
private static String VerifyCodeBase(String codebase)
{
- if(codebase == null)
+ if (codebase == null)
return null;
int len = codebase.Length;
@@ -1406,12 +652,12 @@ namespace System.Reflection
int j = codebase.IndexOf(':');
// Check to see if the url has a prefix
- if( (j != -1) &&
- (j+2 < len) &&
- ((codebase[j+1] == '/') || (codebase[j+1] == '\\')) &&
- ((codebase[j+2] == '/') || (codebase[j+2] == '\\')) )
+ if ((j != -1) &&
+ (j + 2 < len) &&
+ ((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) &&
+ ((codebase[j + 2] == '/') || (codebase[j + 2] == '\\')))
return codebase;
-#if !PLATFORM_UNIX
+#if PLATFORM_WINDOWS
else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\'))
return "file://" + codebase;
else
@@ -1419,7 +665,7 @@ namespace System.Reflection
#else
else
return "file://" + Path.GetFullPath(codebase);
-#endif // !PLATFORM_UNIX
+#endif // PLATFORM_WINDOWS
}
internal Stream GetManifestResourceStream(
@@ -1429,20 +675,23 @@ namespace System.Reflection
ref StackCrawlMark stackMark)
{
StringBuilder sb = new StringBuilder();
- if(type == null) {
+ if (type == null)
+ {
if (name == null)
throw new ArgumentNullException(nameof(type));
}
- else {
+ else
+ {
String nameSpace = type.Namespace;
- if(nameSpace != null) {
+ if (nameSpace != null)
+ {
sb.Append(nameSpace);
- if(name != null)
+ if (name != null)
sb.Append(Type.Delimiter);
}
}
- if(name != null)
+ if (name != null)
sb.Append(name);
return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck);
@@ -1462,10 +711,11 @@ namespace System.Reflection
ulong length = 0;
byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), skipSecurityCheck);
- if (pbInMemoryResource != null) {
+ if (pbInMemoryResource != null)
+ {
//Console.WriteLine("Creating an unmanaged memory stream of length "+length);
if (length > Int64.MaxValue)
- throw new NotImplementedException(Environment.GetResourceString("NotImplemented_ResourcesLongerThan2^63"));
+ throw new NotImplementedException(SR.NotImplemented_ResourcesLongerThanInt64Max);
return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read);
}
@@ -1476,9 +726,9 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private static extern void GetVersion(RuntimeAssembly assembly,
- out int majVer,
- out int minVer,
+ private static extern void GetVersion(RuntimeAssembly assembly,
+ out int majVer,
+ out int minVer,
out int buildNum,
out int revNum);
@@ -1486,7 +736,7 @@ namespace System.Reflection
{
int majorVer, minorVer, build, revision;
GetVersion(GetNativeHandle(), out majorVer, out minorVer, out build, out revision);
- return new Version (majorVer, minorVer, build, revision);
+ return new Version(majorVer, minorVer, build, revision);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -1510,7 +760,8 @@ namespace System.Reflection
public override bool IsDynamic
{
- get {
+ get
+ {
return FCallIsDynamic(GetNativeHandle());
}
}
@@ -1534,7 +785,7 @@ namespace System.Reflection
{
return GetHashAlgorithm(GetNativeHandle());
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly);
@@ -1575,8 +826,9 @@ namespace System.Reflection
Delegate[] ds = moduleResolve.GetInvocationList();
int len = ds.Length;
- for (int i = 0; i < len; i++) {
- RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler) ds[i])(this, new ResolveEventArgs(moduleName,this));
+ for (int i = 0; i < len; i++)
+ {
+ RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler)ds[i])(this, new ResolveEventArgs(moduleName, this));
if (ret != null)
return ret;
}
@@ -1584,7 +836,7 @@ namespace System.Reflection
return null;
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -1592,14 +844,14 @@ namespace System.Reflection
}
// Useful for binding to a very specific version of a satellite assembly
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return InternalGetSatelliteAssembly(culture, version, ref stackMark);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal Assembly InternalGetSatelliteAssembly(CultureInfo culture,
Version version,
ref StackCrawlMark stackMark)
@@ -1613,14 +865,13 @@ namespace System.Reflection
return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
internal RuntimeAssembly InternalGetSatelliteAssembly(String name,
CultureInfo culture,
Version version,
bool throwOnFileNotFound,
ref StackCrawlMark stackMark)
{
-
AssemblyName an = new AssemblyName();
an.SetPublicKey(GetPublicKey());
@@ -1634,13 +885,13 @@ namespace System.Reflection
an.CultureInfo = culture;
an.Name = name;
- RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark,
+ RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark,
IntPtr.Zero,
throwOnFileNotFound, false);
if (retAssembly == this || (retAssembly == null && throwOnFileNotFound))
{
- throw new FileNotFoundException(String.Format(culture, Environment.GetResourceString("IO.FileNotFound_FileName"), an.Name));
+ throw new FileNotFoundException(String.Format(culture, SR.IO_FileNotFound_FileName, an.Name));
}
return retAssembly;
@@ -1648,11 +899,11 @@ namespace System.Reflection
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private extern static void GetModules(RuntimeAssembly assembly,
- bool loadIfNotFound,
- bool getResourceModules,
+ private extern static void GetModules(RuntimeAssembly assembly,
+ bool loadIfNotFound,
+ bool getResourceModules,
ObjectHandleOnStack retModuleHandles);
-
+
private RuntimeModule[] GetModulesInternal(bool loadIfNotFound,
bool getResourceModules)
{
diff --git a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
index c8d71bc1f9..8c3b1fce98 100644
--- a/src/mscorlib/src/System/Reflection/ConstructorInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
@@ -2,94 +2,15 @@
// 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.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.Serialization;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Threading;
- using MemberListType = System.RuntimeType.MemberListType;
- using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
- using System.Runtime.CompilerServices;
-
- [Serializable]
- public abstract class ConstructorInfo : MethodBase
- {
- #region Static Members
- public readonly static String ConstructorName = ".ctor";
-
- public readonly static String TypeConstructorName = ".cctor";
- #endregion
-
- #region Constructor
- protected ConstructorInfo() { }
- #endregion
-
- public static bool operator ==(ConstructorInfo left, ConstructorInfo right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimeConstructorInfo || right is RuntimeConstructorInfo)
- {
- return false;
- }
- return left.Equals(right);
- }
-
- public static bool operator !=(ConstructorInfo left, ConstructorInfo right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- #region Internal Members
- internal virtual Type GetReturnType() { throw new NotImplementedException(); }
- #endregion
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Constructor; } }
- #endregion
-
- #region Public Abstract\Virtual Members
- public abstract Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture);
- #endregion
-
- #region Public Members
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public Object Invoke(Object[] parameters)
- {
- // Theoretically we should set up a LookForMyCaller stack mark here and pass that along.
- // But to maintain backward compatibility we can't switch to calling an
- // internal overload that takes a stack mark.
- // Fortunately the stack walker skips all the reflection invocation frames including this one.
- // So this method will never be returned by the stack walker as the caller.
- // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp.
- return Invoke(BindingFlags.Default, null, parameters, null);
- }
- #endregion
- }
-
[Serializable]
internal sealed class RuntimeConstructorInfo : ConstructorInfo, ISerializable, IRuntimeMethodInfo
{
@@ -109,28 +30,6 @@ namespace System.Reflection
private volatile Signature m_signature;
private INVOCATION_FLAGS m_invocationFlags;
-#if FEATURE_APPX
- private bool IsNonW8PFrameworkAPI()
- {
- if (DeclaringType.IsArray && IsPublic && !IsStatic)
- return false;
-
- RuntimeAssembly rtAssembly = GetRuntimeAssembly();
- if (rtAssembly.IsFrameworkAssembly())
- {
- int ctorToken = rtAssembly.InvocableAttributeCtorToken;
- if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
- !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
- return true;
- }
-
- if (GetRuntimeType().IsNonW8PFrameworkAPI())
- return true;
-
- return false;
- }
-#endif // FEATURE_APPX
-
internal INVOCATION_FLAGS InvocationFlags
{
get
@@ -143,7 +42,7 @@ namespace System.Reflection
//
// first take care of all the NO_INVOKE cases.
- if ( declaringType == typeof(void) ||
+ if (declaringType == typeof(void) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) ||
((Attributes & MethodAttributes.RequireSecObject) == MethodAttributes.RequireSecObject))
@@ -160,9 +59,9 @@ 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 ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 &&
((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
- (declaringType != null && declaringType.NeedsReflectionSecurityCheck)) )
+ (declaringType != null && declaringType.NeedsReflectionSecurityCheck)))
{
// If method is non-public, or declaring type is not visible
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
@@ -174,11 +73,6 @@ namespace System.Reflection
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;
}
-#if FEATURE_APPX
- if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
-#endif // FEATURE_APPX
-
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
@@ -233,24 +127,24 @@ namespace System.Reflection
}
private RuntimeType ReflectedTypeInternal
- {
- get
- {
- return m_reflectedTypeCache.GetRuntimeType();
- }
+ {
+ get
+ {
+ return m_reflectedTypeCache.GetRuntimeType();
+ }
}
- private void CheckConsistency(Object target)
+ private void CheckConsistency(Object target)
{
if (target == null && IsStatic)
return;
if (!m_declaringType.IsInstanceOfType(target))
{
- if (target == null)
- throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
+ if (target == null)
+ throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg);
- throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
+ throw new TargetException(SR.RFLCT_Targ_ITargMismatch);
}
}
@@ -258,7 +152,7 @@ namespace System.Reflection
#endregion
#region Object Overrides
- public override String ToString()
+ public override String ToString()
{
// "Void" really doesn't make sense here. But we'll keep it for compat reasons.
if (m_toString == null)
@@ -282,8 +176,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -296,12 +190,12 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
-
+
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
@@ -315,12 +209,12 @@ namespace System.Reflection
get { return RuntimeMethodHandle.GetName(this); }
}
public override MemberTypes MemberType { get { return MemberTypes.Constructor; } }
-
- public override Type DeclaringType
- {
- get
- {
- return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
+
+ public override Type DeclaringType
+ {
+ get
+ {
+ return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
}
}
@@ -349,8 +243,8 @@ namespace System.Reflection
#region MethodBase Overrides
// This seems to always returns System.Void.
- internal override Type GetReturnType() { return Signature.ReturnType; }
-
+ internal override Type GetReturnType() { return Signature.ReturnType; }
+
internal override ParameterInfo[] GetParametersNoCopy()
{
if (m_parameters == null)
@@ -366,7 +260,7 @@ namespace System.Reflection
if (parameters.Length == 0)
return parameters;
-
+
ParameterInfo[] ret = new ParameterInfo[parameters.Length];
Array.Copy(parameters, ret, parameters.Length);
return ret;
@@ -377,18 +271,18 @@ namespace System.Reflection
return RuntimeMethodHandle.GetImplAttributes(this);
}
- public override RuntimeMethodHandle MethodHandle
+ public override RuntimeMethodHandle MethodHandle
{
get
{
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
return new RuntimeMethodHandle(this);
}
}
- public override MethodAttributes Attributes
+ public override MethodAttributes Attributes
{
get
{
@@ -396,7 +290,7 @@ namespace System.Reflection
}
}
- public override CallingConventions CallingConvention
+ public override CallingConventions CallingConvention
{
get
{
@@ -409,39 +303,39 @@ namespace System.Reflection
if (declaringType == null)
throw new ArgumentNullException(nameof(declaringType));
Contract.EndContractBlock();
-
+
// ctor is ReflectOnly
if (declaringType is ReflectionOnlyType)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
-
+ throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
+
// ctor is declared on interface class
else if (declaringType.IsInterface)
throw new MemberAccessException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateInterfaceEx"), declaringType));
-
+ String.Format(CultureInfo.CurrentUICulture, SR.Acc_CreateInterfaceEx, declaringType));
+
// ctor is on an abstract class
else if (declaringType.IsAbstract)
throw new MemberAccessException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateAbstEx"), declaringType));
-
+ String.Format(CultureInfo.CurrentUICulture, SR.Acc_CreateAbstEx, declaringType));
+
// ctor is on a class that contains stack pointers
else if (declaringType.GetRootElementType() == typeof(ArgIterator))
throw new NotSupportedException();
-
+
// ctor is vararg
else if (isVarArg)
throw new NotSupportedException();
-
+
// ctor is generic or on a generic class
else if (declaringType.ContainsGenericParameters)
{
throw new MemberAccessException(
- String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Acc_CreateGenericEx"), declaringType));
+ String.Format(CultureInfo.CurrentUICulture, SR.Acc_CreateGenericEx, declaringType));
}
// ctor is declared on System.Void
else if (declaringType == typeof(void))
- throw new MemberAccessException(Environment.GetResourceString("Access_Void"));
+ throw new MemberAccessException(SR.Access_Void);
}
internal void ThrowNoInvokeException()
@@ -450,35 +344,25 @@ namespace System.Reflection
// ctor is .cctor
if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static)
- throw new MemberAccessException(Environment.GetResourceString("Acc_NotClassInit"));
-
+ throw new MemberAccessException(SR.Acc_NotClassInit);
+
throw new TargetException();
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(
Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
+ if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
-#if FEATURE_APPX
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
- }
-#endif
-
if (obj != null)
{
// For unverifiable code, we require the caller to be critical.
@@ -490,17 +374,17 @@ namespace System.Reflection
// get the signature
int formalCount = sig.Arguments.Length;
- int actualCount =(parameters != null) ? parameters.Length : 0;
+ int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
- throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
-
+ throw new TargetParameterCountException(SR.Arg_ParmCnt);
+
// if we are here we passed all the previous checks. Time to look at the arguments
- if (actualCount > 0)
+ if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false);
// copy out. This should be made only if ByRef are present.
- for (int index = 0; index < arguments.Length; index++)
+ for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
@@ -510,7 +394,7 @@ namespace System.Reflection
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
- if (mb != null)
+ if (mb != null)
mb.m_methodBase = this;
return mb;
}
@@ -542,66 +426,49 @@ namespace System.Reflection
#region ConstructorInfo Overrides
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// get the declaring TypeHandle early for consistent exceptions in IntrospectionOnly context
RuntimeTypeHandle declaringTypeHandle = m_declaringType.TypeHandle;
-
+
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE)) != 0)
ThrowNoInvokeException();
-#if FEATURE_APPX
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
- }
-#endif
-
// get the signature
Signature sig = Signature;
int formalCount = sig.Arguments.Length;
- int actualCount =(parameters != null) ? parameters.Length : 0;
+ int actualCount = (parameters != null) ? parameters.Length : 0;
if (formalCount != actualCount)
- throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
+ throw new TargetParameterCountException(SR.Arg_ParmCnt);
// We don't need to explicitly invoke the class constructor here,
// 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
- if (actualCount > 0)
+ if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true);
// copy out. This should be made only if ByRef are present.
- for (int index = 0; index < arguments.Length; index++)
+ for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
return RuntimeMethodHandle.InvokeMethod(null, null, sig, true);
}
#endregion
-
+
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
- MemberInfoSerializationHolder.GetSerializationInfo(
- info,
- Name,
- ReflectedTypeInternal,
- ToString(),
- SerializationToString(),
- MemberTypes.Constructor,
- null);
+ MemberInfoSerializationHolder.GetSerializationInfo(info, this);
}
internal string SerializationToString()
@@ -609,6 +476,6 @@ namespace System.Reflection
// We don't need the return type for constructors.
return FormatNameAndSig(true);
}
- #endregion
+ #endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs
new file mode 100644
index 0000000000..930e1820bd
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/RuntimeEventInfo.cs
@@ -0,0 +1,220 @@
+// 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.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
+
+namespace System.Reflection
+{
+ [Serializable]
+ internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable
+ {
+ #region Private Data Members
+ private int m_token;
+ private EventAttributes m_flags;
+ private string m_name;
+ private void* m_utf8name;
+ private RuntimeTypeCache m_reflectedTypeCache;
+ private RuntimeMethodInfo m_addMethod;
+ private RuntimeMethodInfo m_removeMethod;
+ private RuntimeMethodInfo m_raiseMethod;
+ private MethodInfo[] m_otherMethod;
+ private RuntimeType m_declaringType;
+ private BindingFlags m_bindingFlags;
+ #endregion
+
+ #region Constructor
+ internal RuntimeEventInfo()
+ {
+ // Used for dummy head node during population
+ }
+ internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
+ {
+ Contract.Requires(declaredType != null);
+ Contract.Requires(reflectedTypeCache != null);
+ Debug.Assert(!reflectedTypeCache.IsGlobal);
+
+ MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
+
+ m_token = tkEvent;
+ m_reflectedTypeCache = reflectedTypeCache;
+ m_declaringType = declaredType;
+
+
+ RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType();
+
+ scope.GetEventProps(tkEvent, out m_utf8name, out m_flags);
+
+ RuntimeMethodInfo dummy;
+ Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType,
+ out m_addMethod, out m_removeMethod, out m_raiseMethod,
+ out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags);
+ }
+ #endregion
+
+ #region Internal Members
+ internal override bool CacheEquals(object o)
+ {
+ RuntimeEventInfo m = o as RuntimeEventInfo;
+
+ if ((object)m == null)
+ return false;
+
+ return m.m_token == m_token &&
+ RuntimeTypeHandle.GetModule(m_declaringType).Equals(
+ RuntimeTypeHandle.GetModule(m.m_declaringType));
+ }
+
+ internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
+ #endregion
+
+ #region Object Overrides
+ public override String ToString()
+ {
+ if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0)
+ throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod);
+
+ return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name;
+ }
+ #endregion
+
+ #region ICustomAttributeProvider
+ public override Object[] GetCustomAttributes(bool inherit)
+ {
+ return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ }
+
+ public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
+ {
+ if (attributeType == null)
+ throw new ArgumentNullException(nameof(attributeType));
+ Contract.EndContractBlock();
+
+ RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
+
+ return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
+ }
+
+ public override bool IsDefined(Type attributeType, bool inherit)
+ {
+ if (attributeType == null)
+ throw new ArgumentNullException(nameof(attributeType));
+ Contract.EndContractBlock();
+
+ RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
+
+ return CustomAttribute.IsDefined(this, attributeRuntimeType);
+ }
+
+ public override IList<CustomAttributeData> GetCustomAttributesData()
+ {
+ return CustomAttributeData.GetCustomAttributesInternal(this);
+ }
+ #endregion
+
+ #region MemberInfo Overrides
+ public override MemberTypes MemberType { get { return MemberTypes.Event; } }
+ public override String Name
+ {
+ get
+ {
+ if (m_name == null)
+ m_name = new Utf8String(m_utf8name).ToString();
+
+ return m_name;
+ }
+ }
+ public override Type DeclaringType { get { return m_declaringType; } }
+ public override Type ReflectedType
+ {
+ get
+ {
+ return ReflectedTypeInternal;
+ }
+ }
+
+ private RuntimeType ReflectedTypeInternal
+ {
+ get
+ {
+ return m_reflectedTypeCache.GetRuntimeType();
+ }
+ }
+
+ public override int MetadataToken { get { return m_token; } }
+ public override Module Module { get { return GetRuntimeModule(); } }
+ internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
+ #endregion
+
+ #region ISerializable
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ throw new ArgumentNullException(nameof(info));
+ Contract.EndContractBlock();
+
+ MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ }
+ #endregion
+
+ #region EventInfo Overrides
+ public override MethodInfo[] GetOtherMethods(bool nonPublic)
+ {
+ List<MethodInfo> ret = new List<MethodInfo>();
+
+ if ((object)m_otherMethod == null)
+ return new MethodInfo[0];
+
+ for (int i = 0; i < m_otherMethod.Length; i++)
+ {
+ if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic))
+ ret.Add(m_otherMethod[i]);
+ }
+
+ return ret.ToArray();
+ }
+
+ public override MethodInfo GetAddMethod(bool nonPublic)
+ {
+ if (!Associates.IncludeAccessor(m_addMethod, nonPublic))
+ return null;
+
+ return m_addMethod;
+ }
+
+ public override MethodInfo GetRemoveMethod(bool nonPublic)
+ {
+ if (!Associates.IncludeAccessor(m_removeMethod, nonPublic))
+ return null;
+
+ return m_removeMethod;
+ }
+
+ public override MethodInfo GetRaiseMethod(bool nonPublic)
+ {
+ if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic))
+ return null;
+
+ return m_raiseMethod;
+ }
+
+ public override EventAttributes Attributes
+ {
+ get
+ {
+ return m_flags;
+ }
+ }
+ #endregion
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs
new file mode 100644
index 0000000000..29cc97d225
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/RuntimeFieldInfo.cs
@@ -0,0 +1,136 @@
+// 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.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
+
+namespace System.Reflection
+{
+ [Serializable]
+ internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable
+ {
+ #region Private Data Members
+ private BindingFlags m_bindingFlags;
+ protected RuntimeTypeCache m_reflectedTypeCache;
+ protected RuntimeType m_declaringType;
+ #endregion
+
+ #region Constructor
+ protected RuntimeFieldInfo()
+ {
+ // Used for dummy head node during population
+ }
+ protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags)
+ {
+ m_bindingFlags = bindingFlags;
+ m_declaringType = declaringType;
+ m_reflectedTypeCache = reflectedTypeCache;
+ }
+ #endregion
+
+ #region NonPublic Members
+ internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
+ private RuntimeType ReflectedTypeInternal
+ {
+ get
+ {
+ return m_reflectedTypeCache.GetRuntimeType();
+ }
+ }
+
+ internal RuntimeType GetDeclaringTypeInternal()
+ {
+ return m_declaringType;
+ }
+
+ internal RuntimeType GetRuntimeType() { return m_declaringType; }
+ internal abstract RuntimeModule GetRuntimeModule();
+ #endregion
+
+ #region MemberInfo Overrides
+ public override MemberTypes MemberType { get { return MemberTypes.Field; } }
+ public override Type ReflectedType
+ {
+ get
+ {
+ return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal;
+ }
+ }
+
+ public override Type DeclaringType
+ {
+ get
+ {
+ return m_reflectedTypeCache.IsGlobal ? null : m_declaringType;
+ }
+ }
+
+ public override Module Module { get { return GetRuntimeModule(); } }
+ #endregion
+
+ #region Object Overrides
+ public unsafe override String ToString()
+ {
+ return FieldType.FormatTypeName() + " " + Name;
+ }
+ #endregion
+
+ #region ICustomAttributeProvider
+ public override Object[] GetCustomAttributes(bool inherit)
+ {
+ return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ }
+
+ public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
+ {
+ if (attributeType == null)
+ throw new ArgumentNullException(nameof(attributeType));
+ Contract.EndContractBlock();
+
+ RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
+
+ return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
+ }
+
+ public override bool IsDefined(Type attributeType, bool inherit)
+ {
+ if (attributeType == null)
+ throw new ArgumentNullException(nameof(attributeType));
+ Contract.EndContractBlock();
+
+ RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
+
+ return CustomAttribute.IsDefined(this, attributeRuntimeType);
+ }
+
+ public override IList<CustomAttributeData> GetCustomAttributesData()
+ {
+ return CustomAttributeData.GetCustomAttributesInternal(this);
+ }
+ #endregion
+
+ #region FieldInfo Overrides
+ // All implemented on derived classes
+ #endregion
+
+ #region ISerializable Implementation
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ throw new ArgumentNullException(nameof(info));
+ Contract.EndContractBlock();
+
+ MemberInfoSerializationHolder.GetSerializationInfo(info, this);
+ }
+ #endregion
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/MethodInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
index 5ce124614c..b8a2341e4e 100644
--- a/src/mscorlib/src/System/Reflection/MethodInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
@@ -2,90 +2,23 @@
// 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.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Security;
+using System.Text;
+using System.Threading;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Text;
- using System.Threading;
- using MemberListType = System.RuntimeType.MemberListType;
- using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
- using System.Runtime.CompilerServices;
-
- [Serializable]
- public abstract class MethodInfo : MethodBase
- {
- #region Constructor
- protected MethodInfo() { }
- #endregion
-
- public static bool operator ==(MethodInfo left, MethodInfo right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimeMethodInfo || right is RuntimeMethodInfo)
- {
- return false;
- }
- return left.Equals(right);
- }
-
- public static bool operator !=(MethodInfo left, MethodInfo right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Method; } }
- #endregion
-
- #region Public Abstract\Virtual Members
- public virtual Type ReturnType { get { throw new NotImplementedException(); } }
-
- public virtual ParameterInfo ReturnParameter { get { throw new NotImplementedException(); } }
-
- public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; }
-
- public abstract MethodInfo GetBaseDefinition();
-
- public override Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
-
- public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
-
- public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
-
- public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
- public virtual Delegate CreateDelegate(Type delegateType, Object target) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); }
- #endregion
- }
-
[Serializable]
internal sealed class RuntimeMethodInfo : MethodInfo, ISerializable, IRuntimeMethodInfo
{
#region Private Data Members
- private IntPtr m_handle;
+ private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
private string m_name;
private string m_toString;
@@ -98,37 +31,6 @@ namespace System.Reflection
private object m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
-#if FEATURE_APPX
- private bool IsNonW8PFrameworkAPI()
- {
- if (m_declaringType.IsArray && IsPublic && !IsStatic)
- return false;
-
- RuntimeAssembly rtAssembly = GetRuntimeAssembly();
- if (rtAssembly.IsFrameworkAssembly())
- {
- int ctorToken = rtAssembly.InvocableAttributeCtorToken;
- if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
- !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
- return true;
- }
-
- if (GetRuntimeType().IsNonW8PFrameworkAPI())
- return true;
-
- if (IsGenericMethod && !IsGenericMethodDefinition)
- {
- foreach (Type t in GetGenericArguments())
- {
- if (((RuntimeType)t).IsNonW8PFrameworkAPI())
- return true;
- }
- }
-
- return false;
- }
-#endif
-
internal INVOCATION_FLAGS InvocationFlags
{
get
@@ -157,8 +59,8 @@ namespace System.Reflection
if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0)
{
- if ( (Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
- (declaringType != null && declaringType.NeedsReflectionSecurityCheck) )
+ 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;
@@ -179,11 +81,6 @@ namespace System.Reflection
}
}
-#if FEATURE_APPX
- if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
-#endif // FEATURE_APPX
-
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
@@ -194,13 +91,13 @@ namespace System.Reflection
#region Constructor
internal RuntimeMethodInfo(
- RuntimeMethodHandleInternal handle, RuntimeType declaringType,
+ RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive)
{
Contract.Ensures(!m_handle.IsNull());
Debug.Assert(!handle.IsNullHandle());
- Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
+ Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
@@ -221,11 +118,11 @@ namespace System.Reflection
}
private RuntimeType ReflectedTypeInternal
- {
- get
- {
- return m_reflectedTypeCache.GetRuntimeType();
- }
+ {
+ get
+ {
+ return m_reflectedTypeCache.GetRuntimeType();
+ }
}
private ParameterInfo[] FetchNonReturnParameters()
@@ -265,15 +162,15 @@ namespace System.Reflection
return sbName.ToString();
}
- internal override bool CacheEquals(object o)
- {
+ internal override bool CacheEquals(object o)
+ {
RuntimeMethodInfo m = o as RuntimeMethodInfo;
if ((object)m == null)
return false;
return m.m_handle == m_handle;
- }
+ }
internal Signature Signature
{
@@ -315,7 +212,7 @@ namespace System.Reflection
#endregion
#region Object Overrides
- public override String ToString()
+ public override String ToString()
{
if (m_toString == null)
m_toString = ReturnType.FormatTypeName() + " " + FormatNameAndSig();
@@ -389,8 +286,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
@@ -403,8 +300,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
@@ -416,7 +313,7 @@ namespace System.Reflection
#endregion
#region MemberInfo Overrides
- public override String Name
+ public override String Name
{
get
{
@@ -427,7 +324,7 @@ namespace System.Reflection
}
}
- public override Type DeclaringType
+ public override Type DeclaringType
{
get
{
@@ -438,7 +335,7 @@ namespace System.Reflection
}
}
- public override Type ReflectedType
+ public override Type ReflectedType
{
get
{
@@ -453,13 +350,13 @@ namespace System.Reflection
public override int MetadataToken
{
get { return RuntimeMethodHandle.GetMethodDef(this); }
- }
+ }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
- public override bool IsSecurityCritical
+ public override bool IsSecurityCritical
{
get { return true; }
}
@@ -471,9 +368,9 @@ namespace System.Reflection
{
get { return false; }
}
-#endregion
+ #endregion
-#region MethodBase Overrides
+ #region MethodBase Overrides
internal override ParameterInfo[] GetParametersNoCopy()
{
FetchNonReturnParameters();
@@ -501,48 +398,48 @@ namespace System.Reflection
return RuntimeMethodHandle.GetImplAttributes(this);
}
- public override RuntimeMethodHandle MethodHandle
- {
- get
- {
+ public override RuntimeMethodHandle MethodHandle
+ {
+ get
+ {
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
- return new RuntimeMethodHandle(this);
- }
+ throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
+ return new RuntimeMethodHandle(this);
+ }
}
public override MethodAttributes Attributes { get { return m_methodAttributes; } }
-
- public override CallingConventions CallingConvention
- {
- get
- {
- return Signature.CallingConvention;
- }
+
+ public override CallingConventions CallingConvention
+ {
+ get
+ {
+ return Signature.CallingConvention;
+ }
}
public override MethodBody GetMethodBody()
{
MethodBody mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
- if (mb != null)
+ if (mb != null)
mb.m_methodBase = this;
return mb;
- }
-#endregion
+ }
+ #endregion
-#region Invocation Logic(On MemberBase)
- private void CheckConsistency(Object target)
+ #region Invocation Logic(On MemberBase)
+ private void CheckConsistency(Object target)
{
// only test instance methods
- if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
+ if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
- if (target == null)
- throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatMethReqTarg"));
+ if (target == null)
+ throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg);
else
- throw new TargetException(Environment.GetResourceString("RFLCT.Targ_ITargMismatch"));
+ throw new TargetException(SR.RFLCT_Targ_ITargMismatch);
}
}
}
@@ -553,7 +450,7 @@ namespace System.Reflection
Type declaringType = DeclaringType;
if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType)
{
- throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
+ throw new InvalidOperationException(SR.Arg_ReflectionOnlyInvoke);
}
// method is on a class that contains stack pointers
else if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
@@ -568,7 +465,7 @@ namespace System.Reflection
// method is generic or on a generic class
else if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters)
{
- throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenParam"));
+ throw new InvalidOperationException(SR.Arg_UnboundGenParam);
}
// method is abstract class
else if (IsAbstract)
@@ -578,33 +475,19 @@ namespace System.Reflection
// ByRef return are not allowed in reflection
else if (ReturnType.IsByRef)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ByRefReturn"));
+ throw new NotSupportedException(SR.NotSupported_ByRefReturn);
}
throw new TargetException();
}
-
+
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
-#region Security Check
- INVOCATION_FLAGS invocationFlags = InvocationFlags;
-
-#if FEATURE_APPX
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName));
- }
-#endif
-#endregion
-
return UnsafeInvokeInternal(obj, parameters, arguments);
}
@@ -657,7 +540,7 @@ namespace System.Reflection
CheckConsistency(obj);
if (formalCount != actualCount)
- throw new TargetParameterCountException(Environment.GetResourceString("Arg_ParmCnt"));
+ throw new TargetParameterCountException(SR.Arg_ParmCnt);
if (actualCount != 0)
return CheckArguments(parameters, binder, invokeAttr, culture, sig);
@@ -665,20 +548,20 @@ namespace System.Reflection
return null;
}
-#endregion
+ #endregion
-#region MethodInfo Overrides
- public override Type ReturnType
- {
- get { return Signature.ReturnType; }
+ #region MethodInfo Overrides
+ public override Type ReturnType
+ {
+ get { return Signature.ReturnType; }
}
- public override ICustomAttributeProvider ReturnTypeCustomAttributes
- {
- get { return ReturnParameter; }
+ public override ICustomAttributeProvider ReturnTypeCustomAttributes
+ {
+ get { return ReturnParameter; }
}
- public override ParameterInfo ReturnParameter
+ public override ParameterInfo ReturnParameter
{
get
{
@@ -699,7 +582,8 @@ namespace System.Reflection
RuntimeType baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
- do {
+ do
+ {
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
@@ -711,7 +595,7 @@ namespace System.Reflection
declaringType = (RuntimeType)declaringType.BaseType;
} while (declaringType != null);
- return(MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
+ return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle);
}
public override Delegate CreateDelegate(Type delegateType)
@@ -758,34 +642,34 @@ namespace System.Reflection
RuntimeType rtType = delegateType as RuntimeType;
if (rtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(delegateType));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType));
if (!rtType.IsDelegate())
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(delegateType));
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(delegateType));
Delegate d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags, ref stackMark);
if (d == null)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));
+ throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
return d;
}
-#endregion
+ #endregion
-#region Generics
+ #region Generics
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
- if (methodInstantiation == null)
+ if (methodInstantiation == null)
throw new ArgumentNullException(nameof(methodInstantiation));
- Contract.EndContractBlock();
+ Contract.EndContractBlock();
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(
- Environment.GetResourceString("Arg_NotGenericMethodDefinition", this));
+ SR.Format(SR.Arg_NotGenericMethodDefinition, this));
for (int i = 0; i < methodInstantiation.Length; i++)
{
@@ -813,18 +697,18 @@ namespace System.Reflection
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
MethodInfo ret = null;
-
+
try
{
ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
- RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(this.m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
+ RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
}
catch (VerificationException e)
{
RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
throw;
}
-
+
return ret;
}
@@ -833,23 +717,23 @@ namespace System.Reflection
return RuntimeMethodHandle.GetMethodInstantiationInternal(this);
}
- public override Type[] GetGenericArguments()
+ public override Type[] GetGenericArguments()
{
Type[] types = RuntimeMethodHandle.GetMethodInstantiationPublic(this);
if (types == null)
{
- types = EmptyArray<Type>.Value;
+ types = Array.Empty<Type>();
}
return types;
}
- public override MethodInfo GetGenericMethodDefinition()
+ public override MethodInfo GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
Contract.EndContractBlock();
-
+
return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo;
}
@@ -861,11 +745,11 @@ namespace System.Reflection
public override bool IsGenericMethodDefinition
{
get { return RuntimeMethodHandle.IsGenericMethodDefinition(this); }
- }
+ }
- public override bool ContainsGenericParameters
- {
- get
+ public override bool ContainsGenericParameters
+ {
+ get
{
if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
return true;
@@ -873,7 +757,7 @@ namespace System.Reflection
if (!IsGenericMethod)
return false;
- Type[] pis = GetGenericArguments();
+ Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
@@ -881,11 +765,11 @@ namespace System.Reflection
}
return false;
- }
+ }
}
-#endregion
+ #endregion
-#region ISerializable Implementation
+ #region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
@@ -893,34 +777,27 @@ namespace System.Reflection
Contract.EndContractBlock();
if (m_reflectedTypeCache.IsGlobal)
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
+ throw new NotSupportedException(SR.NotSupported_GlobalMethodSerialization);
- MemberInfoSerializationHolder.GetSerializationInfo(
- info,
- Name,
- ReflectedTypeInternal,
- ToString(),
- SerializationToString(),
- MemberTypes.Method,
- IsGenericMethod & !IsGenericMethodDefinition ? GetGenericArguments() : null);
+ MemberInfoSerializationHolder.GetSerializationInfo(info, this);
}
internal string SerializationToString()
{
return ReturnType.FormatTypeName(true) + " " + FormatNameAndSig(true);
}
-#endregion
+ #endregion
-#region Legacy Internal
+ #region Legacy Internal
internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
- if (method == null)
+ if (method == null)
return null;
-
+
return RuntimeType.GetMethodBase(method);
}
-#endregion
+ #endregion
}
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeModule.cs b/src/mscorlib/src/System/Reflection/RuntimeModule.cs
new file mode 100644
index 0000000000..75809cba01
--- /dev/null
+++ b/src/mscorlib/src/System/Reflection/RuntimeModule.cs
@@ -0,0 +1,602 @@
+// 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.Runtime.Serialization;
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using System.Security;
+using System.Globalization;
+using System.Diagnostics.Contracts;
+
+namespace System.Reflection
+{
+ [Serializable]
+ internal class RuntimeModule : Module
+ {
+ internal RuntimeModule() { throw new NotSupportedException(); }
+
+ #region FCalls
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private extern static void GetType(RuntimeModule module, String className, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive);
+
+ [DllImport(JitHelpers.QCall)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern bool nIsTransientInternal(RuntimeModule module);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private extern static void GetScopeName(RuntimeModule module, StringHandleOnStack retString);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private extern static void GetFullyQualifiedName(RuntimeModule module, StringHandleOnStack retString);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern static RuntimeType[] GetTypes(RuntimeModule module);
+
+ internal RuntimeType[] GetDefinedTypes()
+ {
+ return GetTypes(GetNativeHandle());
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern static bool IsResource(RuntimeModule module);
+ #endregion
+
+ #region Module overrides
+ private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments)
+ {
+ if (genericArguments == null)
+ return null;
+
+ int size = genericArguments.Length;
+ RuntimeTypeHandle[] typeHandleArgs = new RuntimeTypeHandle[size];
+ for (int i = 0; i < size; i++)
+ {
+ Type typeArg = genericArguments[i];
+ if (typeArg == null)
+ throw new ArgumentException(SR.Argument_InvalidGenericInstArray);
+ typeArg = typeArg.UnderlyingSystemType;
+ if (typeArg == null)
+ throw new ArgumentException(SR.Argument_InvalidGenericInstArray);
+ if (!(typeArg is RuntimeType))
+ throw new ArgumentException(SR.Argument_InvalidGenericInstArray);
+ typeHandleArgs[i] = typeArg.GetTypeHandleInternal();
+ }
+ return typeHandleArgs;
+ }
+
+ public override byte[] ResolveSignature(int metadataToken)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+
+ if (!MetadataImport.IsValidToken(tk))
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ SR.Format(SR.Argument_InvalidToken, tk, this));
+
+ if (!tk.IsMemberRef && !tk.IsMethodDef && !tk.IsTypeSpec && !tk.IsSignature && !tk.IsFieldDef)
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidToken, tk, this),
+ nameof(metadataToken));
+
+ ConstArray signature;
+ if (tk.IsMemberRef)
+ signature = MetadataImport.GetMemberRefProps(metadataToken);
+ else
+ signature = MetadataImport.GetSignatureFromToken(metadataToken);
+
+ byte[] sig = new byte[signature.Length];
+
+ for (int i = 0; i < signature.Length; i++)
+ sig[i] = signature[i];
+
+ return sig;
+ }
+
+ public override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+
+ if (!MetadataImport.IsValidToken(tk))
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ SR.Format(SR.Argument_InvalidToken, tk, this));
+
+ RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
+ RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
+
+ try
+ {
+ if (!tk.IsMethodDef && !tk.IsMethodSpec)
+ {
+ if (!tk.IsMemberRef)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, tk, this),
+ nameof(metadataToken));
+
+ unsafe
+ {
+ ConstArray sig = MetadataImport.GetMemberRefProps(tk);
+
+ if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, tk, this),
+ nameof(metadataToken));
+ }
+ }
+
+ IRuntimeMethodInfo methodHandle = ModuleHandle.ResolveMethodHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
+ Type declaringType = RuntimeMethodHandle.GetDeclaringType(methodHandle);
+
+ if (declaringType.IsGenericType || declaringType.IsArray)
+ {
+ MetadataToken tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tk));
+
+ if (tk.IsMethodSpec)
+ tkDeclaringType = new MetadataToken(MetadataImport.GetParentToken(tkDeclaringType));
+
+ declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
+ }
+
+ return System.RuntimeType.GetMethodBase(declaringType as RuntimeType, methodHandle);
+ }
+ catch (BadImageFormatException e)
+ {
+ throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
+ }
+ }
+
+ private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+
+ if (!MetadataImport.IsValidToken(tk) || !tk.IsFieldDef)
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ String.Format(CultureInfo.CurrentUICulture, SR.Format(SR.Argument_InvalidToken, tk, this)));
+
+ int tkDeclaringType;
+ string fieldName;
+
+ fieldName = MetadataImport.GetName(tk).ToString();
+ tkDeclaringType = MetadataImport.GetParentToken(tk);
+
+ Type declaringType = ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
+
+ declaringType.GetFields();
+
+ try
+ {
+ return declaringType.GetField(fieldName,
+ BindingFlags.Static | BindingFlags.Instance |
+ BindingFlags.Public | BindingFlags.NonPublic |
+ BindingFlags.DeclaredOnly);
+ }
+ catch
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this), nameof(metadataToken));
+ }
+ }
+
+ public override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+
+ if (!MetadataImport.IsValidToken(tk))
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ SR.Format(SR.Argument_InvalidToken, tk, this));
+
+ RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
+ RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
+
+ try
+ {
+ IRuntimeFieldInfo fieldHandle = null;
+
+ if (!tk.IsFieldDef)
+ {
+ if (!tk.IsMemberRef)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this),
+ nameof(metadataToken));
+
+ unsafe
+ {
+ ConstArray sig = MetadataImport.GetMemberRefProps(tk);
+
+ if (*(MdSigCallingConvention*)sig.Signature.ToPointer() != MdSigCallingConvention.Field)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveField, tk, this),
+ nameof(metadataToken));
+ }
+
+ fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), tk, typeArgs, methodArgs);
+ }
+
+ fieldHandle = ModuleHandle.ResolveFieldHandleInternal(GetNativeHandle(), metadataToken, typeArgs, methodArgs);
+ RuntimeType declaringType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle.Value);
+
+ if (declaringType.IsGenericType || declaringType.IsArray)
+ {
+ int tkDeclaringType = ModuleHandle.GetMetadataImport(GetNativeHandle()).GetParentToken(metadataToken);
+ declaringType = (RuntimeType)ResolveType(tkDeclaringType, genericTypeArguments, genericMethodArguments);
+ }
+
+ return System.RuntimeType.GetFieldInfo(declaringType, fieldHandle);
+ }
+ catch (MissingFieldException)
+ {
+ return ResolveLiteralField(tk, genericTypeArguments, genericMethodArguments);
+ }
+ catch (BadImageFormatException e)
+ {
+ throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
+ }
+ }
+
+ public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+
+ if (tk.IsGlobalTypeDefToken)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveModuleType, tk), nameof(metadataToken));
+
+ if (!MetadataImport.IsValidToken(tk))
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ SR.Format(SR.Argument_InvalidToken, tk, this));
+
+ if (!tk.IsTypeDef && !tk.IsTypeSpec && !tk.IsTypeRef)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken));
+
+ RuntimeTypeHandle[] typeArgs = ConvertToTypeHandleArray(genericTypeArguments);
+ RuntimeTypeHandle[] methodArgs = ConvertToTypeHandleArray(genericMethodArguments);
+
+ try
+ {
+ Type t = GetModuleHandleImpl().ResolveTypeHandle(metadataToken, typeArgs, methodArgs).GetRuntimeType();
+
+ if (t == null)
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveType, tk, this), nameof(metadataToken));
+
+ return t;
+ }
+ catch (BadImageFormatException e)
+ {
+ throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, e);
+ }
+ }
+
+ public override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+
+ if (tk.IsProperty)
+ throw new ArgumentException(SR.InvalidOperation_PropertyInfoNotAvailable);
+
+ if (tk.IsEvent)
+ throw new ArgumentException(SR.InvalidOperation_EventInfoNotAvailable);
+
+ if (tk.IsMethodSpec || tk.IsMethodDef)
+ return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments);
+
+ if (tk.IsFieldDef)
+ return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments);
+
+ if (tk.IsTypeRef || tk.IsTypeDef || tk.IsTypeSpec)
+ return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments);
+
+ if (tk.IsMemberRef)
+ {
+ if (!MetadataImport.IsValidToken(tk))
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ SR.Format(SR.Argument_InvalidToken, tk, this));
+
+ ConstArray sig = MetadataImport.GetMemberRefProps(tk);
+
+ unsafe
+ {
+ if (*(MdSigCallingConvention*)sig.Signature.ToPointer() == MdSigCallingConvention.Field)
+ {
+ return ResolveField(tk, genericTypeArguments, genericMethodArguments);
+ }
+ else
+ {
+ return ResolveMethod(tk, genericTypeArguments, genericMethodArguments);
+ }
+ }
+ }
+
+ throw new ArgumentException(SR.Format(SR.Argument_ResolveMember, tk, this),
+ nameof(metadataToken));
+ }
+
+ public override string ResolveString(int metadataToken)
+ {
+ MetadataToken tk = new MetadataToken(metadataToken);
+ if (!tk.IsString)
+ throw new ArgumentException(
+ String.Format(CultureInfo.CurrentUICulture, SR.Argument_ResolveString, metadataToken, ToString()));
+
+ if (!MetadataImport.IsValidToken(tk))
+ throw new ArgumentOutOfRangeException(nameof(metadataToken),
+ String.Format(CultureInfo.CurrentUICulture, SR.Format(SR.Argument_InvalidToken, tk, this)));
+
+ string str = MetadataImport.GetUserString(metadataToken);
+
+ if (str == null)
+ throw new ArgumentException(
+ String.Format(CultureInfo.CurrentUICulture, SR.Argument_ResolveString, metadataToken, ToString()));
+
+ return str;
+ }
+
+ public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine)
+ {
+ ModuleHandle.GetPEKind(GetNativeHandle(), out peKind, out machine);
+ }
+
+ public override int MDStreamVersion
+ {
+ get
+ {
+ return ModuleHandle.GetMDStreamVersion(GetNativeHandle());
+ }
+ }
+ #endregion
+
+ #region Data Members
+#pragma warning disable 169
+ // If you add any data members, you need to update the native declaration ReflectModuleBaseObject.
+ private RuntimeType m_runtimeType;
+ private RuntimeAssembly m_runtimeAssembly;
+ private IntPtr m_pRefClass;
+ private IntPtr m_pData;
+ private IntPtr m_pGlobals;
+ private IntPtr m_pFields;
+#pragma warning restore 169
+ #endregion
+
+ #region Protected Virtuals
+ protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ {
+ return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers);
+ }
+
+ internal MethodInfo GetMethodInternal(String name, BindingFlags bindingAttr, Binder binder,
+ CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ {
+ if (RuntimeType == null)
+ return null;
+
+ if (types == null)
+ {
+ return RuntimeType.GetMethod(name, bindingAttr);
+ }
+ else
+ {
+ return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers);
+ }
+ }
+ #endregion
+
+ #region Internal Members
+ internal RuntimeType RuntimeType
+ {
+ get
+ {
+ if (m_runtimeType == null)
+ m_runtimeType = ModuleHandle.GetModuleType(GetNativeHandle());
+
+ return m_runtimeType;
+ }
+ }
+
+ internal bool IsTransientInternal()
+ {
+ return RuntimeModule.nIsTransientInternal(this.GetNativeHandle());
+ }
+
+ internal MetadataImport MetadataImport
+ {
+ get
+ {
+ unsafe
+ {
+ return ModuleHandle.GetMetadataImport(GetNativeHandle());
+ }
+ }
+ }
+ #endregion
+
+ #region ICustomAttributeProvider Members
+ public override Object[] GetCustomAttributes(bool inherit)
+ {
+ return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
+ }
+
+ public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
+ {
+ if (attributeType == null)
+ throw new ArgumentNullException(nameof(attributeType));
+ Contract.EndContractBlock();
+
+ RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
+
+ return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
+ }
+
+ public override bool IsDefined(Type attributeType, bool inherit)
+ {
+ if (attributeType == null)
+ throw new ArgumentNullException(nameof(attributeType));
+ Contract.EndContractBlock();
+
+ RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
+
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
+
+ return CustomAttribute.IsDefined(this, attributeRuntimeType);
+ }
+
+ public override IList<CustomAttributeData> GetCustomAttributesData()
+ {
+ return CustomAttributeData.GetCustomAttributesInternal(this);
+ }
+ #endregion
+
+ #region Public Virtuals
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+ Contract.EndContractBlock();
+ UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.ModuleUnity, this.ScopeName, this.GetRuntimeAssembly());
+ }
+
+ public override Type GetType(String className, bool throwOnError, bool ignoreCase)
+ {
+ // throw on null strings regardless of the value of "throwOnError"
+ if (className == null)
+ throw new ArgumentNullException(nameof(className));
+
+ RuntimeType retType = null;
+ Object keepAlive = null;
+ GetType(GetNativeHandle(), className, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref retType), JitHelpers.GetObjectHandleOnStack(ref keepAlive));
+ GC.KeepAlive(keepAlive);
+ return retType;
+ }
+
+ internal string GetFullyQualifiedName()
+ {
+ String fullyQualifiedName = null;
+ GetFullyQualifiedName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref fullyQualifiedName));
+ return fullyQualifiedName;
+ }
+
+ public override String FullyQualifiedName
+ {
+ get
+ {
+ return GetFullyQualifiedName();
+ }
+ }
+
+ public override Type[] GetTypes()
+ {
+ return GetTypes(GetNativeHandle());
+ }
+
+ #endregion
+
+ #region Public Members
+
+ public override Guid ModuleVersionId
+ {
+ get
+ {
+ unsafe
+ {
+ Guid mvid;
+ MetadataImport.GetScopeProps(out mvid);
+ return mvid;
+ }
+ }
+ }
+
+ public override int MetadataToken
+ {
+ get
+ {
+ return ModuleHandle.GetToken(GetNativeHandle());
+ }
+ }
+
+ public override bool IsResource()
+ {
+ return IsResource(GetNativeHandle());
+ }
+
+ public override FieldInfo[] GetFields(BindingFlags bindingFlags)
+ {
+ if (RuntimeType == null)
+ return new FieldInfo[0];
+
+ return RuntimeType.GetFields(bindingFlags);
+ }
+
+ public override FieldInfo GetField(String name, BindingFlags bindingAttr)
+ {
+ if (name == null)
+ throw new ArgumentNullException(nameof(name));
+
+ if (RuntimeType == null)
+ return null;
+
+ return RuntimeType.GetField(name, bindingAttr);
+ }
+
+ public override MethodInfo[] GetMethods(BindingFlags bindingFlags)
+ {
+ if (RuntimeType == null)
+ return new MethodInfo[0];
+
+ return RuntimeType.GetMethods(bindingFlags);
+ }
+
+ public override String ScopeName
+ {
+ get
+ {
+ string scopeName = null;
+ GetScopeName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref scopeName));
+ return scopeName;
+ }
+ }
+
+ public override String Name
+ {
+ get
+ {
+ String s = GetFullyQualifiedName();
+
+#if !FEATURE_PAL
+ int i = s.LastIndexOf('\\');
+#else
+ int i = s.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
+#endif
+ if (i == -1)
+ return s;
+
+ return s.Substring(i + 1);
+ }
+ }
+
+ public override Assembly Assembly
+ {
+ [Pure]
+ get
+ {
+ return GetRuntimeAssembly();
+ }
+ }
+
+ internal RuntimeAssembly GetRuntimeAssembly()
+ {
+ return m_runtimeAssembly;
+ }
+
+ protected override ModuleHandle GetModuleHandleImpl()
+ {
+ return new ModuleHandle(this);
+ }
+
+ internal RuntimeModule GetNativeHandle()
+ {
+ return this;
+ }
+ #endregion
+ }
+}
diff --git a/src/mscorlib/src/System/Reflection/ParameterInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
index fad4402aff..addf68e75d 100644
--- a/src/mscorlib/src/System/Reflection/ParameterInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
@@ -2,232 +2,15 @@
// 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.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Runtime.Serialization;
+using System.Runtime.CompilerServices;
+using MdToken = System.Reflection.MetadataToken;
namespace System.Reflection
{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
- using System.Threading;
- using MdToken = System.Reflection.MetadataToken;
-
- [Serializable]
- public class ParameterInfo : ICustomAttributeProvider, IObjectReference
- {
- #region Legacy Protected Members
- protected String NameImpl;
- protected Type ClassImpl;
- protected int PositionImpl;
- protected ParameterAttributes AttrsImpl;
- protected Object DefaultValueImpl; // cannot cache this as it may be non agile user defined enum
- protected MemberInfo MemberImpl;
- #endregion
-
- #region Legacy Private Members
- // These are here only for backwards compatibility -- they are not set
- // until this instance is serialized, so don't rely on their values from
- // arbitrary code.
-#pragma warning disable 169
- [OptionalField]
- private IntPtr _importer;
- [OptionalField]
- private int _token;
- [OptionalField]
- private bool bExtraConstChecked;
-#pragma warning restore 169
- #endregion
-
- #region Constructor
- protected ParameterInfo()
- {
- }
- #endregion
-
- #region Internal Members
- // this is an internal api for DynamicMethod. A better solution is to change the relationship
- // between ParameterInfo and ParameterBuilder so that a ParameterBuilder can be seen as a writer
- // api over a ParameterInfo. However that is a possible breaking change so it needs to go through some process first
- internal void SetName(String name)
- {
- NameImpl = name;
- }
-
- internal void SetAttributes(ParameterAttributes attributes)
- {
- AttrsImpl = attributes;
- }
- #endregion
-
- #region Public Methods
- public virtual Type ParameterType
- {
- get
- {
- return ClassImpl;
- }
- }
-
- public virtual String Name
- {
- get
- {
- return NameImpl;
- }
- }
-
- public virtual bool HasDefaultValue { get { throw new NotImplementedException(); } }
-
- public virtual Object DefaultValue { get { throw new NotImplementedException(); } }
- public virtual Object RawDefaultValue { get { throw new NotImplementedException(); } }
-
- public virtual int Position { get { return PositionImpl; } }
- public virtual ParameterAttributes Attributes { get { return AttrsImpl; } }
-
- public virtual MemberInfo Member {
- get {
- Contract.Ensures(Contract.Result<MemberInfo>() != null);
- return MemberImpl;
- }
- }
-
- public bool IsIn { get { return((Attributes & ParameterAttributes.In) != 0); } }
- public bool IsOut { get { return((Attributes & ParameterAttributes.Out) != 0); } }
- public bool IsLcid { get { return((Attributes & ParameterAttributes.Lcid) != 0); } }
- public bool IsRetval { get { return((Attributes & ParameterAttributes.Retval) != 0); } }
- public bool IsOptional { get { return((Attributes & ParameterAttributes.Optional) != 0); } }
-
- public virtual int MetadataToken
- {
- get
- {
- // This API was made virtual in V4. Code compiled against V2 might use
- // "call" rather than "callvirt" to call it.
- // This makes sure those code still works.
- RuntimeParameterInfo rtParam = this as RuntimeParameterInfo;
- if (rtParam != null)
- return rtParam.MetadataToken;
-
- // return a null token
- return (int)MetadataTokenType.ParamDef;
- }
- }
-
- public virtual Type[] GetRequiredCustomModifiers()
- {
- return EmptyArray<Type>.Value;
- }
-
- public virtual Type[] GetOptionalCustomModifiers()
- {
- return EmptyArray<Type>.Value;
- }
- #endregion
-
- #region Object Overrides
- public override String ToString()
- {
- return ParameterType.FormatTypeName() + " " + Name;
- }
- #endregion
-
- public virtual IEnumerable<CustomAttributeData> CustomAttributes
- {
- get
- {
- return GetCustomAttributesData();
- }
- }
- #region ICustomAttributeProvider
- public virtual Object[] GetCustomAttributes(bool inherit)
- {
- return EmptyArray<Object>.Value;
- }
-
- public virtual Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- return EmptyArray<Object>.Value;
- }
-
- public virtual bool IsDefined(Type attributeType, bool inherit)
- {
- if (attributeType == null)
- throw new ArgumentNullException(nameof(attributeType));
- Contract.EndContractBlock();
-
- return false;
- }
-
- public virtual IList<CustomAttributeData> GetCustomAttributesData()
- {
- throw new NotImplementedException();
- }
- #endregion
-
- #region _ParameterInfo implementation
-
- #endregion
-
- #region IObjectReference
- // In V4 RuntimeParameterInfo is introduced.
- // To support deserializing ParameterInfo instances serialized in earlier versions
- // we need to implement IObjectReference.
- public object GetRealObject(StreamingContext context)
- {
- Contract.Ensures(Contract.Result<Object>() != null);
-
- // Once all the serializable fields have come in we can set up the real
- // instance based on just two of them (MemberImpl and PositionImpl).
-
- if (MemberImpl == null)
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_InsufficientState));
-
- ParameterInfo[] args = null;
-
- switch (MemberImpl.MemberType)
- {
- case MemberTypes.Constructor:
- case MemberTypes.Method:
- if (PositionImpl == -1)
- {
- if (MemberImpl.MemberType == MemberTypes.Method)
- return ((MethodInfo)MemberImpl).ReturnParameter;
- else
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_BadParameterInfo));
- }
- else
- {
- args = ((MethodBase)MemberImpl).GetParametersNoCopy();
-
- if (args != null && PositionImpl < args.Length)
- return args[PositionImpl];
- else
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_BadParameterInfo));
- }
-
- case MemberTypes.Property:
- args = ((RuntimePropertyInfo)MemberImpl).GetIndexParametersNoCopy();
-
- if (args != null && PositionImpl > -1 && PositionImpl < args.Length)
- return args[PositionImpl];
- else
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_BadParameterInfo));
-
- default:
- throw new SerializationException(Environment.GetResourceString(ResId.Serialization_NoParameterInfo));
- }
- }
- #endregion
- }
-
[Serializable]
internal unsafe sealed class RuntimeParameterInfo : ParameterInfo, ISerializable
{
@@ -273,7 +56,7 @@ namespace System.Reflection
// Not all parameters have tokens. Parameters may have no token
// if they have no name and no attributes.
if (cParamDefs > sigArgCount + 1 /* return type */)
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch"));
+ throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
for (int i = 0; i < cParamDefs; i++)
{
@@ -289,7 +72,7 @@ namespace System.Reflection
{
// more than one return parameter?
if (returnParameter != null)
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch"));
+ throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
returnParameter = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member);
}
@@ -297,7 +80,7 @@ namespace System.Reflection
{
// position beyong sigArgCount?
if (position >= sigArgCount)
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ParameterSignatureMismatch"));
+ throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch);
args[position] = new RuntimeParameterInfo(sig, scope, tkParamDef, position, attr, member);
}
@@ -366,6 +149,18 @@ namespace System.Reflection
}
#endregion
+ #region Internal Methods
+ internal void SetName(string name)
+ {
+ NameImpl = name;
+ }
+
+ internal void SetAttributes(ParameterAttributes attributes)
+ {
+ AttrsImpl = attributes;
+ }
+ #endregion
+
#region VTS magic to serialize/deserialized to/from pre-Whidbey endpoints.
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
@@ -413,7 +208,7 @@ namespace System.Reflection
{
// Change ownership
MemberImpl = member;
-
+
// The original owner should always be a method, because this method is only used to
// change the owner from a method to a property.
m_originalMember = accessor.MemberImpl as MethodBase;
@@ -665,7 +460,7 @@ namespace System.Reflection
{
get
{
- return m_tkParamDef;
+ return m_tkParamDef;
}
}
@@ -685,7 +480,7 @@ namespace System.Reflection
public override Object[] GetCustomAttributes(bool inherit)
{
if (MdToken.IsNullToken(m_tkParamDef))
- return EmptyArray<Object>.Value;
+ return Array.Empty<Object>();
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
@@ -697,12 +492,12 @@ namespace System.Reflection
Contract.EndContractBlock();
if (MdToken.IsNullToken(m_tkParamDef))
- return EmptyArray<Object>.Value;
+ return Array.Empty<Object>();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -719,7 +514,7 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(attributeType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
diff --git a/src/mscorlib/src/System/Reflection/PropertyInfo.cs b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs
index e8c2837785..b6a4792e4f 100644
--- a/src/mscorlib/src/System/Reflection/PropertyInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimePropertyInfo.cs
@@ -2,152 +2,16 @@
// 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.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.Serialization;
+using System.Text;
+using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Text;
- using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
-
- [Serializable]
- public abstract class PropertyInfo : MemberInfo
- {
- #region Constructor
- protected PropertyInfo() { }
- #endregion
-
- public static bool operator ==(PropertyInfo left, PropertyInfo right)
- {
- if (ReferenceEquals(left, right))
- return true;
-
- if ((object)left == null || (object)right == null ||
- left is RuntimePropertyInfo || right is RuntimePropertyInfo)
- {
- return false;
- }
- return left.Equals(right);
- }
-
- public static bool operator !=(PropertyInfo left, PropertyInfo right)
- {
- return !(left == right);
- }
-
- public override bool Equals(object obj)
- {
- return base.Equals(obj);
- }
-
- public override int GetHashCode()
- {
- return base.GetHashCode();
- }
-
- #region MemberInfo Overrides
- public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } }
- #endregion
-
- #region Public Abstract\Virtual Members
- public virtual object GetConstantValue()
- {
- throw new NotImplementedException();
- }
-
- public virtual object GetRawConstantValue()
- {
- throw new NotImplementedException();
- }
-
- public abstract Type PropertyType { get; }
-
- public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
-
- public abstract MethodInfo[] GetAccessors(bool nonPublic);
-
- public abstract MethodInfo GetGetMethod(bool nonPublic);
-
- public abstract MethodInfo GetSetMethod(bool nonPublic);
-
- public abstract ParameterInfo[] GetIndexParameters();
-
- public abstract PropertyAttributes Attributes { get; }
-
- public abstract bool CanRead { get; }
-
- public abstract bool CanWrite { get; }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public Object GetValue(Object obj)
- {
- return GetValue(obj, null);
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public virtual Object GetValue(Object obj,Object[] index)
- {
- return GetValue(obj, BindingFlags.Default, null, index, null);
- }
-
- public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public void SetValue(Object obj, Object value)
- {
- SetValue(obj, value, null);
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public virtual void SetValue(Object obj, Object value, Object[] index)
- {
- SetValue(obj, value, BindingFlags.Default, null, index, null);
- }
- #endregion
-
- #region Public Members
- public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; }
-
- public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; }
-
- public MethodInfo[] GetAccessors() { return GetAccessors(false); }
-
- public virtual MethodInfo GetMethod
- {
- get
- {
- return GetGetMethod(true);
- }
- }
-
- public virtual MethodInfo SetMethod
- {
- get
- {
- return GetSetMethod(true);
- }
- }
-
- public MethodInfo GetGetMethod() { return GetGetMethod(false); }
-
- public MethodInfo GetSetMethod() { return GetSetMethod(false); }
-
- public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
- #endregion
- }
-
[Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable
{
@@ -177,14 +41,14 @@ namespace System.Reflection
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkProperty;
- m_reflectedTypeCache = reflectedTypeCache;
+ m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
RuntimeMethodInfo dummy;
- Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
+ Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
out isPrivate, out m_bindingFlags);
@@ -297,8 +161,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
@@ -311,8 +175,8 @@ namespace System.Reflection
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
@@ -325,21 +189,21 @@ namespace System.Reflection
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
- public override String Name
+ public override String Name
{
- get
+ get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
-
- return m_name;
- }
- }
- public override Type DeclaringType
- {
- get
- {
- return m_declaringType;
+
+ return m_name;
+ }
+ }
+ public override Type DeclaringType
+ {
+ get
+ {
+ return m_declaringType;
}
}
@@ -358,9 +222,9 @@ namespace System.Reflection
return m_reflectedTypeCache.GetRuntimeType();
}
}
-
+
public override int MetadataToken { get { return m_token; } }
-
+
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
@@ -373,7 +237,7 @@ namespace System.Reflection
{
return Signature.GetCustomModifiers(0, true);
}
-
+
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
@@ -382,19 +246,19 @@ namespace System.Reflection
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
-
+
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
- throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
-
+ throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound);
+
return defaultValue;
}
-
+
public override object GetConstantValue() { return GetConstantValue(false); }
public override object GetRawConstantValue() { return GetConstantValue(true); }
- public override MethodInfo[] GetAccessors(bool nonPublic)
+ public override MethodInfo[] GetAccessors(bool nonPublic)
{
List<MethodInfo> accessorList = new List<MethodInfo>();
@@ -406,7 +270,7 @@ namespace System.Reflection
if ((object)m_otherMethod != null)
{
- for(int i = 0; i < m_otherMethod.Length; i ++)
+ for (int i = 0; i < m_otherMethod.Length; i++)
{
if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic))
accessorList.Add(m_otherMethod[i]);
@@ -415,12 +279,12 @@ namespace System.Reflection
return accessorList.ToArray();
}
- public override Type PropertyType
+ public override Type PropertyType
{
get { return Signature.ReturnType; }
}
- public override MethodInfo GetGetMethod(bool nonPublic)
+ public override MethodInfo GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
@@ -428,7 +292,7 @@ namespace System.Reflection
return m_getterMethod;
}
- public override MethodInfo GetSetMethod(bool nonPublic)
+ public override MethodInfo GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
@@ -436,7 +300,7 @@ namespace System.Reflection
return m_setterMethod;
}
- public override ParameterInfo[] GetIndexParameters()
+ public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
@@ -496,7 +360,7 @@ namespace System.Reflection
return m_parameters;
}
- public override PropertyAttributes Attributes
+ public override PropertyAttributes Attributes
{
get
{
@@ -504,7 +368,7 @@ namespace System.Reflection
}
}
- public override bool CanRead
+ public override bool CanRead
{
get
{
@@ -512,7 +376,7 @@ namespace System.Reflection
}
}
- public override bool CanWrite
+ public override bool CanWrite
{
get
{
@@ -524,21 +388,20 @@ namespace System.Reflection
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override Object GetValue(Object obj,Object[] index)
+ public override Object GetValue(Object obj, Object[] index)
{
- return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
+ return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
+ public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
-
MethodInfo m = GetGetMethod(true);
if (m == null)
- throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd"));
- return m.Invoke(obj, invokeAttr, binder, index, null);
+ throw new ArgumentException(System.SR.Arg_GetMethNotFnd);
+ return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
@@ -547,9 +410,9 @@ namespace System.Reflection
{
SetValue(obj,
value,
- BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
- null,
- index,
+ BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
+ null,
+ index,
null);
}
@@ -557,24 +420,23 @@ namespace System.Reflection
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
-
MethodInfo m = GetSetMethod(true);
if (m == null)
- throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd"));
+ throw new ArgumentException(System.SR.Arg_SetMethNotFnd);
Object[] args = null;
- if (index != null)
+ if (index != null)
{
args = new Object[index.Length + 1];
- for(int i=0;i<index.Length;i++)
+ for (int i = 0; i < index.Length; i++)
args[i] = index[i];
args[index.Length] = value;
}
- else
+ else
{
args = new Object[1];
args[0] = value;
@@ -593,14 +455,7 @@ namespace System.Reflection
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
- MemberInfoSerializationHolder.GetSerializationInfo(
- info,
- Name,
- ReflectedTypeInternal,
- ToString(),
- SerializationToString(),
- MemberTypes.Property,
- null);
+ MemberInfoSerializationHolder.GetSerializationInfo(info, this);
}
internal string SerializationToString()
@@ -609,5 +464,4 @@ namespace System.Reflection
}
#endregion
}
-
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs b/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
deleted file mode 100644
index 49262634e3..0000000000
--- a/src/mscorlib/src/System/Reflection/RuntimeReflectionExtensions.cs
+++ /dev/null
@@ -1,88 +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.Collections.Generic;
-
-namespace System.Reflection
-{
- public static class RuntimeReflectionExtensions
- {
- private const BindingFlags everything = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
-
- private static void CheckAndThrow(Type type)
- {
- if (type == null) throw new ArgumentNullException(nameof(type));
- if (!(type is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
- }
-
- private static void CheckAndThrow(MethodInfo method)
- {
- if (method == null) throw new ArgumentNullException(nameof(method));
- if (!(method is RuntimeMethodInfo)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
- }
-
- public static IEnumerable<PropertyInfo> GetRuntimeProperties(this Type type)
- {
- CheckAndThrow(type);
- return type.GetProperties(everything);
- }
- public static IEnumerable<EventInfo> GetRuntimeEvents(this Type type)
- {
- CheckAndThrow(type);
- return type.GetEvents(everything);
- }
-
- public static IEnumerable<MethodInfo> GetRuntimeMethods(this Type type)
- {
- CheckAndThrow(type);
- return type.GetMethods(everything);
- }
-
- public static IEnumerable<FieldInfo> GetRuntimeFields(this Type type)
- {
- CheckAndThrow(type);
- return type.GetFields(everything);
- }
-
- public static PropertyInfo GetRuntimeProperty(this Type type, string name)
- {
- CheckAndThrow(type);
- return type.GetProperty(name);
- }
- public static EventInfo GetRuntimeEvent(this Type type, string name)
- {
- CheckAndThrow(type);
- return type.GetEvent(name);
- }
- public static MethodInfo GetRuntimeMethod(this Type type, string name, Type[] parameters)
- {
- CheckAndThrow(type);
- return type.GetMethod(name, parameters);
- }
- public static FieldInfo GetRuntimeField(this Type type, string name)
- {
- CheckAndThrow(type);
- return type.GetField(name);
- }
- public static MethodInfo GetRuntimeBaseDefinition(this MethodInfo method){
- CheckAndThrow(method);
- return method.GetBaseDefinition();
- }
-
- public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, Type interfaceType)
- {
- if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
- if (!(typeInfo is RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
-
- return typeInfo.GetInterfaceMap(interfaceType);
- }
-
- public static MethodInfo GetMethodInfo(this Delegate del)
- {
- if (del == null) throw new ArgumentNullException(nameof(del));
-
- return del.Method;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs b/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
deleted file mode 100644
index 0121982489..0000000000
--- a/src/mscorlib/src/System/Reflection/StrongNameKeyPair.cs
+++ /dev/null
@@ -1,95 +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: Encapsulate access to a public/private key pair
-** used to sign strong name assemblies.
-**
-**
-===========================================================*/
-namespace System.Reflection
-{
- using System;
- using System.IO;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Runtime.Versioning;
- using Microsoft.Win32;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- public class StrongNameKeyPair : IDeserializationCallback, ISerializable
- {
- private bool _keyPairExported;
- private byte[] _keyPairArray;
- private String _keyPairContainer;
- private byte[] _publicKey;
-
- // Build key pair from file.
- public StrongNameKeyPair(FileStream keyPairFile)
- {
- if (keyPairFile == null)
- throw new ArgumentNullException(nameof(keyPairFile));
- Contract.EndContractBlock();
-
- int length = (int)keyPairFile.Length;
- _keyPairArray = new byte[length];
- keyPairFile.Read(_keyPairArray, 0, length);
-
- _keyPairExported = true;
- }
-
- // Build key pair from byte array in memory.
- public StrongNameKeyPair(byte[] keyPairArray)
- {
- if (keyPairArray == null)
- throw new ArgumentNullException(nameof(keyPairArray));
- Contract.EndContractBlock();
-
- _keyPairArray = new byte[keyPairArray.Length];
- Array.Copy(keyPairArray, _keyPairArray, keyPairArray.Length);
-
- _keyPairExported = true;
- }
-
- protected StrongNameKeyPair (SerializationInfo info, StreamingContext context) {
- _keyPairExported = (bool) info.GetValue("_keyPairExported", typeof(bool));
- _keyPairArray = (byte[]) info.GetValue("_keyPairArray", typeof(byte[]));
- _keyPairContainer = (string) info.GetValue("_keyPairContainer", typeof(string));
- _publicKey = (byte[]) info.GetValue("_publicKey", typeof(byte[]));
- }
-
- public StrongNameKeyPair(String keyPairContainer)
- {
- throw new PlatformNotSupportedException();
- }
-
- public byte[] PublicKey
- {
- get
- {
- throw new PlatformNotSupportedException();
- }
- }
-
- /// <internalonly/>
- void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context) {
- info.AddValue("_keyPairExported", _keyPairExported);
- info.AddValue("_keyPairArray", _keyPairArray);
- info.AddValue("_keyPairContainer", _keyPairContainer);
- info.AddValue("_publicKey", _publicKey);
- }
-
- /// <internalonly/>
- void IDeserializationCallback.OnDeserialization (Object sender) {}
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/TargetException.cs b/src/mscorlib/src/System/Reflection/TargetException.cs
deleted file mode 100644
index dcbb38833e..0000000000
--- a/src/mscorlib/src/System/Reflection/TargetException.cs
+++ /dev/null
@@ -1,37 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// TargetException is thrown when the target to an Invoke is invalid. This may
-//
-// occur because the caller doesn't have access to the member, or the target doesn't
-// define the member, etc.
-//
-//
-//
-//
-namespace System.Reflection {
-
- using System;
- using System.Runtime.Serialization;
- [Serializable]
- public class TargetException : ApplicationException {
- public TargetException() : base() {
- SetErrorCode(__HResults.COR_E_TARGET);
- }
-
- public TargetException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_TARGET);
- }
-
- public TargetException(String message, Exception inner) : base(message, inner) {
- SetErrorCode(__HResults.COR_E_TARGET);
- }
-
- protected TargetException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/TargetInvocationException.cs b/src/mscorlib/src/System/Reflection/TargetInvocationException.cs
deleted file mode 100644
index 7bbc93df2a..0000000000
--- a/src/mscorlib/src/System/Reflection/TargetInvocationException.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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// TargetInvocationException is used to report an exception that was thrown
-//
-// by the target of an invocation.
-//
-//
-//
-//
-namespace System.Reflection {
-
-
- using System;
- using System.Runtime.Serialization;
- [Serializable]
- public sealed class TargetInvocationException : ApplicationException {
- // This exception is not creatable without specifying the
- // inner exception.
- private TargetInvocationException()
- : base(Environment.GetResourceString("Arg_TargetInvocationException")) {
- SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
- }
-
- // This is called from within the runtime.
- private TargetInvocationException(String message) : base(message) {
- SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
- }
-
- public TargetInvocationException(System.Exception inner)
- : base(Environment.GetResourceString("Arg_TargetInvocationException"), inner) {
- SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
- }
-
- public TargetInvocationException(String message, Exception inner) : base(message, inner) {
- SetErrorCode(__HResults.COR_E_TARGETINVOCATION);
- }
-
- internal TargetInvocationException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs b/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
deleted file mode 100644
index 7a07b20acd..0000000000
--- a/src/mscorlib/src/System/Reflection/TargetParameterCountException.cs
+++ /dev/null
@@ -1,40 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// TargetParameterCountException is thrown when the number of parameter to an
-//
-// invocation doesn't match the number expected.
-//
-//
-//
-//
-namespace System.Reflection {
-
- using System;
- using SystemException = System.SystemException;
- using System.Runtime.Serialization;
- [Serializable]
- public sealed class TargetParameterCountException : ApplicationException {
- public TargetParameterCountException()
- : base(Environment.GetResourceString("Arg_TargetParameterCountException")) {
- SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
- }
-
- public TargetParameterCountException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
- }
-
- public TargetParameterCountException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_TARGETPARAMCOUNT);
- }
-
- internal TargetParameterCountException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/TypeAttributes.cs b/src/mscorlib/src/System/Reflection/TypeAttributes.cs
deleted file mode 100644
index 25aa113d2e..0000000000
--- a/src/mscorlib/src/System/Reflection/TypeAttributes.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.
-
-namespace System.Reflection {
- using System.Runtime.InteropServices;
- using System;
- // This Enum matchs the CorTypeAttr defined in CorHdr.h
-[Serializable]
-[Flags]
- public enum TypeAttributes
- {
- VisibilityMask = 0x00000007,
- NotPublic = 0x00000000, // Class is not public scope.
- Public = 0x00000001, // Class is public scope.
- NestedPublic = 0x00000002, // Class is nested with public visibility.
- NestedPrivate = 0x00000003, // Class is nested with private visibility.
- NestedFamily = 0x00000004, // Class is nested with family visibility.
- NestedAssembly = 0x00000005, // Class is nested with assembly visibility.
- NestedFamANDAssem = 0x00000006, // Class is nested with family and assembly visibility.
- NestedFamORAssem = 0x00000007, // Class is nested with family or assembly visibility.
-
- // Use this mask to retrieve class layout informaiton
- // 0 is AutoLayout, 0x2 is SequentialLayout, 4 is ExplicitLayout
- LayoutMask = 0x00000018,
- AutoLayout = 0x00000000, // Class fields are auto-laid out
- SequentialLayout = 0x00000008, // Class fields are laid out sequentially
- ExplicitLayout = 0x00000010, // Layout is supplied explicitly
- // end layout mask
-
- // Use this mask to distinguish whether a type declaration is an interface. (Class vs. ValueType done based on whether it subclasses S.ValueType)
- ClassSemanticsMask= 0x00000020,
- Class = 0x00000000, // Type is a class (or a value type).
- Interface = 0x00000020, // Type is an interface.
-
- // Special semantics in addition to class semantics.
- Abstract = 0x00000080, // Class is abstract
- Sealed = 0x00000100, // Class is concrete and may not be extended
- SpecialName = 0x00000400, // Class name is special. Name describes how.
-
- // Implementation attributes.
- Import = 0x00001000, // Class / interface is imported
- Serializable = 0x00002000, // The class is Serializable.
-
- WindowsRuntime = 0x00004000, // Type is a Windows Runtime type.
-
- // Use tdStringFormatMask to retrieve string information for native interop
- StringFormatMask = 0x00030000,
- AnsiClass = 0x00000000, // LPTSTR is interpreted as ANSI in this class
- UnicodeClass = 0x00010000, // LPTSTR is interpreted as UNICODE
- AutoClass = 0x00020000, // LPTSTR is interpreted automatically
- CustomFormatClass = 0x00030000, // A non-standard encoding specified by CustomFormatMask
- CustomFormatMask = 0x00C00000, // Use this mask to retrieve non-standard encoding information for native interop. The meaning of the values of these 2 bits is unspecified.
-
- // end string format mask
-
- BeforeFieldInit = 0x00100000, // Initialize the class any time before first static field access.
-
- // Flags reserved for runtime use.
- ReservedMask = 0x00040800,
- RTSpecialName = 0x00000800, // Runtime should check name encoding.
- HasSecurity = 0x00040000, // Class has security associate with it.
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/TypeDelegator.cs b/src/mscorlib/src/System/Reflection/TypeDelegator.cs
deleted file mode 100644
index 6a77a95853..0000000000
--- a/src/mscorlib/src/System/Reflection/TypeDelegator.cs
+++ /dev/null
@@ -1,257 +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.
-
-// TypeDelegator
-//
-// This class wraps a Type object and delegates all methods to that Type.
-
-namespace System.Reflection {
-
- using System;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
- using CultureInfo = System.Globalization.CultureInfo;
-
- [Serializable]
- public class TypeDelegator : TypeInfo
- {
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
- return IsAssignableFrom(typeInfo.AsType());
- }
-
- protected Type typeImpl;
-
- protected TypeDelegator() {}
-
- public TypeDelegator(Type delegatingType) {
- if (delegatingType == null)
- throw new ArgumentNullException(nameof(delegatingType));
- Contract.EndContractBlock();
-
- typeImpl = delegatingType;
- }
-
- public override Guid GUID {
- get {return typeImpl.GUID;}
- }
-
- public override int MetadataToken { get { return typeImpl.MetadataToken; } }
-
- public override Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target,
- Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters)
- {
- return typeImpl.InvokeMember(name,invokeAttr,binder,target,args,modifiers,culture,namedParameters);
- }
-
- public override Module Module {
- get {return typeImpl.Module;}
- }
-
- public override Assembly Assembly {
- get {return typeImpl.Assembly;}
- }
-
- public override RuntimeTypeHandle TypeHandle {
- get{return typeImpl.TypeHandle;}
- }
-
- public override String Name {
- get{return typeImpl.Name;}
- }
-
- public override String FullName {
- get{return typeImpl.FullName;}
- }
-
- public override String Namespace {
- get{return typeImpl.Namespace;}
- }
-
- public override String AssemblyQualifiedName {
- get {
- return typeImpl.AssemblyQualifiedName;
- }
- }
-
- public override Type BaseType {
- get{return typeImpl.BaseType;}
- }
-
- protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
- {
- return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers);
- }
-
- public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
- {
- return typeImpl.GetConstructors(bindingAttr);
- }
-
- protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
- CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
- {
- // This is interesting there are two paths into the impl. One that validates
- // type as non-null and one where type may be null.
- if (types == null)
- return typeImpl.GetMethod(name,bindingAttr);
- else
- return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers);
- }
-
- public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
- {
- return typeImpl.GetMethods(bindingAttr);
- }
-
- public override FieldInfo GetField(String name, BindingFlags bindingAttr)
- {
- return typeImpl.GetField(name,bindingAttr);
- }
-
- public override FieldInfo[] GetFields(BindingFlags bindingAttr)
- {
- return typeImpl.GetFields(bindingAttr);
- }
-
- public override Type GetInterface(String name, bool ignoreCase)
- {
- return typeImpl.GetInterface(name,ignoreCase);
- }
-
- public override Type[] GetInterfaces()
- {
- return typeImpl.GetInterfaces();
- }
-
- public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
- {
- return typeImpl.GetEvent(name,bindingAttr);
- }
-
- public override EventInfo[] GetEvents()
- {
- return typeImpl.GetEvents();
- }
-
- protected override PropertyInfo GetPropertyImpl(String name,BindingFlags bindingAttr,Binder binder,
- Type returnType, Type[] types, ParameterModifier[] modifiers)
- {
- if (returnType == null && types == null)
- return typeImpl.GetProperty(name,bindingAttr);
- else
- return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers);
- }
-
- public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
- {
- return typeImpl.GetProperties(bindingAttr);
- }
-
- public override EventInfo[] GetEvents(BindingFlags bindingAttr)
- {
- return typeImpl.GetEvents(bindingAttr);
- }
-
- public override Type[] GetNestedTypes(BindingFlags bindingAttr)
- {
- return typeImpl.GetNestedTypes(bindingAttr);
- }
-
- public override Type GetNestedType(String name, BindingFlags bindingAttr)
- {
- return typeImpl.GetNestedType(name,bindingAttr);
- }
-
- public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
- {
- return typeImpl.GetMember(name,type,bindingAttr);
- }
-
- public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
- {
- return typeImpl.GetMembers(bindingAttr);
- }
-
- protected override TypeAttributes GetAttributeFlagsImpl()
- {
- return typeImpl.Attributes;
- }
-
- protected override bool IsArrayImpl()
- {
- return typeImpl.IsArray;
- }
-
- protected override bool IsPrimitiveImpl()
- {
- return typeImpl.IsPrimitive;
- }
-
- protected override bool IsByRefImpl()
- {
- return typeImpl.IsByRef;
- }
-
- protected override bool IsPointerImpl()
- {
- return typeImpl.IsPointer;
- }
-
- protected override bool IsValueTypeImpl()
- {
- return typeImpl.IsValueType;
- }
-
- protected override bool IsCOMObjectImpl()
- {
- return typeImpl.IsCOMObject;
- }
-
- public override bool IsConstructedGenericType
- {
- get
- {
- return typeImpl.IsConstructedGenericType;
- }
- }
-
- public override Type GetElementType()
- {
- return typeImpl.GetElementType();
- }
-
- protected override bool HasElementTypeImpl()
- {
- return typeImpl.HasElementType;
- }
-
- public override Type UnderlyingSystemType
- {
- get {return typeImpl.UnderlyingSystemType;}
- }
-
- // ICustomAttributeProvider
- public override Object[] GetCustomAttributes(bool inherit)
- {
- return typeImpl.GetCustomAttributes(inherit);
- }
-
- public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
- {
- return typeImpl.GetCustomAttributes(attributeType, inherit);
- }
-
- public override bool IsDefined(Type attributeType, bool inherit)
- {
- return typeImpl.IsDefined(attributeType, inherit);
- }
-
- public override InterfaceMapping GetInterfaceMap(Type interfaceType)
- {
- return typeImpl.GetInterfaceMap(interfaceType);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Reflection/TypeFilter.cs b/src/mscorlib/src/System/Reflection/TypeFilter.cs
deleted file mode 100644
index 4837a303a1..0000000000
--- a/src/mscorlib/src/System/Reflection/TypeFilter.cs
+++ /dev/null
@@ -1,18 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-// TypeFilter defines a delegate that is as a callback function for filtering
-//
-// a list of Types.
-//
-//
-namespace System.Reflection {
-
- // Define the delegate
- [Serializable]
- public delegate bool TypeFilter(Type m, Object filterCriteria);
-}
diff --git a/src/mscorlib/src/System/Reflection/TypeInfo.cs b/src/mscorlib/src/System/Reflection/TypeInfo.cs
deleted file mode 100644
index 61d7bb27a9..0000000000
--- a/src/mscorlib/src/System/Reflection/TypeInfo.cs
+++ /dev/null
@@ -1,194 +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: Notion of a type definition
-**
-**
-=============================================================================*/
-
-namespace System.Reflection
-{
- using System;
- using System.Runtime.CompilerServices;
- using System.Collections.Generic;
- using System.Diagnostics.Contracts;
-
- //all today's runtime Type derivations derive now from TypeInfo
- //we make TypeInfo implement IRCT - simplifies work
- [Serializable]
- public abstract class TypeInfo:Type,IReflectableType
- {
- [FriendAccessAllowed]
- internal TypeInfo() { }
-
- TypeInfo IReflectableType.GetTypeInfo(){
- return this;
- }
- public virtual Type AsType(){
- return (Type)this;
- }
-
- public virtual Type[] GenericTypeParameters{
- get{
- if(IsGenericTypeDefinition){
- return GetGenericArguments();
- }
- else{
- return Type.EmptyTypes;
- }
-
- }
- }
- //a re-implementation of ISAF from Type, skipping the use of UnderlyingType
- [Pure]
- public virtual bool IsAssignableFrom(TypeInfo typeInfo)
- {
- if (typeInfo == null)
- return false;
-
- if (this == typeInfo)
- return true;
-
- // If c is a subclass of this class, then c can be cast to this type.
- if (typeInfo.IsSubclassOf(this))
- return true;
-
- if (this.IsInterface)
- {
- return typeInfo.ImplementInterface(this);
- }
- else if (IsGenericParameter)
- {
- Type[] constraints = GetGenericParameterConstraints();
- for (int i = 0; i < constraints.Length; i++)
- if (!constraints[i].IsAssignableFrom(typeInfo))
- return false;
-
- return true;
- }
-
- return false;
- }
-#region moved over from Type
- // Fields
-
- public virtual EventInfo GetDeclaredEvent(String name)
- {
- return GetEvent(name, Type.DeclaredOnlyLookup);
- }
- public virtual FieldInfo GetDeclaredField(String name)
- {
- return GetField(name, Type.DeclaredOnlyLookup);
- }
- public virtual MethodInfo GetDeclaredMethod(String name)
- {
- return GetMethod(name, Type.DeclaredOnlyLookup);
- }
-
- public virtual IEnumerable<MethodInfo> GetDeclaredMethods(String name)
- {
- foreach (MethodInfo method in GetMethods(Type.DeclaredOnlyLookup))
- {
- if (method.Name == name)
- yield return method;
- }
- }
- public virtual System.Reflection.TypeInfo GetDeclaredNestedType(String name)
- {
- var nt=GetNestedType(name, Type.DeclaredOnlyLookup);
- if(nt == null){
- return null; //the extension method GetTypeInfo throws for null
- }else{
- return nt.GetTypeInfo();
- }
- }
- public virtual PropertyInfo GetDeclaredProperty(String name)
- {
- return GetProperty(name, Type.DeclaredOnlyLookup);
- }
-
-
-
-
-
- // Properties
-
- public virtual IEnumerable<ConstructorInfo> DeclaredConstructors
- {
- get
- {
- return GetConstructors(Type.DeclaredOnlyLookup);
- }
- }
-
- public virtual IEnumerable<EventInfo> DeclaredEvents
- {
- get
- {
- return GetEvents(Type.DeclaredOnlyLookup);
- }
- }
-
- public virtual IEnumerable<FieldInfo> DeclaredFields
- {
- get
- {
- return GetFields(Type.DeclaredOnlyLookup);
- }
- }
-
- public virtual IEnumerable<MemberInfo> DeclaredMembers
- {
- get
- {
- return GetMembers(Type.DeclaredOnlyLookup);
- }
- }
-
- public virtual IEnumerable<MethodInfo> DeclaredMethods
- {
- get
- {
- return GetMethods(Type.DeclaredOnlyLookup);
- }
- }
- public virtual IEnumerable<System.Reflection.TypeInfo> DeclaredNestedTypes
- {
- get
- {
- foreach (var t in GetNestedTypes(Type.DeclaredOnlyLookup)){
- yield return t.GetTypeInfo();
- }
- }
- }
-
- public virtual IEnumerable<PropertyInfo> DeclaredProperties
- {
- get
- {
- return GetProperties(Type.DeclaredOnlyLookup);
- }
- }
-
-
- public virtual IEnumerable<Type> ImplementedInterfaces
- {
- get
- {
- return GetInterfaces();
- }
- }
-
-
-#endregion
-
- }
-}
-
diff --git a/src/mscorlib/src/System/Reflection/__Filters.cs b/src/mscorlib/src/System/Reflection/__Filters.cs
deleted file mode 100644
index 8edcd0d7cb..0000000000
--- a/src/mscorlib/src/System/Reflection/__Filters.cs
+++ /dev/null
@@ -1,67 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-//
-//
-// This class defines the delegate methods for the COM+ implemented filters.
-// This is the reflection version of these. There is also a _Filters class in
-// runtime which is related to this.
-//
-//
-//
-//
-namespace System.Reflection {
- using System;
- using System.Globalization;
-
- [Serializable]
- internal class __Filters {
-
- // FilterTypeName
- // This method will filter the class based upon the name. It supports
- // a trailing wild card.
- public virtual bool FilterTypeName(Type cls,Object filterCriteria)
- {
- // Check that the criteria object is a String object
- if (filterCriteria == null || !(filterCriteria is String))
- throw new InvalidFilterCriteriaException(System.Environment.GetResourceString("RFLCT.FltCritString"));
-
- String str = (String) filterCriteria;
- //str = str.Trim();
-
- // Check to see if this is a prefix or exact match requirement
- if (str.Length > 0 && str[str.Length - 1] == '*') {
- str = str.Substring(0, str.Length - 1);
- return cls.Name.StartsWith(str, StringComparison.Ordinal);
- }
-
- return cls.Name.Equals(str);
- }
-
- // FilterFieldNameIgnoreCase
- // This method filter the Type based upon name, it ignores case.
- public virtual bool FilterTypeNameIgnoreCase(Type cls, Object filterCriteria)
- {
- // Check that the criteria object is a String object
- if(filterCriteria == null || !(filterCriteria is String))
- throw new InvalidFilterCriteriaException(System.Environment.GetResourceString("RFLCT.FltCritString"));
-
- String str = (String) filterCriteria;
- //str = str.Trim();
-
- // Check to see if this is a prefix or exact match requirement
- if (str.Length > 0 && str[str.Length - 1] == '*') {
- str = str.Substring(0, str.Length - 1);
- String name = cls.Name;
- if (name.Length >= str.Length)
- return (String.Compare(name,0,str,0,str.Length, StringComparison.OrdinalIgnoreCase)==0);
- else
- return false;
- }
- return (String.Compare(str,cls.Name, StringComparison.OrdinalIgnoreCase) == 0);
- }
- }
-}
diff --git a/src/mscorlib/src/System/ResId.cs b/src/mscorlib/src/System/ResId.cs
index e6a2423c28..7be46145b0 100644
--- a/src/mscorlib/src/System/ResId.cs
+++ b/src/mscorlib/src/System/ResId.cs
@@ -11,83 +11,87 @@
**
**
===========================================================*/
-namespace System {
- //This class contains only static members and does not need to be serializable.
- using System.Configuration.Assemblies;
- using System;
- internal static class ResId {
+//This class contains only static members and does not need to be serializable.
+
+using System.Configuration.Assemblies;
+using System;
+
+namespace System
+{
+ internal static class ResId
+ {
// Only statics, does not need to be marked with the serializable attribute
- internal const String Arg_ArrayLengthsDiffer="Arg_ArrayLengthsDiffer";
- internal const String Argument_InvalidNumberOfMembers="Argument_InvalidNumberOfMembers";
- internal const String Argument_UnequalMembers="Argument_UnequalMembers";
- internal const String Argument_SpecifyValueSize="Argument_SpecifyValueSize";
- internal const String Argument_UnmatchingSymScope="Argument_UnmatchingSymScope";
- internal const String Argument_NotInExceptionBlock="Argument_NotInExceptionBlock";
- internal const String Argument_NotExceptionType="Argument_NotExceptionType";
- internal const String Argument_InvalidLabel="Argument_InvalidLabel";
- internal const String Argument_UnclosedExceptionBlock="Argument_UnclosedExceptionBlock";
- internal const String Argument_MissingDefaultConstructor="Argument_MissingDefaultConstructor";
- internal const String Argument_TooManyFinallyClause="Argument_TooManyFinallyClause";
- internal const String Argument_NotInTheSameModuleBuilder="Argument_NotInTheSameModuleBuilder";
- internal const String Argument_BadCurrentLocalVariable="Argument_BadCurrentLocalVariable";
- internal const String Argument_DuplicateModuleName="Argument_DuplicateModuleName";
- internal const String Argument_BadPersistableModuleInTransientAssembly="Argument_BadPersistableModuleInTransientAssembly";
- internal const String Argument_HasToBeArrayClass="Argument_HasToBeArrayClass";
- internal const String Argument_InvalidDirectory="Argument_InvalidDirectory";
-
- internal const String MissingType="MissingType";
- internal const String MissingModule="MissingModule";
-
- internal const String ArgumentOutOfRange_Index="ArgumentOutOfRange_Index";
- internal const String ArgumentOutOfRange_Range="ArgumentOutOfRange_Range";
-
- internal const String ExecutionEngine_YoureHosed="ExecutionEngine_YoureHosed";
-
- internal const String Format_NeedSingleChar="Format_NeedSingleChar";
- internal const String Format_StringZeroLength="Format_StringZeroLength";
-
- internal const String InvalidOperation_EnumEnded="InvalidOperation_EnumEnded";
- internal const String InvalidOperation_EnumFailedVersion="InvalidOperation_EnumFailedVersion";
- internal const String InvalidOperation_EnumNotStarted="InvalidOperation_EnumNotStarted";
- internal const String InvalidOperation_EnumOpCantHappen="InvalidOperation_EnumOpCantHappen";
- internal const String InvalidOperation_InternalState="InvalidOperation_InternalState";
- internal const String InvalidOperation_ModifyRONumFmtInfo="InvalidOperation_ModifyRONumFmtInfo";
- internal const String InvalidOperation_MethodBaked="InvalidOperation_MethodBaked";
- internal const String InvalidOperation_NotADebugModule="InvalidOperation_NotADebugModule";
- internal const String InvalidOperation_MethodHasBody="InvalidOperation_MethodHasBody";
- internal const String InvalidOperation_OpenLocalVariableScope="InvalidOperation_OpenLocalVariableScope";
- internal const String InvalidOperation_TypeHasBeenCreated="InvalidOperation_TypeHasBeenCreated";
- internal const String InvalidOperation_RefedAssemblyNotSaved="InvalidOperation_RefedAssemblyNotSaved";
- internal const String InvalidOperation_AssemblyHasBeenSaved="InvalidOperation_AssemblyHasBeenSaved";
- internal const String InvalidOperation_ModuleHasBeenSaved="InvalidOperation_ModuleHasBeenSaved";
- internal const String InvalidOperation_CannotAlterAssembly="InvalidOperation_CannotAlterAssembly";
-
- internal const String NotSupported_CannotSaveModuleIndividually="NotSupported_CannotSaveModuleIndividually";
- internal const String NotSupported_Constructor="NotSupported_Constructor";
- internal const String NotSupported_Method="NotSupported_Method";
- internal const String NotSupported_NYI="NotSupported_NYI";
- internal const String NotSupported_DynamicModule="NotSupported_DynamicModule";
- internal const String NotSupported_NotDynamicModule="NotSupported_NotDynamicModule";
- internal const String NotSupported_NotAllTypesAreBaked="NotSupported_NotAllTypesAreBaked";
- internal const String NotSupported_SortedListNestedWrite="NotSupported_SortedListNestedWrite";
-
-
- internal const String Serialization_ArrayInvalidLength="Serialization_ArrayInvalidLength";
- internal const String Serialization_ArrayNoLength="Serialization_ArrayNoLength";
- internal const String Serialization_CannotGetType="Serialization_CannotGetType";
- internal const String Serialization_InsufficientState="Serialization_InsufficientState";
- internal const String Serialization_InvalidID="Serialization_InvalidID";
- internal const String Serialization_MalformedArray="Serialization_MalformedArray";
- internal const String Serialization_MultipleMembers="Serialization_MultipleMembers";
- internal const String Serialization_NoID="Serialization_NoID";
- internal const String Serialization_NoType="Serialization_NoType";
- internal const String Serialization_NoBaseType="Serialization_NoBaseType";
- internal const String Serialization_NullSignature="Serialization_NullSignature";
- internal const String Serialization_UnknownMember="Serialization_UnknownMember";
- internal const String Serialization_BadParameterInfo="Serialization_BadParameterInfo";
- internal const String Serialization_NoParameterInfo="Serialization_NoParameterInfo";
+ internal const String Arg_ArrayLengthsDiffer = "Arg_ArrayLengthsDiffer";
+ internal const String Argument_InvalidNumberOfMembers = "Argument_InvalidNumberOfMembers";
+ internal const String Argument_UnequalMembers = "Argument_UnequalMembers";
+ internal const String Argument_SpecifyValueSize = "Argument_SpecifyValueSize";
+ internal const String Argument_UnmatchingSymScope = "Argument_UnmatchingSymScope";
+ internal const String Argument_NotInExceptionBlock = "Argument_NotInExceptionBlock";
+ internal const String Argument_NotExceptionType = "Argument_NotExceptionType";
+ internal const String Argument_InvalidLabel = "Argument_InvalidLabel";
+ internal const String Argument_UnclosedExceptionBlock = "Argument_UnclosedExceptionBlock";
+ internal const String Argument_MissingDefaultConstructor = "Argument_MissingDefaultConstructor";
+ internal const String Argument_TooManyFinallyClause = "Argument_TooManyFinallyClause";
+ internal const String Argument_NotInTheSameModuleBuilder = "Argument_NotInTheSameModuleBuilder";
+ internal const String Argument_BadCurrentLocalVariable = "Argument_BadCurrentLocalVariable";
+ internal const String Argument_DuplicateModuleName = "Argument_DuplicateModuleName";
+ internal const String Argument_BadPersistableModuleInTransientAssembly = "Argument_BadPersistableModuleInTransientAssembly";
+ internal const String Argument_HasToBeArrayClass = "Argument_HasToBeArrayClass";
+ internal const String Argument_InvalidDirectory = "Argument_InvalidDirectory";
+
+ internal const String MissingType = "MissingType";
+ internal const String MissingModule = "MissingModule";
+
+ internal const String ArgumentOutOfRange_Index = "ArgumentOutOfRange_Index";
+ internal const String ArgumentOutOfRange_Range = "ArgumentOutOfRange_Range";
+
+ internal const String ExecutionEngine_YoureHosed = "ExecutionEngine_YoureHosed";
+
+ internal const String Format_NeedSingleChar = "Format_NeedSingleChar";
+ internal const String Format_StringZeroLength = "Format_StringZeroLength";
+
+ internal const String InvalidOperation_EnumEnded = "InvalidOperation_EnumEnded";
+ internal const String InvalidOperation_EnumFailedVersion = "InvalidOperation_EnumFailedVersion";
+ internal const String InvalidOperation_EnumNotStarted = "InvalidOperation_EnumNotStarted";
+ internal const String InvalidOperation_EnumOpCantHappen = "InvalidOperation_EnumOpCantHappen";
+ internal const String InvalidOperation_InternalState = "InvalidOperation_InternalState";
+ internal const String InvalidOperation_ModifyRONumFmtInfo = "InvalidOperation_ModifyRONumFmtInfo";
+ internal const String InvalidOperation_MethodBaked = "InvalidOperation_MethodBaked";
+ internal const String InvalidOperation_NotADebugModule = "InvalidOperation_NotADebugModule";
+ internal const String InvalidOperation_MethodHasBody = "InvalidOperation_MethodHasBody";
+ internal const String InvalidOperation_OpenLocalVariableScope = "InvalidOperation_OpenLocalVariableScope";
+ internal const String InvalidOperation_TypeHasBeenCreated = "InvalidOperation_TypeHasBeenCreated";
+ internal const String InvalidOperation_RefedAssemblyNotSaved = "InvalidOperation_RefedAssemblyNotSaved";
+ internal const String InvalidOperation_AssemblyHasBeenSaved = "InvalidOperation_AssemblyHasBeenSaved";
+ internal const String InvalidOperation_ModuleHasBeenSaved = "InvalidOperation_ModuleHasBeenSaved";
+ internal const String InvalidOperation_CannotAlterAssembly = "InvalidOperation_CannotAlterAssembly";
+
+ internal const String NotSupported_CannotSaveModuleIndividually = "NotSupported_CannotSaveModuleIndividually";
+ internal const String NotSupported_Constructor = "NotSupported_Constructor";
+ internal const String NotSupported_Method = "NotSupported_Method";
+ internal const String NotSupported_NYI = "NotSupported_NYI";
+ internal const String NotSupported_DynamicModule = "NotSupported_DynamicModule";
+ internal const String NotSupported_NotDynamicModule = "NotSupported_NotDynamicModule";
+ internal const String NotSupported_NotAllTypesAreBaked = "NotSupported_NotAllTypesAreBaked";
+ internal const String NotSupported_SortedListNestedWrite = "NotSupported_SortedListNestedWrite";
+
+
+ internal const String Serialization_ArrayInvalidLength = "Serialization_ArrayInvalidLength";
+ internal const String Serialization_ArrayNoLength = "Serialization_ArrayNoLength";
+ internal const String Serialization_CannotGetType = "Serialization_CannotGetType";
+ internal const String Serialization_InsufficientState = "Serialization_InsufficientState";
+ internal const String Serialization_InvalidID = "Serialization_InvalidID";
+ internal const String Serialization_MalformedArray = "Serialization_MalformedArray";
+ internal const String Serialization_MultipleMembers = "Serialization_MultipleMembers";
+ internal const String Serialization_NoID = "Serialization_NoID";
+ internal const String Serialization_NoType = "Serialization_NoType";
+ internal const String Serialization_NoBaseType = "Serialization_NoBaseType";
+ internal const String Serialization_NullSignature = "Serialization_NullSignature";
+ internal const String Serialization_UnknownMember = "Serialization_UnknownMember";
+ internal const String Serialization_BadParameterInfo = "Serialization_BadParameterInfo";
+ internal const String Serialization_NoParameterInfo = "Serialization_NoParameterInfo";
- internal const String WeakReference_NoLongerValid="WeakReference_NoLongerValid";
- internal const String Loader_InvalidPath="Loader_InvalidPath";
+ internal const String WeakReference_NoLongerValid = "WeakReference_NoLongerValid";
+ internal const String Loader_InvalidPath = "Loader_InvalidPath";
}
}
diff --git a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
index c5e92165f1..e1bbd2814a 100644
--- a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
@@ -13,7 +13,9 @@
**
**
===========================================================*/
-namespace System.Resources {
+
+namespace System.Resources
+{
using System;
using System.Collections;
using System.Collections.Generic;
@@ -39,7 +41,7 @@ namespace System.Resources {
// Consider modifying IResourceGroveler interface (hence this method signature) when we figure out
// serialization compat story for moving ResourceManager members to either file-based or
// manifest-based classes. Want to continue tightening the design to get rid of unused params.
- public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
+ public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
Debug.Assert(culture != null, "culture shouldn't be null; check caller");
@@ -60,7 +62,7 @@ namespace System.Resources {
{
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralDisk") + Environment.NewLine + "baseName: " + _mediator.BaseNameField + " locationInfo: " + (_mediator.LocationInfo == null ? "<null>" : _mediator.LocationInfo.FullName) + " fileName: " + _mediator.GetResourceFileName(culture));
+ throw new MissingManifestResourceException(SR.MissingManifestResource_NoNeutralDisk + Environment.NewLine + "baseName: " + _mediator.BaseNameField + " locationInfo: " + (_mediator.LocationInfo == null ? "<null>" : _mediator.LocationInfo.FullName) + " fileName: " + _mediator.GetResourceFileName(culture));
}
}
}
@@ -90,7 +92,7 @@ namespace System.Resources {
{
#if _DEBUG
if (ResourceManager.DEBUG >= 3)
- BCLDebug.Log("FindResourceFile: checking module dir: \""+_mediator.ModuleDir+'\"');
+ BCLDebug.Log("FindResourceFile: checking module dir: \"" + _mediator.ModuleDir + '\"');
#endif
String path = Path.Combine(_mediator.ModuleDir, fileName);
@@ -98,7 +100,7 @@ namespace System.Resources {
{
#if _DEBUG
if (ResourceManager.DEBUG >= 3)
- BCLDebug.Log("Found resource file in module dir! "+path);
+ BCLDebug.Log("Found resource file in module dir! " + path);
#endif
return path;
}
@@ -106,7 +108,7 @@ namespace System.Resources {
#if _DEBUG
if (ResourceManager.DEBUG >= 3)
- BCLDebug.Log("Couldn't find resource file in module dir, checking .\\"+fileName);
+ BCLDebug.Log("Couldn't find resource file in module dir, checking .\\" + fileName);
#endif
// look in .
@@ -140,7 +142,7 @@ namespace System.Resources {
}
catch (MissingMethodException e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e);
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
diff --git a/src/mscorlib/src/System/Resources/IResourceGroveler.cs b/src/mscorlib/src/System/Resources/IResourceGroveler.cs
index 77c5c95890..bdd8826c77 100644
--- a/src/mscorlib/src/System/Resources/IResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/IResourceGroveler.cs
@@ -12,16 +12,18 @@
**
**
===========================================================*/
-namespace System.Resources {
- using System;
- using System.Globalization;
- using System.Threading;
- using System.Collections.Generic;
- using System.Runtime.Versioning;
+using System;
+using System.Globalization;
+using System.Threading;
+using System.Collections.Generic;
+using System.Runtime.Versioning;
+
+namespace System.Resources
+{
internal interface IResourceGroveler
{
- ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents,
+ ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents,
bool createIfNotExists, ref StackCrawlMark stackMark);
}
}
diff --git a/src/mscorlib/src/System/Resources/IResourceReader.cs b/src/mscorlib/src/System/Resources/IResourceReader.cs
deleted file mode 100644
index de8f9db18e..0000000000
--- a/src/mscorlib/src/System/Resources/IResourceReader.cs
+++ /dev/null
@@ -1,30 +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: Abstraction to read streams of resources.
-**
-**
-===========================================================*/
-namespace System.Resources {
- using System;
- using System.IO;
- using System.Collections;
-
- public interface IResourceReader : IEnumerable, IDisposable
- {
- // Interface does not need to be marked with the serializable attribute
- // Closes the ResourceReader, releasing any resources associated with it.
- // This could close a network connection, a file, or do nothing.
- void Close();
-
-
- new IDictionaryEnumerator GetEnumerator();
- }
-}
diff --git a/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs b/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
index 9287ae4590..3179df09b7 100644
--- a/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
+++ b/src/mscorlib/src/System/Resources/LooselyLinkedResourceReference.cs
@@ -39,9 +39,9 @@ namespace System.Resources {
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
if (looselyLinkedResourceName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(looselyLinkedResourceName));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(looselyLinkedResourceName));
if (typeName.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(typeName));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(typeName));
Contract.EndContractBlock();
_manifestResourceName = looselyLinkedResourceName;
@@ -64,7 +64,7 @@ namespace System.Resources {
Stream data = assembly.GetManifestResourceStream(_manifestResourceName);
if (data == null)
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_LooselyLinked", _manifestResourceName, assembly.FullName));
+ throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_LooselyLinked, _manifestResourceName, assembly.FullName));
Type type = Type.GetType(_typeName, true);
diff --git a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
index 78e961a7f9..0e9666b2b1 100644
--- a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
@@ -13,8 +13,9 @@
**
**
===========================================================*/
-namespace System.Resources {
+namespace System.Resources
+{
using System;
using System.Collections;
using System.Collections.Generic;
@@ -41,7 +42,6 @@ namespace System.Resources {
//
internal class ManifestBasedResourceGroveler : IResourceGroveler
{
-
private ResourceManager.ResourceManagerMediator _mediator;
public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
@@ -52,7 +52,6 @@ namespace System.Resources {
_mediator = mediator;
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
Debug.Assert(culture != null, "culture shouldn't be null; check caller");
@@ -132,7 +131,6 @@ namespace System.Resources {
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
-
CultureInfo returnCulture = lookForCulture;
// If our neutral resources were written in this culture AND we know the main assembly
@@ -155,15 +153,18 @@ namespace System.Resources {
Debug.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
- if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
- JitHelpers.GetStringHandleOnStack(ref cultureName),
- out fallback)) {
- if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite) {
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", fallback));
+ if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
+ JitHelpers.GetStringHandleOnStack(ref cultureName),
+ out fallback))
+ {
+ if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite)
+ {
+ throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, fallback));
}
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
- else {
+ else
+ {
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
@@ -180,11 +181,11 @@ namespace System.Resources {
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
- Debug.Assert(false, System.CoreLib.Name+"'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
+ Debug.Assert(false, System.CoreLib.Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture", a.ToString(), cultureName), e);
+ throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_Asm_Culture, a.ToString(), cultureName), e);
}
}
@@ -202,10 +203,10 @@ namespace System.Resources {
if (store.CanSeek && store.Length > 4)
{
long startPos = store.Position;
-
+
// not disposing because we want to leave stream open
BinaryReader br = new BinaryReader(store);
-
+
// Look for our magic number as a little endian Int32.
int bytes = br.ReadInt32();
if (bytes == ResourceManager.MagicNumber)
@@ -237,7 +238,7 @@ namespace System.Resources {
// resMgrHeaderVersion is older than this ResMgr version.
// We should add in backwards compatibility support here.
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ObsoleteResourcesFile", _mediator.MainAssembly.GetSimpleName()));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetSimpleName()));
}
store.Position = startPos;
@@ -294,7 +295,6 @@ namespace System.Resources {
{
store.Position = startPos;
}
-
}
if (_mediator.UserResourceSet == null)
@@ -334,7 +334,7 @@ namespace System.Resources {
}
catch (MissingMethodException e)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResMgrBadResSet_Type", _mediator.UserResourceSet.AssemblyQualifiedName), e);
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
@@ -362,7 +362,7 @@ namespace System.Resources {
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
{
Contract.Requires(satellite != null, "satellite shouldn't be null; check caller");
@@ -394,7 +394,7 @@ namespace System.Resources {
}
else
{
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_MultipleBlobs", givenName, satellite.ToString()));
+ throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_MultipleBlobs, givenName, satellite.ToString()));
}
}
}
@@ -412,7 +412,6 @@ namespace System.Resources {
return satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
{
if (!_mediator.LookedForSatelliteContractVersion)
@@ -493,7 +492,7 @@ namespace System.Resources {
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
- satAssemblyName += ".resources";
+ satAssemblyName += ".resources";
return satAssemblyName;
}
@@ -522,7 +521,7 @@ namespace System.Resources {
{
missingCultureName = "<invariant>";
}
- throw new MissingSatelliteAssemblyException(Environment.GetResourceString("MissingSatelliteAssembly_Culture_Name", _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
+ throw new MissingSatelliteAssemblyException(SR.Format(SR.MissingSatelliteAssembly_Culture_Name, _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
private void HandleResourceStreamMissing(String fileName)
@@ -531,8 +530,8 @@ namespace System.Resources {
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
{
// This would break CultureInfo & all our exceptions.
- Debug.Assert(false, "Couldn't get " + System.CoreLib.Name+ResourceManager.ResFileExtension + " from "+System.CoreLib.Name+"'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
-
+ Debug.Assert(false, "Couldn't get " + System.CoreLib.Name + ResourceManager.ResFileExtension + " from " + System.CoreLib.Name + "'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
+
// We cannot continue further - simply FailFast.
string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
System.Environment.FailFast(mesgFailFast);
@@ -543,12 +542,12 @@ namespace System.Resources {
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter;
resName += fileName;
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoNeutralAsm", resName, _mediator.MainAssembly.GetSimpleName()));
+ throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_NoNeutralAsm, resName, _mediator.MainAssembly.GetSimpleName()));
}
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [System.Security.SuppressUnmanagedCodeSecurity]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [System.Security.SuppressUnmanagedCodeSecurity]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
}
}
diff --git a/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs b/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
deleted file mode 100644
index 2e82f19c7b..0000000000
--- a/src/mscorlib/src/System/Resources/MissingManifestResourceException.cs
+++ /dev/null
@@ -1,41 +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 missing assembly-level resource
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.Resources {
- [Serializable]
- public class MissingManifestResourceException : SystemException
- {
- public MissingManifestResourceException()
- : base(Environment.GetResourceString("Arg_MissingManifestResourceException")) {
- SetErrorCode(System.__HResults.COR_E_MISSINGMANIFESTRESOURCE);
- }
-
- public MissingManifestResourceException(String message)
- : base(message) {
- SetErrorCode(System.__HResults.COR_E_MISSINGMANIFESTRESOURCE);
- }
-
- public MissingManifestResourceException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(System.__HResults.COR_E_MISSINGMANIFESTRESOURCE);
- }
-
- protected MissingManifestResourceException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs b/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
deleted file mode 100644
index fc676a8dd5..0000000000
--- a/src/mscorlib/src/System/Resources/MissingSatelliteAssemblyException.cs
+++ /dev/null
@@ -1,55 +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 missing satellite assembly needed
-** for ultimate resource fallback. This usually
-** indicates a setup and/or deployment problem.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.Resources {
- [Serializable]
- public class MissingSatelliteAssemblyException : SystemException
- {
- private String _cultureName;
-
- public MissingSatelliteAssemblyException()
- : base(Environment.GetResourceString("MissingSatelliteAssembly_Default")) {
- SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
- }
-
- public MissingSatelliteAssemblyException(String message)
- : base(message) {
- SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
- }
-
- public MissingSatelliteAssemblyException(String message, String cultureName)
- : base(message) {
- SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
- _cultureName = cultureName;
- }
-
- public MissingSatelliteAssemblyException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY);
- }
-
- protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
-
- public String CultureName {
- get { return _cultureName; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs b/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.cs
deleted file mode 100644
index a2ed6fbd57..0000000000
--- a/src/mscorlib/src/System/Resources/NeutralResourcesLanguageAttribute.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.
-
-/*============================================================
-**
-**
-**
-**
-**
-** Purpose: Tells the ResourceManager what language your main
-** assembly's resources are written in. The
-** ResourceManager won't try loading a satellite
-** assembly for that culture, which helps perf.
-**
-**
-** NOTE:
-**
-** This custom attribute is no longer implemented in managed code. As part of a perf optimization,
-** it is now read in Module::GetNeutralResourcesLanguage, accessed from ManifestBasedResourceGroveler
-** through an internal runtime call.
-===========================================================*/
-
-namespace System.Resources {
- using System;
- using System.Diagnostics.Contracts;
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
- public sealed class NeutralResourcesLanguageAttribute : Attribute
- {
- private String _culture;
- private UltimateResourceFallbackLocation _fallbackLoc;
-
- public NeutralResourcesLanguageAttribute(String cultureName)
- {
- if (cultureName == null)
- throw new ArgumentNullException(nameof(cultureName));
- Contract.EndContractBlock();
-
- _culture = cultureName;
- _fallbackLoc = UltimateResourceFallbackLocation.MainAssembly;
- }
-
- public NeutralResourcesLanguageAttribute(String cultureName, UltimateResourceFallbackLocation location)
- {
- if (cultureName == null)
- throw new ArgumentNullException(nameof(cultureName));
- if (!Enum.IsDefined(typeof(UltimateResourceFallbackLocation), location))
- throw new ArgumentException(Environment.GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc", location));
- Contract.EndContractBlock();
-
- _culture = cultureName;
- _fallbackLoc = location;
- }
-
- public String CultureName {
- get { return _culture; }
- }
-
- public UltimateResourceFallbackLocation Location {
- get { return _fallbackLoc; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs b/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
index de50cccc33..4ad7b4c93a 100644
--- a/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceFallbackManager.cs
@@ -68,7 +68,7 @@ namespace System.Resources
CultureInfo currentCulture = m_startingCulture;
do
{
- if (m_neutralResourcesCulture != null && currentCulture.Name == m_neutralResourcesCulture.Name)
+ if (m_neutralResourcesCulture != null && currentCulture.Name == m_neutralResourcesCulture.Name)
{
// Return the invariant culture all the time, even if the UltimateResourceFallbackLocation
// is a satellite assembly. This is fixed up later in ManifestBasedResourceGroveler::UltimateFallbackFixup.
@@ -85,180 +85,12 @@ namespace System.Resources
yield break;
}
- // 2. user preferred cultures, omitting starting culture if tried already
- // Compat note: For console apps, this API will return cultures like Arabic
- // or Hebrew that are displayed right-to-left. These don't work with today's
- // CMD.exe. Since not all apps can short-circuit RTL languages to look at
- // US English resources, we're exposing an appcompat flag for this, to make the
- // osFallbackArray an empty array, mimicing our V2 behavior. Apps should instead
- // be using CultureInfo.GetConsoleFallbackUICulture, and then test whether that
- // culture's code page can be displayed on the console, and if not, they should
- // set their culture to their neutral resources language.
- // Note: the app compat switch will omit the OS Preferred fallback culture.
- // Compat note 2: This feature breaks certain apps dependent on fallback to neutral
- // resources. See extensive note in GetResourceFallbackArray.
- CultureInfo[] osFallbackArray = LoadPreferredCultures();
- if (osFallbackArray != null)
- {
- foreach (CultureInfo ci in osFallbackArray)
- {
- // only have to check starting culture and immediate parent for now.
- // in Dev10, revisit this policy.
- if (m_startingCulture.Name != ci.Name && m_startingCulture.Parent.Name != ci.Name)
- {
- yield return ci;
- }
- }
- }
-
- // 3. invariant
+ // 2. invariant
// Don't return invariant twice though.
if (reachedNeutralResourcesCulture)
yield break;
yield return CultureInfo.InvariantCulture;
}
-
- private static CultureInfo[] LoadPreferredCultures()
- {
- // The list of preferred cultures includes thread, process, user, and OS
- // information and may theoretically change every time we call it.
- // The caching does save us some allocations - this complexity saved about
- // 7% of the wall clock time on a US English machine, and may save more on non-English
- // boxes (since the fallback list may be longer).
- String[] cultureNames = GetResourceFallbackArray();
- if (cultureNames == null)
- return null;
-
- bool useCachedNames = (cachedOsFallbackArray != null && cultureNames.Length == cachedOsFallbackArray.Length);
- if (useCachedNames)
- {
- for (int i = 0; i < cultureNames.Length; i++)
- {
- if (!String.Equals(cultureNames[i], cachedOsFallbackArray[i].Name))
- {
- useCachedNames = false;
- break;
- }
- }
- }
- if (useCachedNames)
- return cachedOsFallbackArray;
-
- cachedOsFallbackArray = LoadCulturesFromNames(cultureNames);
- return cachedOsFallbackArray;
- }
-
- private static CultureInfo[] LoadCulturesFromNames(String[] cultureNames)
- {
- if (cultureNames == null)
- return null;
-
- CultureInfo[] cultures = new CultureInfo[cultureNames.Length];
- int culturesIndex = 0;
- for (int i = 0; i < cultureNames.Length; i++)
- {
- // get cached, read-only cultures to avoid excess allocations
- cultures[culturesIndex] = CultureInfo.GetCultureInfo(cultureNames[i]);
- // Note GetCultureInfo can return null for a culture name that we don't support on the current OS.
- // Don't leave a null in the middle of the array.
- if (!Object.ReferenceEquals(cultures[culturesIndex], null))
- culturesIndex++;
- }
-
- // If we couldn't create a culture, return an array of the right length.
- if (culturesIndex != cultureNames.Length)
- {
- CultureInfo[] ret = new CultureInfo[culturesIndex];
- Array.Copy(cultures, ret, culturesIndex);
- cultures = ret;
- }
-
- return cultures;
- }
-
-
- // Note: May return null.
- private static String[] GetResourceFallbackArray()
- {
- // AppCompat note: We've added this feature for desktop V4 but we ripped it out
- // before shipping V4. It shipped in SL 2 and SL 3. We preserved this behavior in SL 4
- // for compat with previous Silverlight releases. We considered re-introducing this in .NET
- // 4.5 for Windows 8 but chose not to because the Windows 8 immersive resources model
- // has been redesigned from the ground up and we chose to support it (for portable libraries
- // only) instead of further enhancing support for the classic resources model.
- // ---------------------------------------------------------------------
- //
- // We have an appcompat problem that prevents us from adopting the ideal MUI model for
- // culture fallback. Up until .NET Framework v4, our fallback was this:
- //
- // CurrentUICulture & parents Neutral
- //
- // We also had applications that took a dependency on falling back to neutral resources.
- // IE, say an app is developed by US English developers - they may include English resources
- // in the main assembly, not ship an "en" satellite assembly, and ship a French satellite.
- // They may also omit the NeutralResourcesLanguageAttribute.
- //
- // Starting with Silverlight v2 and following advice from the MUI team, we wanted to call
- // the OS's GetThreadPreferredUILanguages, inserting the results like this:
- //
- // CurrentUICulture & parents user-preferred fallback OS-preferred fallback Neutral
- //
- // This does not fit well for two reasons:
- // 1) There is no concept of neutral resources in MUI
- // 2) The user-preferred culture fallbacks make no sense in servers & non-interactive apps
- // This leads to bad results on certain combinations of OS language installations, user
- // settings, and applications built in certain styles. The OS-preferred fallback should
- // be last, and the user-preferred fallback just breaks certain apps no matter where you put it.
- //
- // Necessary and sufficient conditions for an AppCompat bug (if we respected user & OS fallbacks):
- // 1) A French OS (ie, you walk into an Internet café in Paris)
- // 2) A .NET application whose neutral resources are authored in English.
- // 3) The application did not provide an English satellite assembly (a common pattern).
- // 4) The application is localized to French.
- // 5) The user wants to read English, expressed in either of two ways:
- // a. Changing Windows’ Display Language in the Regional Options Control Panel
- // b. The application explicitly ASKS THE USER what language to display.
- //
- // Obviously the exact languages above can be interchanged a bit - I’m keeping this concrete.
- // Also the NeutralResourcesLanguageAttribute will allow this to work, but usually we set it
- // to en-US for our assemblies, meaning all other English cultures are broken.
- //
- // Workarounds:
- // *) Use the NeutralResourcesLanguageAttribute and tell us that your neutral resources
- // are in region-neutral English (en).
- // *) Consider shipping a region-neutral English satellite assembly.
-
- // Future work:
- // 2) Consider a mechanism for individual assemblies to opt into wanting user-preferred fallback.
- // They should ship their neutral resources in a satellite assembly, or use the
- // NeutralResourcesLanguageAttribute to say their neutral resources are in a REGION-NEUTRAL
- // language. An appdomain or process-wide flag may not be sufficient.
- // 3) Ask Windows to clarify the scenario for the OS preferred fallback list, to decide whether
- // we should probe there before or after looking at the neutral resources. If we move it
- // to after the neutral resources, ask Windows to return a user-preferred fallback list
- // without the OS preferred fallback included. This is a feature request for
- // GetThreadPreferredUILanguages. We can muddle through without it by removing the OS
- // preferred fallback cultures from end of the combined user + OS preferred fallback list, carefully.
- // 4) Do not look at user-preferred fallback if Environment.UserInteractive is false. (IE,
- // the Windows user who launches ASP.NET shouldn't determine how a web page gets
- // localized - the server itself must respect the remote client's requested languages.)
- // 6) Figure out what should happen in servers (ASP.NET, SQL, NT Services, etc).
- //
- // Done:
- // 1) Got data from Windows on priority of supporting OS preferred fallback. We need to do it.
- // Helps with consistency w/ Windows, and may be necessary for a long tail of other languages
- // (ie, Windows has various degrees of localization support for ~135 languages, and fallbacks
- // to certain languages is important.)
- // 5) Revisited guidance for using the NeutralResourcesLanguageAttribute. Our docs should now say
- // always pick a region-neutral language (ie, "en").
-
-// TODO (matell): I think we actually want to pull this into the PAL on CultureInfo?
-#if FEATURE_COREFX_GLOBALIZATION
- return null;
-#else
- return CultureInfo.nativeGetResourceFallbackArray();
-#endif
- }
}
}
diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs
index f17a7c8f8e..993efddbfc 100644
--- a/src/mscorlib/src/System/Resources/ResourceManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceManager.cs
@@ -14,7 +14,8 @@
**
===========================================================*/
-namespace System.Resources {
+namespace System.Resources
+{
using System;
using System.IO;
using System.Globalization;
@@ -38,20 +39,21 @@ namespace System.Resources {
// allowing us to ask for a WinRT-specific ResourceManager.
// It is important to have WindowsRuntimeResourceManagerBase as regular class with virtual methods and default implementations.
// Defining WindowsRuntimeResourceManagerBase as abstract class or interface will cause issues when adding more methods to it
- // because it’ll create dependency between mscorlib and System.Runtime.WindowsRuntime which will require always shipping both DLLs together.
+ // because it�ll create dependency between mscorlib and System.Runtime.WindowsRuntime which will require always shipping both DLLs together.
// Also using interface or abstract class will not play nice with FriendAccessAllowed.
//
[FriendAccessAllowed]
internal class WindowsRuntimeResourceManagerBase
{
- public virtual bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo){exceptionInfo = null; return false;}
+ public virtual bool Initialize(string libpath, string reswFilename, out PRIExceptionInfo exceptionInfo) { exceptionInfo = null; return false; }
- public virtual String GetString(String stringName, String startingCulture, String neutralResourcesCulture){return null;}
+ public virtual String GetString(String stringName, String startingCulture, String neutralResourcesCulture) { return null; }
- public virtual CultureInfo GlobalResourceContextBestFitCultureInfo {
- get { return null; }
+ public virtual CultureInfo GlobalResourceContextBestFitCultureInfo
+ {
+ get { return null; }
}
-
+
public virtual bool SetGlobalResourceContextDefaultCulture(CultureInfo ci) { return false; }
}
@@ -150,8 +152,8 @@ namespace System.Resources {
[Serializable]
public class ResourceManager
{
-
- internal class CultureNameResourceSetPair {
+ internal class CultureNameResourceSetPair
+ {
public String lastCultureName;
public ResourceSet lastResourceSet;
}
@@ -161,11 +163,11 @@ namespace System.Resources {
// Don't synchronize ResourceSets - too fine-grained a lock to be effective
[Obsolete("call InternalGetResourceSet instead")]
internal Hashtable ResourceSets;
-
+
// don't serialize the cache of ResourceSets
[NonSerialized]
- private Dictionary <String,ResourceSet> _resourceSets;
+ private Dictionary<String, ResourceSet> _resourceSets;
private String moduleDir; // For assembly-ignorant directory location
protected Assembly MainAssembly; // Need the assembly manifest sometimes.
private Type _locationInfo; // For Assembly or type-based directory layout
@@ -182,11 +184,11 @@ namespace System.Resources {
// unused! But need to keep for serialization
[OptionalField(VersionAdded = 1)]
private bool UseSatelliteAssem; // Are all the .resources files in the
- // main assembly, or in satellite assemblies for each culture?
+ // main assembly, or in satellite assemblies for each culture?
#if RESOURCE_SATELLITE_CONFIG
private static volatile Hashtable _installedSatelliteInfo; // Give the user the option
- // to prevent certain satellite assembly probes via a config file.
- // Note that config files are per-appdomain, not per-assembly nor process
+ // to prevent certain satellite assembly probes via a config file.
+ // Note that config files are per-appdomain, not per-assembly nor process
private static volatile bool _checkedConfigFile; // Did we read the app's config file?
#endif
@@ -246,16 +248,16 @@ namespace System.Resources {
// My private debugging aid. Set to 5 or 6 for verbose output. Set to 3
// for summary level information.
internal static readonly int DEBUG = 0; //Making this const causes C# to consider all of the code that it guards unreachable.
-
+
private static volatile bool s_IsAppXModel;
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
private void Init()
{
m_callingAssembly = (RuntimeAssembly)Assembly.GetCallingAssembly();
}
- protected ResourceManager()
+ protected ResourceManager()
{
Init();
@@ -263,7 +265,7 @@ namespace System.Resources {
ResourceManagerMediator mediator = new ResourceManagerMediator(this);
resourceGroveler = new ManifestBasedResourceGroveler(mediator);
}
-
+
// Constructs a Resource Manager for files beginning with
// baseName in the directory specified by resourceDir
// or in the current directory. This Assembly-ignorant constructor is
@@ -274,10 +276,11 @@ namespace System.Resources {
//
// Note: System.Windows.Forms uses this method at design time.
//
- private ResourceManager(String baseName, String resourceDir, Type usingResourceSet) {
- if (null==baseName)
+ private ResourceManager(String baseName, String resourceDir, Type usingResourceSet)
+ {
+ if (null == baseName)
throw new ArgumentNullException(nameof(baseName));
- if (null==resourceDir)
+ if (null == resourceDir)
throw new ArgumentNullException(nameof(resourceDir));
Contract.EndContractBlock();
@@ -296,18 +299,18 @@ namespace System.Resources {
resourceGroveler = new FileBasedResourceGroveler(mediator);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ResourceManager(String baseName, Assembly assembly)
{
- if (null==baseName)
+ if (null == baseName)
throw new ArgumentNullException(nameof(baseName));
- if (null==assembly)
+ if (null == assembly)
throw new ArgumentNullException(nameof(assembly));
Contract.EndContractBlock();
if (!(assembly is RuntimeAssembly))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
MainAssembly = assembly;
BaseNameField = baseName;
@@ -327,23 +330,23 @@ namespace System.Resources {
}
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ResourceManager(String baseName, Assembly assembly, Type usingResourceSet)
{
- if (null==baseName)
+ if (null == baseName)
throw new ArgumentNullException(nameof(baseName));
- if (null==assembly)
+ if (null == assembly)
throw new ArgumentNullException(nameof(assembly));
Contract.EndContractBlock();
if (!(assembly is RuntimeAssembly))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly);
MainAssembly = assembly;
BaseNameField = baseName;
-
+
if (usingResourceSet != null && (usingResourceSet != _minResourceSet) && !(usingResourceSet.IsSubclassOf(_minResourceSet)))
- throw new ArgumentException(Environment.GetResourceString("Arg_ResMgrNotResSet"), nameof(usingResourceSet));
+ throw new ArgumentException(SR.Arg_ResMgrNotResSet, nameof(usingResourceSet));
_userResourceSet = usingResourceSet;
CommonAssemblyInit();
@@ -355,21 +358,21 @@ namespace System.Resources {
if (assembly == typeof(Object).Assembly && m_callingAssembly != assembly)
m_callingAssembly = null;
}
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public ResourceManager(Type resourceSource)
{
- if (null==resourceSource)
+ if (null == resourceSource)
throw new ArgumentNullException(nameof(resourceSource));
Contract.EndContractBlock();
if (!(resourceSource is RuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType);
_locationInfo = resourceSource;
MainAssembly = _locationInfo.Assembly;
BaseNameField = resourceSource.Name;
-
+
SetAppXConfiguration();
CommonAssemblyInit();
@@ -385,9 +388,9 @@ namespace System.Resources {
[OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
- this._resourceSets = null;
- this.resourceGroveler = null;
- this._lastUsedResourceCache = null;
+ _resourceSets = null;
+ resourceGroveler = null;
+ _lastUsedResourceCache = null;
}
[OnDeserialized]
@@ -408,13 +411,13 @@ namespace System.Resources {
}
// correct callingAssembly for v2
- if (this.m_callingAssembly == null)
+ if (m_callingAssembly == null)
{
- this.m_callingAssembly = (RuntimeAssembly)_callingAssembly;
+ m_callingAssembly = (RuntimeAssembly)_callingAssembly;
}
// v2 does this lazily
- if (UseManifest && this._neutralResourcesCulture == null)
+ if (UseManifest && _neutralResourcesCulture == null)
{
_neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, ref _fallbackLoc);
}
@@ -430,7 +433,7 @@ namespace System.Resources {
ResourceSets = new Hashtable(); // for backward compatibility
#pragma warning restore 618
}
-
+
// Trying to unify code as much as possible, even though having to do a
// security check in each constructor prevents it.
@@ -439,8 +442,8 @@ namespace System.Resources {
if (_bUsingModernResourceManagement == false)
{
UseManifest = true;
-
- _resourceSets = new Dictionary<String,ResourceSet>();
+
+ _resourceSets = new Dictionary<String, ResourceSet>();
_lastUsedResourceCache = new CultureNameResourceSetPair();
_fallbackLoc = UltimateResourceFallbackLocation.MainAssembly;
@@ -453,20 +456,23 @@ namespace System.Resources {
}
// Gets the base name for the ResourceManager.
- public virtual String BaseName {
+ public virtual String BaseName
+ {
get { return BaseNameField; }
}
-
+
// Whether we should ignore the capitalization of resources when calling
// GetString or GetObject.
- public virtual bool IgnoreCase {
+ public virtual bool IgnoreCase
+ {
get { return _ignoreCase; }
set { _ignoreCase = value; }
}
// Returns the Type of the ResourceSet the ResourceManager uses
// to construct ResourceSets.
- public virtual Type ResourceSetType {
+ public virtual Type ResourceSetType
+ {
get { return (_userResourceSet == null) ? typeof(RuntimeResourceSet) : _userResourceSet; }
}
@@ -491,13 +497,15 @@ namespace System.Resources {
// If any calls to Close throw, at least leave ourselves in a
// consistent state.
- _resourceSets = new Dictionary<String,ResourceSet>();
+ _resourceSets = new Dictionary<String, ResourceSet>();
_lastUsedResourceCache = new CultureNameResourceSetPair();
-
- lock(localResourceSets) {
+
+ lock (localResourceSets)
+ {
IDictionaryEnumerator setEnum = localResourceSets.GetEnumerator();
- while (setEnum.MoveNext()) {
+ while (setEnum.MoveNext())
+ {
((ResourceSet)setEnum.Value).Close();
}
}
@@ -507,7 +515,7 @@ namespace System.Resources {
{
return new ResourceManager(baseName, resourceDir, usingResourceSet);
}
-
+
// Given a CultureInfo, GetResourceFileName generates the name for
// the binary file for the given CultureInfo. This method uses
// CultureInfo's Name property as part of the file name for all cultures
@@ -518,7 +526,8 @@ namespace System.Resources {
//
// This method can be overriden to look for a different extension,
// such as ".ResX", or a completely different format for naming files.
- protected virtual String GetResourceFileName(CultureInfo culture) {
+ 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.
@@ -537,24 +546,26 @@ namespace System.Resources {
internal ResourceSet GetFirstResourceSet(CultureInfo culture)
{
// Logic from ResourceFallbackManager.GetEnumerator()
- if (_neutralResourcesCulture != null && culture.Name == _neutralResourcesCulture.Name)
+ if (_neutralResourcesCulture != null && culture.Name == _neutralResourcesCulture.Name)
{
culture = CultureInfo.InvariantCulture;
}
- if(_lastUsedResourceCache != null) {
- lock (_lastUsedResourceCache) {
+ if (_lastUsedResourceCache != null)
+ {
+ lock (_lastUsedResourceCache)
+ {
if (culture.Name == _lastUsedResourceCache.lastCultureName)
return _lastUsedResourceCache.lastResourceSet;
}
}
// Look in the ResourceSet table
- Dictionary<String,ResourceSet> localResourceSets = _resourceSets;
+ Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
ResourceSet rs = null;
- if (localResourceSets != null)
+ if (localResourceSets != null)
{
- lock (localResourceSets)
+ lock (localResourceSets)
{
localResourceSets.TryGetValue(culture.Name, out rs);
}
@@ -563,8 +574,10 @@ namespace System.Resources {
if (rs != null)
{
// update the cache with the most recent ResourceSet
- if (_lastUsedResourceCache != null) {
- lock (_lastUsedResourceCache) {
+ if (_lastUsedResourceCache != null)
+ {
+ lock (_lastUsedResourceCache)
+ {
_lastUsedResourceCache.lastCultureName = culture.Name;
_lastUsedResourceCache.lastResourceSet = rs;
}
@@ -574,7 +587,7 @@ namespace System.Resources {
return null;
}
-
+
// Looks up a set of resources for a particular CultureInfo. This is
// not useful for most users of the ResourceManager - call
// GetString() or GetObject() instead.
@@ -583,16 +596,19 @@ namespace System.Resources {
// if it hasn't yet been loaded and if parent CultureInfos should be
// loaded as well for resource inheritance.
//
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable
- public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) {
- if (null==culture)
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public virtual ResourceSet GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
+ {
+ if (null == culture)
throw new ArgumentNullException(nameof(culture));
Contract.EndContractBlock();
- Dictionary<String,ResourceSet> localResourceSets = _resourceSets;
+ Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
ResourceSet rs;
- if (localResourceSets != null) {
- lock (localResourceSets) {
+ if (localResourceSets != null)
+ {
+ lock (localResourceSets)
+ {
if (localResourceSets.TryGetValue(culture.Name, out rs))
return rs;
}
@@ -600,13 +616,15 @@ namespace System.Resources {
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- if (UseManifest && culture.HasInvariantCultureName) {
+ if (UseManifest && culture.HasInvariantCultureName)
+ {
string fileName = GetResourceFileName(culture);
RuntimeAssembly mainAssembly = (RuntimeAssembly)MainAssembly;
Stream stream = mainAssembly.GetManifestResourceStream(_locationInfo, fileName, m_callingAssembly == MainAssembly, ref stackMark);
- if (createIfNotExists && stream!=null) {
+ if (createIfNotExists && stream != null)
+ {
rs = ((ManifestBasedResourceGroveler)resourceGroveler).CreateResourceSet(stream, MainAssembly);
- AddResourceSet(localResourceSets, culture.Name, ref rs);
+ AddResourceSet(localResourceSets, culture.Name, ref rs);
return rs;
}
}
@@ -626,13 +644,13 @@ namespace System.Resources {
// for getting a resource set lives. Access to it is controlled by
// threadsafe methods such as GetResourceSet, GetString, & GetObject.
// This will take a minimal number of locks.
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ protected virtual ResourceSet InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents)
{
Debug.Assert(culture != null, "culture != null");
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return InternalGetResourceSet(culture,createIfNotExists,tryParents, ref stackMark);
+ return InternalGetResourceSet(culture, createIfNotExists, tryParents, ref stackMark);
}
// InternalGetResourceSet is a non-threadsafe method where all the logic
@@ -644,8 +662,10 @@ namespace System.Resources {
Dictionary<String, ResourceSet> localResourceSets = _resourceSets;
ResourceSet rs = null;
CultureInfo foundCulture = null;
- lock (localResourceSets) {
- if (localResourceSets.TryGetValue(requestedCulture.Name, out rs)) {
+ lock (localResourceSets)
+ {
+ if (localResourceSets.TryGetValue(requestedCulture.Name, out rs))
+ {
return rs;
}
}
@@ -654,10 +674,12 @@ namespace System.Resources {
foreach (CultureInfo currentCultureInfo in mgr)
{
- lock(localResourceSets) {
- if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs)) {
+ lock (localResourceSets)
+ {
+ if (localResourceSets.TryGetValue(currentCultureInfo.Name, out rs))
+ {
// we need to update the cache if we fellback
- if(requestedCulture != currentCultureInfo) foundCulture = currentCultureInfo;
+ if (requestedCulture != currentCultureInfo) foundCulture = currentCultureInfo;
break;
}
}
@@ -668,7 +690,7 @@ namespace System.Resources {
// Assembly load event, which could fail then call back into the
// ResourceManager). It's happened.
- rs = resourceGroveler.GrovelForResourceSet(currentCultureInfo, localResourceSets,
+ rs = resourceGroveler.GrovelForResourceSet(currentCultureInfo, localResourceSets,
tryParents, createIfNotExists, ref stackMark);
// found a ResourceSet; we're done
@@ -677,7 +699,6 @@ namespace System.Resources {
foundCulture = currentCultureInfo;
break;
}
-
}
if (rs != null && foundCulture != null)
@@ -696,23 +717,26 @@ namespace System.Resources {
{
break;
}
- }
+ }
}
return rs;
}
// Simple helper to ease maintenance and improve readability.
- private static void AddResourceSet(Dictionary<String,ResourceSet> localResourceSets, String cultureName, ref ResourceSet rs)
+ private static void AddResourceSet(Dictionary<String, ResourceSet> localResourceSets, String cultureName, ref ResourceSet rs)
{
// InternalGetResourceSet is both recursive and reentrant -
// assembly load callbacks in particular are a way we can call
// back into the ResourceManager in unexpectedly on the same thread.
- lock(localResourceSets) {
+ lock (localResourceSets)
+ {
// If another thread added this culture, return that.
ResourceSet lostRace;
- if (localResourceSets.TryGetValue(cultureName, out lostRace)) {
- if (!Object.ReferenceEquals(lostRace, rs)) {
+ if (localResourceSets.TryGetValue(cultureName, out lostRace))
+ {
+ if (!Object.ReferenceEquals(lostRace, rs))
+ {
// Note: In certain cases, we can be trying to add a ResourceSet for multiple
// cultures on one thread, while a second thread added another ResourceSet for one
// of those cultures. If there is a race condition we must make sure our ResourceSet
@@ -722,7 +746,8 @@ namespace System.Resources {
rs = lostRace;
}
}
- else {
+ else
+ {
localResourceSets.Add(cultureName, rs);
}
}
@@ -731,8 +756,9 @@ namespace System.Resources {
protected static Version GetSatelliteContractVersion(Assembly a)
{
// Ensure that the assembly reference is not null
- if (a == null) {
- throw new ArgumentNullException(nameof(a), Environment.GetResourceString("ArgumentNull_Assembly"));
+ if (a == null)
+ {
+ throw new ArgumentNullException(nameof(a), SR.ArgumentNull_Assembly);
}
Contract.EndContractBlock();
@@ -752,7 +778,7 @@ namespace System.Resources {
// IGNORES VERSION
internal static bool CompareNames(String asmTypeName1,
- String typeName2,
+ String typeName2,
AssemblyName asmName2)
{
Debug.Assert(asmTypeName1 != null, "asmTypeName1 was unexpectedly null");
@@ -770,7 +796,7 @@ namespace System.Resources {
// Now, compare assembly display names (IGNORES VERSION AND PROCESSORARCHITECTURE)
// also, for mscorlib ignores everything, since that's what the binder is going to do
- while(Char.IsWhiteSpace(asmTypeName1[++comma]));
+ while (Char.IsWhiteSpace(asmTypeName1[++comma])) ;
// case insensitive
AssemblyName an1 = new AssemblyName(asmTypeName1.Substring(comma));
@@ -793,12 +819,14 @@ namespace System.Resources {
byte[] pkt1 = an1.GetPublicKeyToken();
byte[] pkt2 = asmName2.GetPublicKeyToken();
- if ((pkt1 != null) && (pkt2 != null)) {
+ if ((pkt1 != null) && (pkt2 != null))
+ {
if (pkt1.Length != pkt2.Length)
return false;
- for(int i=0; i < pkt1.Length; i++) {
- if(pkt1[i] != pkt2[i])
+ for (int i = 0; i < pkt1.Length; i++)
+ {
+ if (pkt1[i] != pkt2[i])
return false;
}
}
@@ -807,15 +835,16 @@ namespace System.Resources {
}
#if FEATURE_APPX
- private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture) {
+ private string GetStringFromPRI(String stringName, String startingCulture, String neutralResourcesCulture)
+ {
Debug.Assert(_bUsingModernResourceManagement);
Debug.Assert(_WinRTResourceManager != null);
Debug.Assert(_PRIonAppXInitialized);
Debug.Assert(AppDomain.IsAppXModel());
-
+
if (stringName.Length == 0)
return null;
-
+
string resourceString = null;
// Do not handle exceptions. See the comment in SetAppXConfiguration about throwing
@@ -824,7 +853,7 @@ namespace System.Resources {
stringName,
String.IsNullOrEmpty(startingCulture) ? null : startingCulture,
String.IsNullOrEmpty(neutralResourcesCulture) ? null : neutralResourcesCulture);
-
+
return resourceString;
}
@@ -882,9 +911,9 @@ namespace System.Resources {
if ((platformResourceRoots != null) && (platformResourceRoots != String.Empty))
{
string resourceAssemblyPath = resourcesAssembly.Location;
-
+
// Loop through the PLATFORM_RESOURCE_ROOTS and see if the assembly is contained in it.
- foreach(string pathPlatformResourceRoot in platformResourceRoots.Split(Path.PathSeparator))
+ foreach (string pathPlatformResourceRoot in platformResourceRoots.Split(Path.PathSeparator))
{
if (resourceAssemblyPath.StartsWith(pathPlatformResourceRoot, StringComparison.CurrentCultureIgnoreCase))
{
@@ -924,7 +953,7 @@ namespace System.Resources {
{
// Cannot load the WindowsRuntimeResourceManager when in a compilation process, since it
// lives in System.Runtime.WindowsRuntime and only mscorlib may be loaded for execution.
- if (AppDomain.IsAppXModel() && !AppDomain.IsAppXNGen)
+ if (AppDomain.IsAppXModel())
{
s_IsAppXModel = true;
@@ -945,16 +974,17 @@ namespace System.Resources {
WindowsRuntimeResourceManagerBase WRRM = null;
bool bWRRM_Initialized = false;
-
+
if (AppDomain.IsAppXDesignMode())
{
WRRM = GetWinRTResourceManager();
- try {
+ try
+ {
PRIExceptionInfo exceptionInfo; // If the exception info is filled in, we will ignore it.
bWRRM_Initialized = WRRM.Initialize(resourcesAssembly.Location, reswFilename, out exceptionInfo);
bUsingSatelliteAssembliesUnderAppX = !bWRRM_Initialized;
}
- catch(Exception e)
+ catch (Exception e)
{
bUsingSatelliteAssembliesUnderAppX = true;
if (e.IsTransient)
@@ -966,7 +996,7 @@ namespace System.Resources {
{
// See AssemblyNative::IsFrameworkAssembly for details on which kinds of assemblies are considered Framework assemblies.
// The Modern Resource Manager is not used for such assemblies - they continue to use satellite assemblies (i.e. .resources.dll files).
- _bUsingModernResourceManagement = !ShouldUseSatelliteAssemblyResourceLookupUnderAppX(resourcesAssembly);
+ _bUsingModernResourceManagement = !ShouldUseSatelliteAssemblyResourceLookupUnderAppX(resourcesAssembly);
if (_bUsingModernResourceManagement)
{
@@ -989,11 +1019,12 @@ namespace System.Resources {
_WinRTResourceManager = WRRM;
_PRIonAppXInitialized = true;
}
- else
+ else
{
_WinRTResourceManager = GetWinRTResourceManager();
-
- try {
+
+ try
+ {
_PRIonAppXInitialized = _WinRTResourceManager.Initialize(resourcesAssembly.Location, reswFilename, out _PRIExceptionInfo);
// Note that _PRIExceptionInfo might be null - this is OK.
@@ -1007,12 +1038,12 @@ namespace System.Resources {
// and since they are part of the portable profile, we cannot start throwing a new exception type
// as that would break existing portable libraries. Hence we must save the exception information
// now and throw the exception on the first call to GetString.
- catch(FileNotFoundException)
+ catch (FileNotFoundException)
{
// We will throw MissingManifestResource_NoPRIresources from GetString
// when we see that _PRIonAppXInitialized is false.
}
- catch(Exception e)
+ catch (Exception e)
{
// ERROR_MRM_MAP_NOT_FOUND can be thrown by the call to ResourceManager.get_AllResourceMaps
// in WindowsRuntimeResourceManager.Initialize.
@@ -1053,31 +1084,33 @@ namespace System.Resources {
// current thread's CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
//
- public virtual String GetString(String name) {
+ public virtual String GetString(String name)
+ {
return GetString(name, (CultureInfo)null);
}
-
+
// Looks up a resource value for a particular name. Looks in the
// specified CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
//
- public virtual String GetString(String name, CultureInfo culture) {
- if (null==name)
+ public virtual String GetString(String name, CultureInfo culture)
+ {
+ if (null == name)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
#if FEATURE_APPX
- if(s_IsAppXModel)
+ if (s_IsAppXModel)
{
- // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture,
- // null it out, so that we re-compute it. If we use modern resource lookup, we may end up getting a "better"
- // match, since CultureInfo objects can't represent all the different languages the AppX resource model supports.
- // For classic resources, this causes us to ignore the languages list and instead use the older Win32 behavior,
- // which is the design choice we've made. (See the call a little later to GetCurrentUICultureNoAppX()).
- if(Object.ReferenceEquals(culture, CultureInfo.CurrentUICulture))
- {
- culture = null;
- }
+ // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture,
+ // null it out, so that we re-compute it. If we use modern resource lookup, we may end up getting a "better"
+ // match, since CultureInfo objects can't represent all the different languages the AppX resource model supports.
+ // For classic resources, this causes us to ignore the languages list and instead use the older Win32 behavior,
+ // which is the design choice we've made. (See the call a little later to GetCurrentUICultureNoAppX()).
+ if (Object.ReferenceEquals(culture, CultureInfo.CurrentUICulture))
+ {
+ culture = null;
+ }
}
if (_bUsingModernResourceManagement)
@@ -1087,11 +1120,11 @@ namespace System.Resources {
// Always throw if we did not fully succeed in initializing the WinRT Resource Manager.
if (_PRIExceptionInfo != null && _PRIExceptionInfo._PackageSimpleName != null && _PRIExceptionInfo._ResWFile != null)
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_ResWFileNotLoaded", _PRIExceptionInfo._ResWFile, _PRIExceptionInfo._PackageSimpleName));
+ throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_ResWFileNotLoaded, _PRIExceptionInfo._ResWFile, _PRIExceptionInfo._PackageSimpleName));
- throw new MissingManifestResourceException(Environment.GetResourceString("MissingManifestResource_NoPRIresources"));
+ throw new MissingManifestResourceException(SR.MissingManifestResource_NoPRIresources);
}
-
+
// Throws WinRT hresults.
return GetStringFromPRI(name,
culture == null ? null : culture.Name,
@@ -1100,10 +1133,11 @@ namespace System.Resources {
else
#endif // FEATURE_APPX
{
- if (null==culture) {
+ if (culture == null)
+ {
// 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 = Thread.CurrentThread.GetCurrentUICultureNoAppX();
+ culture = CultureInfo.GetCurrentUICultureNoAppX();
}
ResourceSet last = GetFirstResourceSet(culture);
@@ -1114,25 +1148,28 @@ namespace System.Resources {
if (value != null)
return value;
}
-
-
+
+
// This is the CultureInfo hierarchy traversal code for resource
// lookups, similar but necessarily orthogonal to the ResourceSet
// lookup logic.
ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true);
- foreach (CultureInfo currentCultureInfo in mgr) {
-
+ foreach (CultureInfo currentCultureInfo in mgr)
+ {
ResourceSet rs = InternalGetResourceSet(currentCultureInfo, true, true);
if (rs == null)
break;
- if (rs != last) {
+ if (rs != last)
+ {
String value = rs.GetString(name, _ignoreCase);
if (value != null)
{
// update last used ResourceSet
- if (_lastUsedResourceCache != null) {
- lock (_lastUsedResourceCache) {
+ if (_lastUsedResourceCache != null)
+ {
+ lock (_lastUsedResourceCache)
+ {
_lastUsedResourceCache.lastCultureName = currentCultureInfo.Name;
_lastUsedResourceCache.lastResourceSet = rs;
}
@@ -1147,46 +1184,49 @@ namespace System.Resources {
return null;
}
-
-
+
+
// Looks up a resource value for a particular name. Looks in the
// current thread's CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
//
- public virtual Object GetObject(String name) {
+ public virtual Object GetObject(String name)
+ {
return GetObject(name, (CultureInfo)null, true);
}
-
+
// Looks up a resource value for a particular name. Looks in the
// specified CultureInfo, and if not found, all parent CultureInfos.
// Returns null if the resource wasn't found.
- public virtual Object GetObject(String name, CultureInfo culture) {
+ public virtual Object GetObject(String name, CultureInfo culture)
+ {
return GetObject(name, culture, true);
}
private Object GetObject(String name, CultureInfo culture, bool wrapUnmanagedMemStream)
{
- if (null==name)
+ if (null == name)
throw new ArgumentNullException(nameof(name));
Contract.EndContractBlock();
#if FEATURE_APPX
- if(s_IsAppXModel)
+ if (s_IsAppXModel)
{
- // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture,
- // null it out, so that we re-compute it based on the Win32 value and not the AppX language list value.
- // (See the call a little later to GetCurrentUICultureNoAppX()).
- if(Object.ReferenceEquals(culture, CultureInfo.CurrentUICulture))
- {
- culture = null;
- }
+ // If the caller explictily passed in a culture that was obtained by calling CultureInfo.CurrentUICulture,
+ // null it out, so that we re-compute it based on the Win32 value and not the AppX language list value.
+ // (See the call a little later to GetCurrentUICultureNoAppX()).
+ if (Object.ReferenceEquals(culture, CultureInfo.CurrentUICulture))
+ {
+ culture = null;
+ }
}
#endif
- if (null==culture) {
+ if (null == culture)
+ {
// 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 = Thread.CurrentThread.GetCurrentUICultureNoAppX();
+ culture = CultureInfo.GetCurrentUICultureNoAppX();
}
ResourceSet last = GetFirstResourceSet(culture);
@@ -1194,7 +1234,7 @@ namespace System.Resources {
{
Object value = last.GetObject(name, _ignoreCase);
- if (value != null)
+ if (value != null)
{
UnmanagedMemoryStream stream = value as UnmanagedMemoryStream;
if (stream != null && wrapUnmanagedMemStream)
@@ -1203,13 +1243,14 @@ namespace System.Resources {
return value;
}
}
-
+
// This is the CultureInfo hierarchy traversal code for resource
// lookups, similar but necessarily orthogonal to the ResourceSet
// lookup logic.
ResourceFallbackManager mgr = new ResourceFallbackManager(culture, _neutralResourcesCulture, true);
-
- foreach (CultureInfo currentCultureInfo in mgr) {
+
+ foreach (CultureInfo currentCultureInfo in mgr)
+ {
// Note: Technically this method should be passed in a stack crawl mark that we then pass
// to InternalGetResourceSet for ensuring we demand permissions to read your private resources
// if you're reading resources from an assembly other than yourself. But, we must call our
@@ -1219,12 +1260,16 @@ namespace System.Resources {
if (rs == null)
break;
- if (rs != last) {
+ if (rs != last)
+ {
Object value = rs.GetObject(name, _ignoreCase);
- if (value != null) {
+ if (value != null)
+ {
// update the last used ResourceSet
- if (_lastUsedResourceCache != null) {
- lock (_lastUsedResourceCache) {
+ if (_lastUsedResourceCache != null)
+ {
+ lock (_lastUsedResourceCache)
+ {
_lastUsedResourceCache.lastCultureName = currentCultureInfo.Name;
_lastUsedResourceCache.lastResourceSet = rs;
}
@@ -1244,15 +1289,17 @@ namespace System.Resources {
return null;
}
- public UnmanagedMemoryStream GetStream(String name) {
+ public UnmanagedMemoryStream GetStream(String name)
+ {
return GetStream(name, (CultureInfo)null);
}
-
- public UnmanagedMemoryStream GetStream(String name, CultureInfo culture) {
+
+ public UnmanagedMemoryStream GetStream(String name, CultureInfo culture)
+ {
Object obj = GetObject(name, culture, false);
UnmanagedMemoryStream ums = obj as UnmanagedMemoryStream;
if (ums == null && obj != null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotStream_Name", name));
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name));
return ums;
}
@@ -1261,9 +1308,12 @@ namespace System.Resources {
// satellite assembly probes for certain cultures via a config file.
private bool TryLookingForSatellite(CultureInfo lookForCulture)
{
- if (!_checkedConfigFile) {
- lock (this) {
- if (!_checkedConfigFile) {
+ if (!_checkedConfigFile)
+ {
+ lock (this)
+ {
+ if (!_checkedConfigFile)
+ {
_checkedConfigFile = true;
_installedSatelliteInfo = GetSatelliteAssembliesFromConfig();
}
@@ -1273,7 +1323,7 @@ namespace System.Resources {
if (_installedSatelliteInfo == null)
return true;
- String[] installedSatellites = (String[]) _installedSatelliteInfo[MainAssembly.FullName];
+ String[] installedSatellites = (String[])_installedSatelliteInfo[MainAssembly.FullName];
if (installedSatellites == null)
return true;
@@ -1317,7 +1367,7 @@ namespace System.Resources {
get { return _rm._locationInfo; }
}
- internal Type UserResourceSet
+ internal Type UserResourceSet
{
get { return _rm._userResourceSet; }
}
@@ -1358,7 +1408,7 @@ namespace System.Resources {
internal UltimateResourceFallbackLocation FallbackLoc
{
- get { return _rm.FallbackLocation; }
+ get { return _rm.FallbackLocation; }
set { _rm._fallbackLoc = value; }
}
diff --git a/src/mscorlib/src/System/Resources/ResourceReader.cs b/src/mscorlib/src/System/Resources/ResourceReader.cs
index d752771020..9734343f92 100644
--- a/src/mscorlib/src/System/Resources/ResourceReader.cs
+++ b/src/mscorlib/src/System/Resources/ResourceReader.cs
@@ -14,7 +14,9 @@
** Version 2 support on October 6, 2003
**
===========================================================*/
-namespace System.Resources {
+
+namespace System.Resources
+{
using System;
using System.IO;
using System.Text;
@@ -47,14 +49,16 @@ namespace System.Resources {
_value = value;
}
- internal int DataPosition {
+ internal int DataPosition
+ {
get { return _dataPos; }
//set { _dataPos = value; }
}
// Allows adding in profiling data in a future version, or a special
// resource profiling build. We could also use WeakReference.
- internal Object Value {
+ internal Object Value
+ {
get { return _value; }
set { _value = value; }
}
@@ -63,7 +67,7 @@ namespace System.Resources {
{
Debug.Assert(value >= 0, "negative ResourceTypeCode. What?");
return value <= ResourceTypeCode.LastPrimitive;
- }
+ }
}
@@ -111,23 +115,25 @@ namespace System.Resources {
{
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
_store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.RandomAccess), Encoding.UTF8);
- BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(String). UnmanagedMemoryStream: "+(_ums!=null));
+ BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(String). UnmanagedMemoryStream: " + (_ums != null));
- try {
+ try
+ {
ReadResources();
}
- catch {
+ catch
+ {
_store.Close(); // If we threw an exception, close the file.
throw;
}
}
-
+
public ResourceReader(Stream stream)
{
- if (stream==null)
+ if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (!stream.CanRead)
- throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotReadable"));
+ throw new ArgumentException(SR.Argument_StreamNotReadable);
Contract.EndContractBlock();
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
@@ -135,10 +141,10 @@ namespace System.Resources {
// We have a faster code path for reading resource files from an assembly.
_ums = stream as UnmanagedMemoryStream;
- BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(Stream). UnmanagedMemoryStream: "+(_ums!=null));
+ BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(Stream). UnmanagedMemoryStream: " + (_ums != null));
ReadResources();
}
-
+
// This is the constructor the RuntimeResourceSet calls,
// passing in the stream to read from and the RuntimeResourceSet's
// internal hash table (hash table of names with file offsets
@@ -154,16 +160,16 @@ namespace System.Resources {
_ums = stream as UnmanagedMemoryStream;
- BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(Stream, Hashtable). UnmanagedMemoryStream: "+(_ums!=null));
+ BCLDebug.Log("RESMGRFILEFORMAT", "ResourceReader .ctor(Stream, Hashtable). UnmanagedMemoryStream: " + (_ums != null));
ReadResources();
}
-
+
public void Close()
{
Dispose(true);
}
-
+
public void Dispose()
{
Close();
@@ -171,9 +177,11 @@ namespace System.Resources {
private unsafe void Dispose(bool disposing)
{
- if (_store != null) {
+ if (_store != null)
+ {
_resCache = null;
- if (disposing) {
+ if (disposing)
+ {
// Close the stream in a thread-safe way. This fix means
// that we may call Close n times, but that's safe.
BinaryReader copyOfStore = _store;
@@ -189,27 +197,29 @@ namespace System.Resources {
_nameHashesPtr = null;
}
}
-
+
internal static unsafe int ReadUnalignedI4(int* p)
{
byte* buffer = (byte*)p;
// Unaligned, little endian format
return buffer[0] | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
}
-
- private void SkipString() {
+
+ private void SkipString()
+ {
int stringLength = _store.Read7BitEncodedInt();
- if (stringLength < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
+ if (stringLength < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
_store.BaseStream.Seek(stringLength, SeekOrigin.Current);
}
private unsafe int GetNameHash(int index)
{
- Debug.Assert(index >=0 && index < _numResources, "Bad index into hash array. index: "+index);
- Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
+ Debug.Assert(index >= 0 && index < _numResources, "Bad index into hash array. index: " + index);
+ Debug.Assert((_ums == null && _nameHashes != null && _nameHashesPtr == null) ||
(_ums != null && _nameHashes == null && _nameHashesPtr != null), "Internal state mangled.");
if (_ums == null)
return _nameHashes[index];
@@ -219,16 +229,17 @@ namespace System.Resources {
private unsafe int GetNamePosition(int index)
{
- Debug.Assert(index >=0 && index < _numResources, "Bad index into name position array. index: "+index);
- Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
+ Debug.Assert(index >= 0 && index < _numResources, "Bad index into name position array. index: " + index);
+ Debug.Assert((_ums == null && _namePositions != null && _namePositionsPtr == null) ||
(_ums != null && _namePositions == null && _namePositionsPtr != null), "Internal state mangled.");
int r;
if (_ums == null)
r = _namePositions[index];
else
r = ReadUnalignedI4(&_namePositionsPtr[index]);
- if (r < 0 || r > _dataSectionOffset - _nameSectionOffset) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", r));
+ if (r < 0 || r > _dataSectionOffset - _nameSectionOffset)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, r));
}
return r;
}
@@ -241,7 +252,7 @@ namespace System.Resources {
public IDictionaryEnumerator GetEnumerator()
{
if (_resCache == null)
- throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
+ throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return new ResourceEnumerator(this);
}
@@ -258,14 +269,15 @@ namespace System.Resources {
{
Debug.Assert(_store != null, "ResourceReader is closed!");
int hash = FastResourceComparer.HashFunction(name);
- BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for "+name+" hash: "+hash.ToString("x", CultureInfo.InvariantCulture));
+ BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for " + name + " hash: " + hash.ToString("x", CultureInfo.InvariantCulture));
// Binary search over the hashes. Use the _namePositions array to
// determine where they exist in the underlying stream.
int lo = 0;
int hi = _numResources - 1;
int index = -1;
bool success = false;
- while (lo <= hi) {
+ while (lo <= hi)
+ {
index = (lo + hi) >> 1;
// Do NOT use subtraction here, since it will wrap for large
// negative numbers.
@@ -278,7 +290,8 @@ namespace System.Resources {
else
c = 1;
//BCLDebug.Log("RESMGRFILEFORMAT", " Probing index "+index+" lo: "+lo+" hi: "+hi+" c: "+c);
- if (c == 0) {
+ if (c == 0)
+ {
success = true;
break;
}
@@ -287,7 +300,8 @@ namespace System.Resources {
else
hi = index - 1;
}
- if (!success) {
+ if (!success)
+ {
#if RESOURCE_FILE_FORMAT_DEBUG
String lastReadString;
lock(this) {
@@ -298,36 +312,42 @@ namespace System.Resources {
#endif
return -1;
}
-
+
// index is the location in our hash array that corresponds with a
// value in the namePositions array.
// There could be collisions in our hash function. Check on both sides
// of index to find the range of hash values that are equal to the
// target hash value.
- if (lo != index) {
+ if (lo != index)
+ {
lo = index;
while (lo > 0 && GetNameHash(lo - 1) == hash)
lo--;
}
- if (hi != index) {
+ if (hi != index)
+ {
hi = index;
while (hi < _numResources - 1 && GetNameHash(hi + 1) == hash)
hi++;
}
- lock(this) {
- for(int i = lo; i<=hi; i++) {
+ lock (this)
+ {
+ for (int i = lo; i <= hi; i++)
+ {
_store.BaseStream.Seek(_nameSectionOffset + GetNamePosition(i), SeekOrigin.Begin);
- if (CompareStringEqualsName(name)) {
+ if (CompareStringEqualsName(name))
+ {
int dataPos = _store.ReadInt32();
- if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataPos));
+ if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataPos));
}
return dataPos;
}
}
}
- BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for "+name+": Found a hash collision, HOWEVER, neither of these collided values equaled the given string.");
+ BCLDebug.Log("RESMGRFILEFORMAT", "FindPosForResource for " + name + ": Found a hash collision, HOWEVER, neither of these collided values equaled the given string.");
return -1;
}
@@ -339,15 +359,18 @@ namespace System.Resources {
{
Debug.Assert(_store != null, "ResourceReader is closed!");
int byteLen = _store.Read7BitEncodedInt();
- if (byteLen < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
+ if (byteLen < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
- if (_ums != null) {
+ if (_ums != null)
+ {
byte* bytes = _ums.PositionPointer;
// Skip over the data in the Stream, positioning ourselves right after it.
_ums.Seek(byteLen, SeekOrigin.Current);
- if (_ums.Position > _ums.Length) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameTooLong"));
+ if (_ums.Position > _ums.Length)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesNameTooLong);
}
// On 64-bit machines, these char*'s may be misaligned. Use a
@@ -355,17 +378,19 @@ namespace System.Resources {
//return FastResourceComparer.CompareOrdinal((char*)bytes, byteLen/2, name) == 0;
return FastResourceComparer.CompareOrdinal(bytes, byteLen, name) == 0;
}
- else {
+ else
+ {
// This code needs to be fast
byte[] bytes = new byte[byteLen];
int numBytesToRead = byteLen;
- while(numBytesToRead > 0) {
+ while (numBytesToRead > 0)
+ {
int n = _store.Read(bytes, byteLen - numBytesToRead, numBytesToRead);
if (n == 0)
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted"));
+ throw new BadImageFormatException(SR.BadImageFormat_ResourceNameCorrupted);
numBytesToRead -= n;
}
- return FastResourceComparer.CompareOrdinal(bytes, byteLen/2, name) == 0;
+ return FastResourceComparer.CompareOrdinal(bytes, byteLen / 2, name) == 0;
}
}
@@ -378,17 +403,20 @@ namespace System.Resources {
byte[] bytes;
int byteLen;
long nameVA = GetNamePosition(index);
- lock (this) {
+ lock (this)
+ {
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
// Can't use _store.ReadString, since it's using UTF-8!
byteLen = _store.Read7BitEncodedInt();
- if (byteLen < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_NegativeStringLength"));
+ if (byteLen < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength);
}
- if (_ums != null) {
+ if (_ums != null)
+ {
if (_ums.Position > _ums.Length - byteLen)
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesIndexTooLong", index));
+ throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourcesIndexTooLong, index));
String s = null;
char* charPtr = (char*)_ums.PositionPointer;
@@ -402,14 +430,15 @@ namespace System.Resources {
}
else {
#endif //IA64
- s = new String(charPtr, 0, byteLen/2);
+ s = new String(charPtr, 0, byteLen / 2);
#if IA64
}
#endif //IA64
_ums.Position += byteLen;
dataOffset = _store.ReadInt32();
- if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataOffset));
+ if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataOffset));
}
return s;
}
@@ -419,15 +448,17 @@ namespace System.Resources {
// Use a blocking read in case the stream doesn't give us back
// everything immediately.
int count = byteLen;
- while(count > 0) {
+ while (count > 0)
+ {
int n = _store.Read(bytes, byteLen - count, count);
if (n == 0)
- throw new EndOfStreamException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted_NameIndex", index));
+ throw new EndOfStreamException(SR.Format(SR.BadImageFormat_ResourceNameCorrupted_NameIndex, index));
count -= n;
}
dataOffset = _store.ReadInt32();
- if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataOffset));
+ if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataOffset));
}
}
return Encoding.Unicode.GetString(bytes, 0, byteLen);
@@ -440,15 +471,17 @@ namespace System.Resources {
{
Debug.Assert(_store != null, "ResourceReader is closed!");
long nameVA = GetNamePosition(index);
- lock(this) {
+ lock (this)
+ {
_store.BaseStream.Seek(nameVA + _nameSectionOffset, SeekOrigin.Begin);
SkipString();
//BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex for index: "+index+" skip (name length): "+skip);
int dataPos = _store.ReadInt32();
- if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dataPos));
+ if (dataPos < 0 || dataPos >= _store.BaseStream.Length - _dataSectionOffset)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataPos));
}
- BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex: dataPos: "+dataPos);
+ BCLDebug.Log("RESMGRFILEFORMAT", "GetValueForNameIndex: dataPos: " + dataPos);
ResourceTypeCode junk;
if (_version == 1)
return LoadObjectV1(dataPos);
@@ -464,30 +497,33 @@ namespace System.Resources {
internal String LoadString(int pos)
{
Debug.Assert(_store != null, "ResourceReader is closed!");
- _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
+ _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
String s = null;
int typeIndex = _store.Read7BitEncodedInt();
- if (_version == 1) {
+ if (_version == 1)
+ {
if (typeIndex == -1)
return null;
if (FindType(typeIndex) != typeof(String))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", FindType(typeIndex).FullName));
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, FindType(typeIndex).FullName));
s = _store.ReadString();
}
- else {
- ResourceTypeCode typeCode = (ResourceTypeCode) typeIndex;
- if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null) {
+ else
+ {
+ ResourceTypeCode typeCode = (ResourceTypeCode)typeIndex;
+ if (typeCode != ResourceTypeCode.String && typeCode != ResourceTypeCode.Null)
+ {
String typeString;
if (typeCode < ResourceTypeCode.StartOfUserTypes)
typeString = typeCode.ToString();
else
typeString = FindType(typeCode - ResourceTypeCode.StartOfUserTypes).FullName;
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Type", typeString));
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, typeString));
}
if (typeCode == ResourceTypeCode.String) // ignore Null
s = _store.ReadString();
}
- BCLDebug.Log("RESMGRFILEFORMAT", "LoadString("+pos.ToString("x", CultureInfo.InvariantCulture)+" returned "+(s==null ? "[a null string]" : s));
+ BCLDebug.Log("RESMGRFILEFORMAT", "LoadString(" + pos.ToString("x", CultureInfo.InvariantCulture) + " returned " + (s == null ? "[a null string]" : s));
return s;
}
@@ -502,7 +538,8 @@ namespace System.Resources {
internal Object LoadObject(int pos, out ResourceTypeCode typeCode)
{
- if (_version == 1) {
+ if (_version == 1)
+ {
Object o = LoadObjectV1(pos);
typeCode = (o is String) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes;
return o;
@@ -519,26 +556,30 @@ namespace System.Resources {
Debug.Assert(_store != null, "ResourceReader is closed!");
Debug.Assert(_version == 1, ".resources file was not a V1 .resources file!");
- try {
+ try
+ {
// mega try-catch performs exceptionally bad on x64; factored out body into
// _LoadObjectV1 and wrap here.
return _LoadObjectV1(pos);
}
- catch (EndOfStreamException eof) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof);
+ catch (EndOfStreamException eof)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
- catch (ArgumentOutOfRangeException e) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), e);
+ catch (ArgumentOutOfRangeException e)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
- private Object _LoadObjectV1(int pos) {
- _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
+ private Object _LoadObjectV1(int pos)
+ {
+ _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
int typeIndex = _store.Read7BitEncodedInt();
if (typeIndex == -1)
return null;
RuntimeType type = FindType(typeIndex);
- BCLDebug.Log("RESMGRFILEFORMAT", "LoadObject type: "+type.Name+" pos: 0x"+_store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture));
+ BCLDebug.Log("RESMGRFILEFORMAT", "LoadObject type: " + type.Name + " pos: 0x" + _store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture));
// Consider putting in logic to see if this type is a
// primitive or a value type first, so we can reach the
// deserialization code faster for arbitrary objects.
@@ -565,21 +606,24 @@ namespace System.Resources {
return _store.ReadSingle();
else if (type == typeof(Double))
return _store.ReadDouble();
- else if (type == typeof(DateTime)) {
+ else if (type == typeof(DateTime))
+ {
// Ideally we should use DateTime's ToBinary & FromBinary,
// but we can't for compatibility reasons.
return new DateTime(_store.ReadInt64());
}
else if (type == typeof(TimeSpan))
return new TimeSpan(_store.ReadInt64());
- else if (type == typeof(Decimal)) {
+ else if (type == typeof(Decimal))
+ {
int[] bits = new int[4];
- for(int i=0; i<bits.Length; i++)
+ for (int i = 0; i < bits.Length; i++)
bits[i] = _store.ReadInt32();
return new Decimal(bits);
}
- else {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
+ else
+ {
+ throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization);
}
}
@@ -588,136 +632,152 @@ namespace System.Resources {
Debug.Assert(_store != null, "ResourceReader is closed!");
Debug.Assert(_version >= 2, ".resources file was not a V2 (or higher) .resources file!");
- try {
+ try
+ {
// mega try-catch performs exceptionally bad on x64; factored out body into
// _LoadObjectV2 and wrap here.
return _LoadObjectV2(pos, out typeCode);
}
- catch (EndOfStreamException eof) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), eof);
+ catch (EndOfStreamException eof)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, eof);
}
- catch (ArgumentOutOfRangeException e) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"), e);
+ catch (ArgumentOutOfRangeException e)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, e);
}
}
- private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) {
- _store.BaseStream.Seek(_dataSectionOffset+pos, SeekOrigin.Begin);
- typeCode = (ResourceTypeCode) _store.Read7BitEncodedInt();
+ private Object _LoadObjectV2(int pos, out ResourceTypeCode typeCode)
+ {
+ _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin);
+ typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt();
- BCLDebug.Log("RESMGRFILEFORMAT", "LoadObjectV2 type: "+typeCode+" pos: 0x"+_store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture));
-
- switch(typeCode) {
- case ResourceTypeCode.Null:
- return null;
+ BCLDebug.Log("RESMGRFILEFORMAT", "LoadObjectV2 type: " + typeCode + " pos: 0x" + _store.BaseStream.Position.ToString("x", CultureInfo.InvariantCulture));
- case ResourceTypeCode.String:
- return _store.ReadString();
-
- case ResourceTypeCode.Boolean:
- return _store.ReadBoolean();
+ switch (typeCode)
+ {
+ case ResourceTypeCode.Null:
+ return null;
- case ResourceTypeCode.Char:
- return (char) _store.ReadUInt16();
+ case ResourceTypeCode.String:
+ return _store.ReadString();
- case ResourceTypeCode.Byte:
- return _store.ReadByte();
+ case ResourceTypeCode.Boolean:
+ return _store.ReadBoolean();
- case ResourceTypeCode.SByte:
- return _store.ReadSByte();
+ case ResourceTypeCode.Char:
+ return (char)_store.ReadUInt16();
- case ResourceTypeCode.Int16:
- return _store.ReadInt16();
+ case ResourceTypeCode.Byte:
+ return _store.ReadByte();
- case ResourceTypeCode.UInt16:
- return _store.ReadUInt16();
+ case ResourceTypeCode.SByte:
+ return _store.ReadSByte();
- case ResourceTypeCode.Int32:
- return _store.ReadInt32();
+ case ResourceTypeCode.Int16:
+ return _store.ReadInt16();
- case ResourceTypeCode.UInt32:
- return _store.ReadUInt32();
+ case ResourceTypeCode.UInt16:
+ return _store.ReadUInt16();
- case ResourceTypeCode.Int64:
- return _store.ReadInt64();
+ case ResourceTypeCode.Int32:
+ return _store.ReadInt32();
- case ResourceTypeCode.UInt64:
- return _store.ReadUInt64();
+ case ResourceTypeCode.UInt32:
+ return _store.ReadUInt32();
- case ResourceTypeCode.Single:
- return _store.ReadSingle();
+ case ResourceTypeCode.Int64:
+ return _store.ReadInt64();
- case ResourceTypeCode.Double:
- return _store.ReadDouble();
+ case ResourceTypeCode.UInt64:
+ return _store.ReadUInt64();
- case ResourceTypeCode.Decimal:
- return _store.ReadDecimal();
-
- case ResourceTypeCode.DateTime:
- // Use DateTime's ToBinary & FromBinary.
- Int64 data = _store.ReadInt64();
- return DateTime.FromBinary(data);
-
- case ResourceTypeCode.TimeSpan:
- Int64 ticks = _store.ReadInt64();
- return new TimeSpan(ticks);
-
- // Special types
- case ResourceTypeCode.ByteArray: {
- int len = _store.ReadInt32();
- if (len < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len));
- }
+ case ResourceTypeCode.Single:
+ return _store.ReadSingle();
+
+ case ResourceTypeCode.Double:
+ return _store.ReadDouble();
+
+ case ResourceTypeCode.Decimal:
+ return _store.ReadDecimal();
- if (_ums == null) {
- if (len > _store.BaseStream.Length) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len));
+ case ResourceTypeCode.DateTime:
+ // Use DateTime's ToBinary & FromBinary.
+ Int64 data = _store.ReadInt64();
+ return DateTime.FromBinary(data);
+
+ case ResourceTypeCode.TimeSpan:
+ Int64 ticks = _store.ReadInt64();
+ return new TimeSpan(ticks);
+
+ // Special types
+ case ResourceTypeCode.ByteArray:
+ {
+ int len = _store.ReadInt32();
+ if (len < 0)
+ {
+ throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
}
- return _store.ReadBytes(len);
- }
- if (len > _ums.Length - _ums.Position) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len));
- }
+ if (_ums == null)
+ {
+ if (len > _store.BaseStream.Length)
+ {
+ throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
+ }
+ return _store.ReadBytes(len);
+ }
- byte[] bytes = new byte[len];
- int r = _ums.Read(bytes, 0, len);
- Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
- return bytes;
- }
+ if (len > _ums.Length - _ums.Position)
+ {
+ throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
+ }
- case ResourceTypeCode.Stream: {
- int len = _store.ReadInt32();
- if (len < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len));
- }
- if (_ums == null) {
- byte[] bytes = _store.ReadBytes(len);
- // Lifetime of memory == lifetime of this stream.
- return new PinnedBufferMemoryStream(bytes);
+ byte[] bytes = new byte[len];
+ int r = _ums.Read(bytes, 0, len);
+ Debug.Assert(r == len, "ResourceReader needs to use a blocking read here. (Call _store.ReadBytes(len)?)");
+ return bytes;
}
- // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream.
- if (len > _ums.Length - _ums.Position) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourceDataLengthInvalid", len));
+ case ResourceTypeCode.Stream:
+ {
+ int len = _store.ReadInt32();
+ if (len < 0)
+ {
+ throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
+ }
+ if (_ums == null)
+ {
+ byte[] bytes = _store.ReadBytes(len);
+ // Lifetime of memory == lifetime of this stream.
+ return new PinnedBufferMemoryStream(bytes);
+ }
+
+ // make sure we don't create an UnmanagedMemoryStream that is longer than the resource stream.
+ if (len > _ums.Length - _ums.Position)
+ {
+ throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, len));
+ }
+
+ // For the case that we've memory mapped in the .resources
+ // file, just return a Stream pointing to that block of memory.
+ unsafe
+ {
+ return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read);
+ }
}
- // For the case that we've memory mapped in the .resources
- // file, just return a Stream pointing to that block of memory.
- unsafe {
- return new UnmanagedMemoryStream(_ums.PositionPointer, len, len, FileAccess.Read);
+ default:
+ if (typeCode < ResourceTypeCode.StartOfUserTypes)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch);
}
- }
-
- default:
- if (typeCode < ResourceTypeCode.StartOfUserTypes) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_TypeMismatch"));
- }
- break;
+ break;
}
// Normal serialized objects
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
+ throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization);
}
@@ -729,16 +789,19 @@ namespace System.Resources {
{
Debug.Assert(_store != null, "ResourceReader is closed!");
- try {
+ try
+ {
// mega try-catch performs exceptionally bad on x64; factored out body into
// _ReadResources and wrap here.
_ReadResources();
}
- catch (EndOfStreamException eof) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"), eof);
+ catch (EndOfStreamException eof)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, eof);
}
- catch (IndexOutOfRangeException e) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"), e);
+ catch (IndexOutOfRangeException e)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, e);
}
}
@@ -748,21 +811,24 @@ namespace System.Resources {
// Check for magic number
int magicNum = _store.ReadInt32();
if (magicNum != ResourceManager.MagicNumber)
- throw new ArgumentException(Environment.GetResourceString("Resources_StreamNotValid"));
+ throw new ArgumentException(SR.Resources_StreamNotValid);
// Assuming this is ResourceManager header V1 or greater, hopefully
// after the version number there is a number of bytes to skip
// to bypass the rest of the ResMgr header. For V2 or greater, we
// use this to skip to the end of the header
int resMgrHeaderVersion = _store.ReadInt32();
int numBytesToSkip = _store.ReadInt32();
- if (numBytesToSkip < 0 || resMgrHeaderVersion < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (numBytesToSkip < 0 || resMgrHeaderVersion < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
- if (resMgrHeaderVersion > 1) {
+ if (resMgrHeaderVersion > 1)
+ {
BCLDebug.Log("RESMGRFILEFORMAT", LogLevel.Status, "ReadResources: Unexpected ResMgr header version: {0} Skipping ahead {1} bytes.", resMgrHeaderVersion, numBytesToSkip);
_store.BaseStream.Seek(numBytesToSkip, SeekOrigin.Current);
}
- else {
+ else
+ {
BCLDebug.Log("RESMGRFILEFORMAT", "ReadResources: Parsing ResMgr header v1.");
// We don't care about numBytesToSkip; read the rest of the header
@@ -773,7 +839,7 @@ namespace System.Resources {
AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName);
if (!ResourceManager.CompareNames(readerType, ResourceManager.ResReaderTypeName, mscorlib))
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_WrongResourceReader_Type", readerType));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_WrongResourceReader_Type, readerType));
// Skip over type name for a suitable ResourceSet
SkipString();
@@ -783,7 +849,7 @@ namespace System.Resources {
// Do file version check
int version = _store.ReadInt32();
if (version != RuntimeResourceSet.Version && version != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_ResourceFileUnsupportedVersion", RuntimeResourceSet.Version, version));
+ throw new ArgumentException(SR.Format(SR.Arg_ResourceFileUnsupportedVersion, RuntimeResourceSet.Version, version));
_version = version;
#if RESOURCE_FILE_FORMAT_DEBUG
@@ -807,8 +873,9 @@ namespace System.Resources {
#endif
_numResources = _store.ReadInt32();
- if (_numResources < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (_numResources < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
BCLDebug.Log("RESMGRFILEFORMAT", "ReadResources: Expecting " + _numResources + " resources.");
#if RESOURCE_FILE_FORMAT_DEBUG
@@ -819,13 +886,15 @@ namespace System.Resources {
// Read type positions into type positions array.
// But delay initialize the type table.
int numTypes = _store.ReadInt32();
- if (numTypes < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (numTypes < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_typeTable = new RuntimeType[numTypes];
_typeNamePositions = new int[numTypes];
- for (int i=0; i<numTypes; i++) {
- _typeNamePositions[i] = (int) _store.BaseStream.Position;
+ for (int i = 0; i < numTypes; i++)
+ {
+ _typeNamePositions[i] = (int)_store.BaseStream.Position;
// Skip over the Strings in the file. Don't create types.
SkipString();
@@ -844,8 +913,10 @@ namespace System.Resources {
// should be aligned No need to verify the byte values.
long pos = _store.BaseStream.Position;
int alignBytes = ((int)pos) & 7;
- if (alignBytes != 0) {
- for (int i = 0; i < 8 - alignBytes; i++) {
+ if (alignBytes != 0)
+ {
+ for (int i = 0; i < 8 - alignBytes; i++)
+ {
_store.ReadByte();
}
}
@@ -858,18 +929,23 @@ namespace System.Resources {
}
#endif
- if (_ums == null) {
+ if (_ums == null)
+ {
_nameHashes = new int[_numResources];
- for (int i = 0; i < _numResources; i++) {
+ for (int i = 0; i < _numResources; i++)
+ {
_nameHashes[i] = _store.ReadInt32();
}
}
- else {
+ else
+ {
int seekPos = unchecked(4 * _numResources);
- if (seekPos < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (seekPos < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
- unsafe {
+ unsafe
+ {
_nameHashesPtr = (int*)_ums.PositionPointer;
// Skip over the array of nameHashes.
_ums.Seek(seekPos, SeekOrigin.Current);
@@ -885,23 +961,29 @@ namespace System.Resources {
_store.BaseStream.Position += 8;
}
#endif
- if (_ums == null) {
+ if (_ums == null)
+ {
_namePositions = new int[_numResources];
- for (int i = 0; i < _numResources; i++) {
+ for (int i = 0; i < _numResources; i++)
+ {
int namePosition = _store.ReadInt32();
- if (namePosition < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (namePosition < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
_namePositions[i] = namePosition;
}
}
- else {
+ else
+ {
int seekPos = unchecked(4 * _numResources);
- if (seekPos < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (seekPos < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
- unsafe {
+ unsafe
+ {
_namePositionsPtr = (int*)_ums.PositionPointer;
// Skip over the array of namePositions.
_ums.Seek(seekPos, SeekOrigin.Current);
@@ -912,16 +994,18 @@ namespace System.Resources {
// Read location of data section.
_dataSectionOffset = _store.ReadInt32();
- if (_dataSectionOffset < 0) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (_dataSectionOffset < 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
// Store current location as start of name section
_nameSectionOffset = _store.BaseStream.Position;
// _nameSectionOffset should be <= _dataSectionOffset; if not, it's corrupt
- if (_dataSectionOffset < _nameSectionOffset) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"));
+ if (_dataSectionOffset < _nameSectionOffset)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted);
}
BCLDebug.Log("RESMGRFILEFORMAT", String.Format(CultureInfo.InvariantCulture, "ReadResources: _nameOffset = 0x{0:x} _dataOffset = 0x{1:x}", _nameSectionOffset, _dataSectionOffset));
@@ -932,12 +1016,15 @@ namespace System.Resources {
// and initialize Reflection.
private RuntimeType FindType(int typeIndex)
{
- if (typeIndex < 0 || typeIndex >= _typeTable.Length) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_InvalidType"));
+ if (typeIndex < 0 || typeIndex >= _typeTable.Length)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
- if (_typeTable[typeIndex] == null) {
+ if (_typeTable[typeIndex] == null)
+ {
long oldPos = _store.BaseStream.Position;
- try {
+ try
+ {
_store.BaseStream.Position = _typeNamePositions[typeIndex];
String typeName = _store.ReadString();
_typeTable[typeIndex] = (RuntimeType)Type.GetType(typeName, true);
@@ -954,9 +1041,10 @@ namespace System.Resources {
// getting to Type.GetType -- this is costly with v1 resource formats.
catch (FileNotFoundException)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ResourceObjectSerialization"));
+ throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization);
}
- finally {
+ finally
+ {
_store.BaseStream.Position = oldPos;
}
}
@@ -971,7 +1059,7 @@ namespace System.Resources {
throw new ArgumentNullException(nameof(resourceName));
Contract.EndContractBlock();
if (_resCache == null)
- throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
+ throw new InvalidOperationException(SR.ResourceReaderIsClosed);
// Get the type information from the data section. Also,
// sort all of the data section's indexes to compute length of
@@ -979,24 +1067,29 @@ namespace System.Resources {
// off the length of the type code).
int[] sortedDataPositions = new int[_numResources];
int dataPos = FindPosForResource(resourceName);
- if( dataPos == -1) {
- throw new ArgumentException(Environment.GetResourceString("Arg_ResourceNameNotExist", resourceName));
+ if (dataPos == -1)
+ {
+ throw new ArgumentException(SR.Format(SR.Arg_ResourceNameNotExist, resourceName));
}
-
- lock(this) {
+
+ lock (this)
+ {
// Read all the positions of data within the data section.
- for(int i=0; i<_numResources; i++) {
+ for (int i = 0; i < _numResources; i++)
+ {
_store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i);
// Skip over name of resource
int numBytesToSkip = _store.Read7BitEncodedInt();
- if (numBytesToSkip < 0) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesNameInvalidOffset", numBytesToSkip));
+ if (numBytesToSkip < 0)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, numBytesToSkip));
}
_store.BaseStream.Position += numBytesToSkip;
int dPos = _store.ReadInt32();
- if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset) {
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourcesDataInvalidOffset", dPos));
+ if (dPos < 0 || dPos >= _store.BaseStream.Length - _dataSectionOffset)
+ {
+ throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dPos));
}
sortedDataPositions[i] = dPos;
}
@@ -1005,23 +1098,24 @@ namespace System.Resources {
int index = Array.BinarySearch(sortedDataPositions, dataPos);
Debug.Assert(index >= 0 && index < _numResources, "Couldn't find data position within sorted data positions array!");
long nextData = (index < _numResources - 1) ? sortedDataPositions[index + 1] + _dataSectionOffset : _store.BaseStream.Length;
- int len = (int) (nextData - (dataPos + _dataSectionOffset));
- Debug.Assert(len >= 0 && len <= (int) _store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
+ int len = (int)(nextData - (dataPos + _dataSectionOffset));
+ Debug.Assert(len >= 0 && len <= (int)_store.BaseStream.Length - dataPos + _dataSectionOffset, "Length was negative or outside the bounds of the file!");
// Read type code then byte[]
_store.BaseStream.Position = _dataSectionOffset + dataPos;
- ResourceTypeCode typeCode = (ResourceTypeCode) _store.Read7BitEncodedInt();
- if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length) {
- throw new BadImageFormatException(Environment.GetResourceString("BadImageFormat_InvalidType"));
+ ResourceTypeCode typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt();
+ if (typeCode < 0 || typeCode >= ResourceTypeCode.StartOfUserTypes + _typeTable.Length)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_InvalidType);
}
resourceType = TypeNameFromTypeCode(typeCode);
// The length must be adjusted to subtract off the number
// of bytes in the 7 bit encoded type code.
- len -= (int) (_store.BaseStream.Position - (_dataSectionOffset + dataPos));
+ len -= (int)(_store.BaseStream.Position - (_dataSectionOffset + dataPos));
byte[] bytes = _store.ReadBytes(len);
if (bytes.Length != len)
- throw new FormatException(Environment.GetResourceString("BadImageFormat_ResourceNameCorrupted"));
+ throw new FormatException(SR.BadImageFormat_ResourceNameCorrupted);
resourceData = bytes;
}
}
@@ -1029,19 +1123,23 @@ namespace System.Resources {
private String TypeNameFromTypeCode(ResourceTypeCode typeCode)
{
Contract.Requires(typeCode >= 0, "can't be negative");
- if (typeCode < ResourceTypeCode.StartOfUserTypes) {
+ if (typeCode < ResourceTypeCode.StartOfUserTypes)
+ {
Debug.Assert(!String.Equals(typeCode.ToString(), "LastPrimitive"), "Change ResourceTypeCode metadata order so LastPrimitive isn't what Enum.ToString prefers.");
return "ResourceTypeCode." + typeCode.ToString();
}
- else {
+ else
+ {
int typeIndex = typeCode - ResourceTypeCode.StartOfUserTypes;
Debug.Assert(typeIndex >= 0 && typeIndex < _typeTable.Length, "TypeCode is broken or corrupted!");
long oldPos = _store.BaseStream.Position;
- try {
+ try
+ {
_store.BaseStream.Position = _typeNamePositions[typeIndex];
return _store.ReadString();
}
- finally {
+ finally
+ {
_store.BaseStream.Position = oldPos;
}
}
@@ -1068,7 +1166,8 @@ namespace System.Resources {
public bool MoveNext()
{
- if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE) {
+ if (_currentName == _reader._numResources - 1 || _currentName == ENUM_DONE)
+ {
_currentIsValid = false;
_currentName = ENUM_DONE;
return false;
@@ -1077,49 +1176,61 @@ namespace System.Resources {
_currentName++;
return true;
}
-
- public Object Key {
- get {
- if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
+
+ public Object Key
+ {
+ get
+ {
+ if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded));
+ if (!_currentIsValid) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
+ if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
return _reader.AllocateStringForNameIndex(_currentName, out _dataPosition);
}
}
-
- public Object Current {
- get {
+
+ public Object Current
+ {
+ get
+ {
return Entry;
}
}
// Warning: This requires that you call the Key or Entry property FIRST before calling it!
- internal int DataPosition {
- get {
+ internal int DataPosition
+ {
+ get
+ {
return _dataPosition;
}
}
- public DictionaryEntry Entry {
- get {
- if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
+ public DictionaryEntry Entry
+ {
+ get
+ {
+ if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded));
+ if (!_currentIsValid) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
+ if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
String key;
Object value = null;
- lock (_reader) { // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock
- lock (_reader._resCache) {
+ lock (_reader)
+ { // locks should be taken in the same order as in RuntimeResourceSet.GetObject to avoid deadlock
+ lock (_reader._resCache)
+ {
key = _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); // AllocateStringForNameIndex could lock on _reader
ResourceLocator locator;
- if (_reader._resCache.TryGetValue(key, out locator)) {
+ if (_reader._resCache.TryGetValue(key, out locator))
+ {
value = locator.Value;
}
- if (value == null) {
- if (_dataPosition == -1)
+ if (value == null)
+ {
+ if (_dataPosition == -1)
value = _reader.GetValueForNameIndex(_currentName);
- else
+ else
value = _reader.LoadObject(_dataPosition);
// If enumeration and subsequent lookups happen very
// frequently in the same process, add a ResourceLocator
@@ -1132,12 +1243,14 @@ namespace System.Resources {
return new DictionaryEntry(key, value);
}
}
-
- public Object Value {
- get {
- if (_currentName == ENUM_DONE) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
- if (!_currentIsValid) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
+
+ public Object Value
+ {
+ get
+ {
+ if (_currentName == ENUM_DONE) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded));
+ if (!_currentIsValid) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
+ if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
// Consider using _resCache here, eventually, if
// this proves to be an interesting perf scenario.
@@ -1149,7 +1262,7 @@ namespace System.Resources {
public void Reset()
{
- if (_reader._resCache == null) throw new InvalidOperationException(Environment.GetResourceString("ResourceReaderIsClosed"));
+ if (_reader._resCache == null) throw new InvalidOperationException(SR.ResourceReaderIsClosed);
_currentIsValid = false;
_currentName = ENUM_NOT_STARTED;
}
diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs
index 8fd9346f91..8775f6411a 100644
--- a/src/mscorlib/src/System/Resources/ResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/ResourceSet.cs
@@ -12,7 +12,9 @@
**
**
===========================================================*/
-namespace System.Resources {
+
+namespace System.Resources
+{
using System;
using System.Collections;
using System.IO;
@@ -75,7 +77,7 @@ namespace System.Resources {
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
+
// Creates a ResourceSet using the system default ResourceReader
// implementation. Use this constructor to read from an open stream
// of data.
@@ -119,7 +121,7 @@ namespace System.Resources {
ReadResources();
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
+
private void CommonInit()
{
Table = new Hashtable();
@@ -133,10 +135,11 @@ namespace System.Resources {
{
Dispose(true);
}
-
+
protected virtual void Dispose(bool disposing)
{
- if (disposing) {
+ if (disposing)
+ {
// Close the Reader in a thread-safe way.
IResourceReader copyOfReader = Reader;
Reader = null;
@@ -169,7 +172,7 @@ namespace System.Resources {
{
return typeof(ResourceReader);
}
-
+
// Returns the preferred IResourceWriter class for this kind of ResourceSet.
// Subclasses of ResourceSet using their own Readers &; should override
// GetDefaultReader and GetDefaultWriter.
@@ -183,7 +186,6 @@ namespace System.Resources {
return GetEnumeratorHelper();
}
- /// <internalonly/>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorHelper();
@@ -193,7 +195,7 @@ namespace System.Resources {
{
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
return copyOfTable.GetEnumerator();
}
@@ -202,11 +204,13 @@ namespace System.Resources {
public virtual String GetString(String name)
{
Object obj = GetObjectInternal(name);
- try {
+ try
+ {
return (String)obj;
}
- catch (InvalidCastException) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
+ catch (InvalidCastException)
+ {
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name));
}
}
@@ -217,28 +221,33 @@ namespace System.Resources {
// Case-sensitive lookup
obj = GetObjectInternal(name);
- try {
+ try
+ {
s = (String)obj;
}
- catch (InvalidCastException) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
+ catch (InvalidCastException)
+ {
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name));
}
// case-sensitive lookup succeeded
- if (s != null || !ignoreCase) {
+ if (s != null || !ignoreCase)
+ {
return s;
- }
+ }
// Try doing a case-insensitive lookup
obj = GetCaseInsensitiveObjectInternal(name);
- try {
+ try
+ {
return (String)obj;
}
- catch (InvalidCastException) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ResourceNotString_Name", name));
+ catch (InvalidCastException)
+ {
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name));
}
}
-
+
// Look up an object value for a resource given its name.
//
public virtual Object GetObject(String name)
@@ -249,17 +258,18 @@ namespace System.Resources {
public virtual Object GetObject(String name, bool ignoreCase)
{
Object obj = GetObjectInternal(name);
-
+
if (obj != null || !ignoreCase)
return obj;
return GetCaseInsensitiveObjectInternal(name);
}
-
+
protected virtual void ReadResources()
{
IDictionaryEnumerator en = Reader.GetEnumerator();
- while (en.MoveNext()) {
+ while (en.MoveNext())
+ {
Object value = en.Value;
#if LOOSELY_LINKED_RESOURCE_REFERENCE
if (Assembly != null && value is LooselyLinkedResourceReference) {
@@ -282,7 +292,7 @@ namespace System.Resources {
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
return copyOfTable[name];
}
@@ -292,7 +302,7 @@ namespace System.Resources {
Hashtable copyOfTable = Table; // Avoid a race with Dispose
if (copyOfTable == null)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close
if (caseTable == null)
@@ -300,7 +310,7 @@ namespace System.Resources {
caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase);
#if _DEBUG
//Console.WriteLine("ResourceSet::GetObject loading up case-insensitive data");
- BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing "+name+" correctly in your source");
+ BCLDebug.Perf(false, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + name + " correctly in your source");
#endif
IDictionaryEnumerator en = copyOfTable.GetEnumerator();
diff --git a/src/mscorlib/src/System/Resources/ResourceTypeCode.cs b/src/mscorlib/src/System/Resources/ResourceTypeCode.cs
deleted file mode 100644
index 64fb076eb5..0000000000
--- a/src/mscorlib/src/System/Resources/ResourceTypeCode.cs
+++ /dev/null
@@ -1,57 +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: Marker for types in .resources files
-**
-**
-===========================================================*/
-
-namespace System.Resources {
- /* An internal implementation detail for .resources files, describing
- what type an object is.
- Ranges:
- 0 - 0x1F Primitives and reserved values
- 0x20 - 0x3F Specially recognized types, like byte[] and Streams
-
- Note this data must be included in any documentation describing the
- internals of .resources files.
- */
- [Serializable]
- internal enum ResourceTypeCode {
- // Primitives
- Null = 0,
- String = 1,
- Boolean = 2,
- Char = 3,
- Byte = 4,
- SByte = 5,
- Int16 = 6,
- UInt16 = 7,
- Int32 = 8,
- UInt32 = 9,
- Int64 = 0xa,
- UInt64 = 0xb,
- Single = 0xc,
- Double = 0xd,
- Decimal = 0xe,
- DateTime = 0xf,
- TimeSpan = 0x10,
-
- // A meta-value - change this if you add new primitives
- LastPrimitive = TimeSpan,
-
- // Types with a special representation, like byte[] and Stream
- ByteArray = 0x20,
- Stream = 0x21,
-
- // User types - serialized using the binary formatter.
- StartOfUserTypes = 0x40
- }
-}
diff --git a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
index a94ac82781..e9c038a498 100644
--- a/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/RuntimeResourceSet.cs
@@ -12,7 +12,9 @@
**
**
===========================================================*/
-namespace System.Resources {
+
+namespace System.Resources
+{
using System;
using System.IO;
using System.Collections;
@@ -162,7 +164,7 @@ namespace System.Resources {
internal sealed class RuntimeResourceSet : ResourceSet, IEnumerable
{
internal const int Version = 2; // File format version number
-
+
// Cache for resources. Key is the resource name, which can be cached
// for arbitrarily long times, since the object is usually a string
// literal that will live for the lifetime of the appdomain. The
@@ -217,11 +219,14 @@ namespace System.Resources {
{
if (Reader == null)
return;
-
- if (disposing) {
- lock(Reader) {
+
+ if (disposing)
+ {
+ lock (Reader)
+ {
_resCache = null;
- if (_defaultReader != null) {
+ if (_defaultReader != null)
+ {
_defaultReader.Close();
_defaultReader = null;
}
@@ -229,8 +234,9 @@ namespace System.Resources {
// Set Reader to null to avoid a race in GetObject.
base.Dispose(disposing);
}
- }
- else {
+ }
+ else
+ {
// Just to make sure we always clear these fields in the future...
_resCache = null;
_caseInsensitiveTable = null;
@@ -253,7 +259,7 @@ namespace System.Resources {
{
IResourceReader copyOfReader = Reader;
if (copyOfReader == null || _resCache == null)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
return copyOfReader.GetEnumerator();
}
@@ -262,13 +268,13 @@ namespace System.Resources {
public override String GetString(String key)
{
Object o = GetObject(key, false, true);
- return (String) o;
+ return (String)o;
}
public override String GetString(String key, bool ignoreCase)
{
Object o = GetObject(key, ignoreCase, true);
- return (String) o;
+ return (String)o;
}
public override Object GetObject(String key)
@@ -283,34 +289,39 @@ namespace System.Resources {
private Object GetObject(String key, bool ignoreCase, bool isString)
{
- if (key==null)
+ if (key == null)
throw new ArgumentNullException(nameof(key));
if (Reader == null || _resCache == null)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
Contract.EndContractBlock();
Object value = null;
ResourceLocator resLocation;
-
- lock(Reader) {
+
+ lock (Reader)
+ {
if (Reader == null)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
-
- if (_defaultReader != null) {
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet);
+
+ if (_defaultReader != null)
+ {
BCLDebug.Log("RESMGRFILEFORMAT", "Going down fast path in RuntimeResourceSet::GetObject");
-
+
// Find the offset within the data section
int dataPos = -1;
- if (_resCache.TryGetValue(key, out resLocation)) {
+ if (_resCache.TryGetValue(key, out resLocation))
+ {
value = resLocation.Value;
dataPos = resLocation.DataPosition;
}
-
- if (dataPos == -1 && value == null) {
+
+ if (dataPos == -1 && value == null)
+ {
dataPos = _defaultReader.FindPosForResource(key);
}
- if (dataPos != -1 && value == null) {
+ if (dataPos != -1 && value == null)
+ {
Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
// Normally calling LoadString or LoadObject requires
// taking a lock. Note that in this case, we took a
@@ -318,28 +329,32 @@ namespace System.Resources {
// sufficient since we never pass this ResourceReader
// to anyone else.
ResourceTypeCode typeCode;
- if (isString) {
+ if (isString)
+ {
value = _defaultReader.LoadString(dataPos);
typeCode = ResourceTypeCode.String;
}
- else {
+ else
+ {
value = _defaultReader.LoadObject(dataPos, out typeCode);
}
resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null);
- lock(_resCache) {
+ lock (_resCache)
+ {
_resCache[key] = resLocation;
}
}
-
- if (value != null || !ignoreCase) {
+
+ if (value != null || !ignoreCase)
+ {
#if LOOSELY_LINKED_RESOURCE_REFERENCE
if (Assembly != null && (value is LooselyLinkedResourceReference)) {
LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
value = assRef.Resolve(Assembly);
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
-
+
return value; // may be null
}
} // if (_defaultReader != null)
@@ -347,20 +362,24 @@ namespace System.Resources {
// At this point, we either don't have our default resource reader
// or we haven't found the particular resource we're looking for
// and may have to search for it in a case-insensitive way.
- if (!_haveReadFromReader) {
+ if (!_haveReadFromReader)
+ {
// If necessary, init our case insensitive hash table.
- if (ignoreCase && _caseInsensitiveTable == null) {
+ if (ignoreCase && _caseInsensitiveTable == null)
+ {
_caseInsensitiveTable = new Dictionary<String, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
}
#if _DEBUG
- BCLDebug.Perf(!ignoreCase, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing "+key+" correctly in your source");
+ BCLDebug.Perf(!ignoreCase, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing " + key + " correctly in your source");
#endif
- if (_defaultReader == null) {
+ if (_defaultReader == null)
+ {
IDictionaryEnumerator en = Reader.GetEnumerator();
- while (en.MoveNext()) {
+ while (en.MoveNext())
+ {
DictionaryEntry entry = en.Entry;
- String readKey = (String) entry.Key;
+ String readKey = (String)entry.Key;
ResourceLocator resLoc = new ResourceLocator(-1, entry.Value);
_resCache.Add(readKey, resLoc);
if (ignoreCase)
@@ -371,12 +390,14 @@ namespace System.Resources {
if (!ignoreCase)
Reader.Close();
}
- else {
+ else
+ {
Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
- while (en.MoveNext()) {
+ while (en.MoveNext())
+ {
// Note: Always ask for the resource key before the data position.
- String currentKey = (String) en.Key;
+ String currentKey = (String)en.Key;
int dataPos = en.DataPosition;
ResourceLocator resLoc = new ResourceLocator(dataPos, null);
_caseInsensitiveTable.Add(currentKey, resLoc);
@@ -387,19 +408,23 @@ namespace System.Resources {
Object obj = null;
bool found = false;
bool keyInWrongCase = false;
- if (_defaultReader != null) {
- if (_resCache.TryGetValue(key, out resLocation)) {
+ if (_defaultReader != null)
+ {
+ if (_resCache.TryGetValue(key, out resLocation))
+ {
found = true;
- obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
+ obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
- if (!found && ignoreCase) {
- if (_caseInsensitiveTable.TryGetValue(key, out resLocation)) {
+ if (!found && ignoreCase)
+ {
+ if (_caseInsensitiveTable.TryGetValue(key, out resLocation))
+ {
found = true;
keyInWrongCase = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
- }
+ }
return obj;
} // lock(Reader)
}
@@ -412,12 +437,15 @@ namespace System.Resources {
// We need to explicitly resolve loosely linked manifest
// resources, and we need to resolve ResourceLocators with null objects.
Object value = resLocation.Value;
- if (value == null) {
+ if (value == null)
+ {
ResourceTypeCode typeCode;
- lock(Reader) {
+ lock (Reader)
+ {
value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode);
}
- if (!keyInWrongCase && ResourceLocator.CanCache(typeCode)) {
+ if (!keyInWrongCase && ResourceLocator.CanCache(typeCode))
+ {
resLocation.Value = value;
copyOfCache[key] = resLocation;
}
diff --git a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs b/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
deleted file mode 100644
index 86e972efdd..0000000000
--- a/src/mscorlib/src/System/Resources/SatelliteContractVersionAttribute.cs
+++ /dev/null
@@ -1,38 +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: Specifies which version of a satellite assembly
-** the ResourceManager should ask for.
-**
-**
-===========================================================*/
-
-namespace System.Resources {
- using System;
- using System.Diagnostics.Contracts;
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
- public sealed class SatelliteContractVersionAttribute : Attribute
- {
- private String _version;
-
- public SatelliteContractVersionAttribute(String version)
- {
- if (version == null)
- throw new ArgumentNullException(nameof(version));
- Contract.EndContractBlock();
- _version = version;
- }
-
- public String Version {
- get { return _version; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs b/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
deleted file mode 100644
index aa4069a366..0000000000
--- a/src/mscorlib/src/System/Resources/UltimateResourceFallbackLocation.cs
+++ /dev/null
@@ -1,28 +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: Tells the ResourceManager where to find the
-** ultimate fallback resources for your assembly.
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System.Resources {
-
-[Serializable]
- public enum UltimateResourceFallbackLocation
- {
- MainAssembly,
- Satellite
- }
-}
diff --git a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs
index e0911fae1d..8bce02abc3 100644
--- a/src/mscorlib/src/System/Resources/__FastResourceComparer.cs
+++ b/src/mscorlib/src/System/Resources/__FastResourceComparer.cs
@@ -13,13 +13,15 @@
**
**
===========================================================*/
-namespace System.Resources {
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Resources
+{
internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer<String>, IEqualityComparer<String>
{
internal static readonly FastResourceComparer Default = new FastResourceComparer();
@@ -27,7 +29,7 @@ namespace System.Resources {
// Implements IHashCodeProvider too, due to Hashtable requirements.
public int GetHashCode(Object key)
{
- String s = (String) key;
+ String s = (String)key;
return FastResourceComparer.HashFunction(s);
}
@@ -45,9 +47,9 @@ namespace System.Resources {
// others can read & write our .resources files. Additionally, we
// have a copy of it in InternalResGen as well.
uint hash = 5381;
- for(int i=0; i<key.Length; i++)
+ for (int i = 0; i < key.Length; i++)
hash = ((hash << 5) + hash) ^ key[i];
- return (int) hash;
+ return (int)hash;
}
// Compares Strings quickly in a case-sensitive way
@@ -74,7 +76,7 @@ namespace System.Resources {
if (a == b) return true;
String sa = (String)a;
String sb = (String)b;
- return String.Equals(sa,sb);
+ return String.Equals(sa, sb);
}
// Input is one string to compare with, and a byte[] containing chars in
@@ -93,10 +95,11 @@ namespace System.Resources {
numChars = bCharLength;
if (bCharLength == 0) // Can't use fixed on a 0-element array.
return (a.Length == 0) ? 0 : -1;
- fixed(byte* pb = bytes) {
-
- byte *pChar = pb;
- while (i < numChars && r == 0) {
+ fixed (byte* pb = bytes)
+ {
+ byte* pChar = pb;
+ while (i < numChars && r == 0)
+ {
// little endian format
int b = pChar[0] | pChar[1] << 8;
r = a[i++] - b;
@@ -126,9 +129,10 @@ namespace System.Resources {
int numChars = byteLen >> 1;
if (numChars > b.Length)
numChars = b.Length;
- while(i < numChars && r == 0) {
+ while (i < numChars && r == 0)
+ {
// Must compare character by character, not byte by byte.
- char aCh = (char) (*a++ | (*a++ << 8));
+ char aCh = (char)(*a++ | (*a++ << 8));
r = aCh - b[i++];
}
if (r != 0) return r;
diff --git a/src/mscorlib/src/System/Resources/__HResults.cs b/src/mscorlib/src/System/Resources/__HResults.cs
index c1546edc63..5817161665 100644
--- a/src/mscorlib/src/System/Resources/__HResults.cs
+++ b/src/mscorlib/src/System/Resources/__HResults.cs
@@ -11,7 +11,8 @@
//
//===========================================================================*/
#if FEATURE_APPX
-namespace System.Resources {
+namespace System.Resources
+{
using System;
// Only static data no need to serialize
internal static class __HResults
diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs
index a24ee679d3..ef3ba29787 100644
--- a/src/mscorlib/src/System/RtType.cs
+++ b/src/mscorlib/src/System/RtType.cs
@@ -19,7 +19,7 @@ using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Runtime;
-using System.Runtime.Serialization;
+using System.Runtime.Serialization;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
@@ -32,7 +32,7 @@ using MdToken = System.Reflection.MetadataToken;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
-namespace System
+namespace System
{
// this is a work around to get the concept of a calli. It's not as fast but it would be interesting to
// see how it compares to the current implementation.
@@ -43,18 +43,18 @@ namespace System
// Keep this in sync with FormatFlags defined in typestring.h
internal enum TypeNameFormatFlags
{
- FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible
- FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names
- FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings)
- FormatAssembly = 0x00000004, // Include assembly display name in type names
- FormatSignature = 0x00000008, // Include signature in method names
- FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names
+ FormatBasic = 0x00000000, // Not a bitmask, simply the tersest flag settings possible
+ FormatNamespace = 0x00000001, // Include namespace and/or enclosing class names in type names
+ FormatFullInst = 0x00000002, // Include namespace and assembly in generic types (regardless of other flag settings)
+ FormatAssembly = 0x00000004, // Include assembly display name in type names
+ FormatSignature = 0x00000008, // Include signature in method names
+ FormatNoVersion = 0x00000010, // Suppress version and culture information in all assembly names
#if _DEBUG
- FormatDebug = 0x00000020, // For debug printing of types only
+ FormatDebug = 0x00000020, // For debug printing of types only
#endif
FormatAngleBrackets = 0x00000040, // Whether generic types are C<T> or C[T]
- FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub}
- FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters
+ FormatStubInfo = 0x00000080, // Include stub info like {unbox-stub}
+ FormatGenericParam = 0x00000100, // Use !name and !!name for generic type and method parameters
// If we want to be able to distinguish between overloads whose parameter types have the same name but come from different assemblies,
// we can add FormatAssembly | FormatNoVersion to FormatSerialization. But we are omitting it because it is not a useful scenario
@@ -73,7 +73,7 @@ namespace System
}
[Serializable]
- internal class RuntimeType :
+ internal class RuntimeType :
System.Reflection.TypeInfo, ISerializable, ICloneable
{
#region Definitions
@@ -89,10 +89,10 @@ namespace System
// Helper to build lists of MemberInfos. Special cased to avoid allocations for lists of one element.
private struct ListBuilder<T> where T : class
{
- T[] _items;
- T _item;
- int _count;
- int _capacity;
+ private T[] _items;
+ private T _item;
+ private int _count;
+ private int _capacity;
public ListBuilder(int capacity)
{
@@ -114,7 +114,7 @@ namespace System
public T[] ToArray()
{
if (_count == 0)
- return EmptyArray<T>.Value;
+ return Array.Empty<T>();
if (_count == 1)
return new T[1] { _item };
@@ -151,7 +151,7 @@ namespace System
{
_item = item;
}
- else
+ else
{
if (_count == 1)
{
@@ -198,9 +198,9 @@ namespace System
public unsafe Filter(byte* pUtf8Name, int cUtf8Name, MemberListType listType)
{
- this.m_name = new Utf8String((void*) pUtf8Name, cUtf8Name);
- this.m_listType = listType;
- this.m_nameHash = 0;
+ m_name = new Utf8String((void*)pUtf8Name, cUtf8Name);
+ m_listType = listType;
+ m_nameHash = 0;
if (RequiresStringComparison())
{
@@ -208,10 +208,10 @@ namespace System
}
}
- public bool Match(Utf8String name)
+ public bool Match(Utf8String name)
{
bool retVal = true;
-
+
if (m_listType == MemberListType.CaseSensitive)
retVal = m_name.Equals(name);
else if (m_listType == MemberListType.CaseInsensitive)
@@ -283,16 +283,16 @@ namespace System
BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
switch (cacheType)
{
- case CacheType.Method:
- list = (T[])(object)new RuntimeMethodInfo[1] {
+ case CacheType.Method:
+ list = (T[])(object)new RuntimeMethodInfo[1] {
new RuntimeMethodInfo(method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags, null)
};
- break;
- case CacheType.Constructor:
- list = (T[])(object)new RuntimeConstructorInfo[1] {
- new RuntimeConstructorInfo(method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags)
+ break;
+ case CacheType.Constructor:
+ list = (T[])(object)new RuntimeConstructorInfo[1] {
+ new RuntimeConstructorInfo(method, declaringType, m_runtimeTypeCache, methodAttributes, bindingFlags)
};
- break;
+ break;
}
Insert(ref list, null, MemberListType.HandleToInfo);
@@ -313,7 +313,7 @@ namespace System
BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
- T[] list = (T[])(object)new RuntimeFieldInfo[1] {
+ T[] list = (T[])(object)new RuntimeFieldInfo[1] {
new RtFieldInfo(field, ReflectedType, m_runtimeTypeCache, bindingFlags)
};
@@ -408,8 +408,8 @@ namespace System
bool lockTaken = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
+ try
+ {
Monitor.Enter(this, ref lockTaken);
switch (listType)
@@ -453,7 +453,7 @@ namespace System
int memberCount = m_allMembers.Length;
while (memberCount > 0)
{
- if (m_allMembers[memberCount-1] != null)
+ if (m_allMembers[memberCount - 1] != null)
break;
memberCount--;
}
@@ -618,7 +618,7 @@ namespace System
else
{
#region IsClass or GenericParameter
- while(RuntimeTypeHandle.IsGenericVariable(declaringType))
+ while (RuntimeTypeHandle.IsGenericVariable(declaringType))
declaringType = declaringType.GetBaseType();
bool* overrides = stackalloc bool[RuntimeTypeHandle.GetNumVirtuals(declaringType)];
@@ -730,12 +730,12 @@ namespace System
{
if (ReflectedType.IsGenericParameter)
{
- return EmptyArray<RuntimeConstructorInfo>.Value;
+ return Array.Empty<RuntimeConstructorInfo>();
}
ListBuilder<RuntimeConstructorInfo> list = new ListBuilder<RuntimeConstructorInfo>();
- RuntimeType declaringType= ReflectedType;
+ RuntimeType declaringType = ReflectedType;
foreach (RuntimeMethodHandleInternal methodHandle in RuntimeTypeHandle.GetIntroducedMethods(declaringType))
{
@@ -785,14 +785,14 @@ namespace System
private unsafe RuntimeFieldInfo[] PopulateFields(Filter filter)
{
ListBuilder<RuntimeFieldInfo> list = new ListBuilder<RuntimeFieldInfo>();
-
+
RuntimeType declaringType = ReflectedType;
#region Populate all static, instance and literal fields
- while(RuntimeTypeHandle.IsGenericVariable(declaringType))
+ while (RuntimeTypeHandle.IsGenericVariable(declaringType))
declaringType = declaringType.GetBaseType();
- while(declaringType != null)
+ while (declaringType != null)
{
PopulateRtFields(filter, declaringType, ref list);
@@ -806,13 +806,13 @@ namespace System
if (ReflectedType.IsGenericParameter)
{
Type[] interfaces = ReflectedType.BaseType.GetInterfaces();
-
+
for (int i = 0; i < interfaces.Length; i++)
{
// Populate literal fields defined on any of the interfaces implemented by the declaring type
PopulateLiteralFields(filter, (RuntimeType)interfaces[i], ref list);
PopulateRtFields(filter, (RuntimeType)interfaces[i], ref list);
- }
+ }
}
else
{
@@ -825,7 +825,7 @@ namespace System
// Populate literal fields defined on any of the interfaces implemented by the declaring type
PopulateLiteralFields(filter, (RuntimeType)interfaces[i], ref list);
PopulateRtFields(filter, (RuntimeType)interfaces[i], ref list);
- }
+ }
}
}
#endregion
@@ -837,10 +837,10 @@ namespace System
{
IntPtr* pResult = stackalloc IntPtr[64];
int count = 64;
-
+
if (!RuntimeTypeHandle.GetFields(declaringType, pResult, &count))
{
- fixed(IntPtr* pBigResult = new IntPtr[count])
+ fixed (IntPtr* pBigResult = new IntPtr[count])
{
RuntimeTypeHandle.GetFields(declaringType, pBigResult, &count);
PopulateRtFields(filter, pBigResult, count, declaringType, ref list);
@@ -851,7 +851,7 @@ namespace System
PopulateRtFields(filter, pResult, count, declaringType, ref list);
}
}
-
+
private unsafe void PopulateRtFields(Filter filter,
IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder<RuntimeFieldInfo> list)
{
@@ -861,7 +861,7 @@ namespace System
bool needsStaticFieldForGeneric = RuntimeTypeHandle.HasInstantiation(declaringType) && !RuntimeTypeHandle.ContainsGenericVariables(declaringType);
bool isInherited = declaringType != ReflectedType;
- for(int i = 0; i < count; i ++)
+ for (int i = 0; i < count; i++)
{
RuntimeFieldHandleInternal runtimeFieldHandle = new RuntimeFieldHandleInternal(ppFieldHandles[i]);
@@ -892,13 +892,13 @@ namespace System
bool isPublic = fieldAccess == FieldAttributes.Public;
bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0;
BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
- #endregion
-
+ #endregion
+
// correct the FieldDesc if needed
if (needsStaticFieldForGeneric && isStatic)
runtimeFieldHandle = RuntimeFieldHandle.GetStaticFieldForGenericType(runtimeFieldHandle, declaringType);
- RuntimeFieldInfo runtimeFieldInfo =
+ RuntimeFieldInfo runtimeFieldInfo =
new RtFieldInfo(runtimeFieldHandle, declaringType, m_runtimeTypeCache, bindingFlags);
list.Add(runtimeFieldInfo);
@@ -955,8 +955,8 @@ namespace System
bool isPublic = fieldAccess == FieldAttributes.Public;
bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0;
BindingFlags bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic);
- #endregion
-
+ #endregion
+
RuntimeFieldInfo runtimeFieldInfo =
new MdFieldInfo(tkField, fieldAttributes, declaringType.GetTypeHandleInternal(), m_runtimeTypeCache, bindingFlags);
@@ -983,7 +983,6 @@ namespace System
}
}
}
-
}
private RuntimeType[] PopulateInterfaces(Filter filter)
@@ -1007,20 +1006,20 @@ namespace System
if (!filter.Match(RuntimeTypeHandle.GetUtf8Name(interfaceType)))
continue;
}
-
+
Debug.Assert(interfaceType.IsInterface);
list.Add(interfaceType);
}
}
- if (ReflectedType.IsSzArray)
+ if (ReflectedType.IsSZArray)
{
RuntimeType arrayType = (RuntimeType)ReflectedType.GetElementType();
-
+
if (!arrayType.IsPointer)
{
AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IList<>).MakeGenericType(arrayType), true);
-
+
// To avoid adding a duplicate IEnumerable<T>, we don't add the sub interfaces of IReadOnlyList.
// Instead, we add IReadOnlyCollection<T> separately.
AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IReadOnlyList<>).MakeGenericType(arrayType), false);
@@ -1088,7 +1087,7 @@ namespace System
// For example, TypeDescs do not have metadata tokens
if (MdToken.IsNullToken(tkEnclosingType))
- return EmptyArray<RuntimeType>.Value;
+ return Array.Empty<RuntimeType>();
ListBuilder<RuntimeType> list = new ListBuilder<RuntimeType>();
@@ -1106,7 +1105,7 @@ namespace System
{
nestedType = ModuleHandle.ResolveTypeHandleInternal(moduleHandle, tkNestedClasses[i], null, null);
}
- catch(System.TypeLoadException)
+ catch (System.TypeLoadException)
{
// In a reflection emit scenario, we may have a token for a class which
// has not been baked and hence cannot be loaded.
@@ -1124,7 +1123,7 @@ namespace System
return list.ToArray();
}
-
+
private unsafe RuntimeEventInfo[] PopulateEvents(Filter filter)
{
Contract.Requires(ReflectedType != null);
@@ -1138,11 +1137,11 @@ namespace System
if (!RuntimeTypeHandle.IsInterface(declaringType))
{
- while(RuntimeTypeHandle.IsGenericVariable(declaringType))
+ while (RuntimeTypeHandle.IsGenericVariable(declaringType))
declaringType = declaringType.GetBaseType();
// Populate associates off of the class hierarchy
- while(declaringType != null)
+ while (declaringType != null)
{
PopulateEvents(filter, declaringType, csEventInfos, ref list);
declaringType = RuntimeTypeHandle.GetBaseType(declaringType);
@@ -1231,7 +1230,7 @@ namespace System
if (!RuntimeTypeHandle.IsInterface(declaringType))
{
- while(RuntimeTypeHandle.IsGenericVariable(declaringType))
+ while (RuntimeTypeHandle.IsGenericVariable(declaringType))
declaringType = declaringType.GetBaseType();
// Do not create the dictionary if we are filtering the properties by name already
@@ -1258,8 +1257,8 @@ namespace System
}
private unsafe void PopulateProperties(
- Filter filter,
- RuntimeType declaringType,
+ Filter filter,
+ RuntimeType declaringType,
Dictionary<String, List<RuntimePropertyInfo>> csPropertyInfos,
bool[] usedSlots,
ref ListBuilder<RuntimePropertyInfo> list)
@@ -1408,7 +1407,7 @@ namespace System
{
T[] list = null;
- switch(listType)
+ switch (listType)
{
case MemberListType.CaseSensitive:
list = m_csMemberInfos[name];
@@ -1480,21 +1479,21 @@ namespace System
#region Private Members
private string ConstructName(ref string name, TypeNameFormatFlags formatFlags)
{
- if (name == null)
+ if (name == null)
{
name = new RuntimeTypeHandle(m_runtimeType).ConstructName(formatFlags);
}
return name;
}
- private T[] GetMemberList<T>(ref MemberInfoCache<T> m_cache, MemberListType listType, string name, CacheType cacheType)
+ private T[] GetMemberList<T>(ref MemberInfoCache<T> m_cache, MemberListType listType, string name, CacheType cacheType)
where T : MemberInfo
{
MemberInfoCache<T> existingCache = GetMemberCache<T>(ref m_cache);
return existingCache.GetMemberList(listType, name, cacheType);
}
- private MemberInfoCache<T> GetMemberCache<T>(ref MemberInfoCache<T> m_cache)
+ private MemberInfoCache<T> GetMemberCache<T>(ref MemberInfoCache<T> m_cache)
where T : MemberInfo
{
MemberInfoCache<T> existingCache = m_cache;
@@ -1524,7 +1523,7 @@ namespace System
get { return m_bIsDomainInitialized; }
set { m_bIsDomainInitialized = value; }
}
-
+
internal string GetName(TypeNameKind kind)
{
switch (kind)
@@ -1565,11 +1564,11 @@ namespace System
{
// @Optimization - Use ConstructName to populate m_namespace
if (m_namespace == null)
- {
+ {
Type type = m_runtimeType;
type = type.GetRootElementType();
-
- while (type.IsNested)
+
+ while (type.IsNested)
type = type.DeclaringType;
m_namespace = RuntimeTypeHandle.GetMetadataImport((RuntimeType)type).GetNamespace(type.MetadataToken).ToString();
@@ -1581,11 +1580,11 @@ namespace System
internal TypeCode TypeCode
{
get { return m_typeCode; }
- set { m_typeCode = value; }
+ set { m_typeCode = value; }
}
internal unsafe RuntimeType GetEnclosingType()
- {
+ {
if (m_enclosingType == null)
{
// Use void as a marker of null enclosing type
@@ -1602,9 +1601,9 @@ namespace System
return m_runtimeType;
}
- internal bool IsGlobal
- {
- get { return m_isGlobal; }
+ internal bool IsGlobal
+ {
+ get { return m_isGlobal; }
}
internal void InvalidateCachedNestedType()
@@ -1698,55 +1697,55 @@ namespace System
return rmi;
}
- internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string name)
- {
+ internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string name)
+ {
return GetMemberList<RuntimeMethodInfo>(ref m_methodInfoCache, listType, name, CacheType.Method);
}
internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string name)
- {
+ {
return GetMemberList<RuntimeConstructorInfo>(ref m_constructorInfoCache, listType, name, CacheType.Constructor);
}
internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string name)
- {
+ {
return GetMemberList<RuntimePropertyInfo>(ref m_propertyInfoCache, listType, name, CacheType.Property);
}
internal RuntimeEventInfo[] GetEventList(MemberListType listType, string name)
- {
+ {
return GetMemberList<RuntimeEventInfo>(ref m_eventInfoCache, listType, name, CacheType.Event);
}
internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string name)
- {
+ {
return GetMemberList<RuntimeFieldInfo>(ref m_fieldInfoCache, listType, name, CacheType.Field);
}
internal RuntimeType[] GetInterfaceList(MemberListType listType, string name)
- {
+ {
return GetMemberList<RuntimeType>(ref m_interfaceCache, listType, name, CacheType.Interface);
}
internal RuntimeType[] GetNestedTypeList(MemberListType listType, string name)
- {
+ {
return GetMemberList<RuntimeType>(ref m_nestedClassesCache, listType, name, CacheType.NestedType);
}
- internal MethodBase GetMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method)
- {
+ internal MethodBase GetMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method)
+ {
GetMemberCache<RuntimeMethodInfo>(ref m_methodInfoCache);
return m_methodInfoCache.AddMethod(declaringType, method, CacheType.Method);
}
internal MethodBase GetConstructor(RuntimeType declaringType, RuntimeMethodHandleInternal constructor)
- {
+ {
GetMemberCache<RuntimeConstructorInfo>(ref m_constructorInfoCache);
return m_constructorInfoCache.AddMethod(declaringType, constructor, CacheType.Constructor);
}
internal FieldInfo GetField(RuntimeFieldHandleInternal field)
- {
+ {
GetMemberCache<RuntimeFieldInfo>(ref m_fieldInfoCache);
return m_fieldInfoCache.AddField(field);
}
@@ -1833,7 +1832,7 @@ namespace System
if (!loaderAssuredCompatible)
throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_ResolveMethodHandle"),
+ CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle,
reflectedType.ToString(), declaredType.ToString()));
}
// Action<in string> is assignable from, but not a subclass of Action<in object>.
@@ -1861,7 +1860,7 @@ namespace System
{
// ignoring instantiation is the ReflectedType is not a subtype of the DeclaringType
throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_ResolveMethodHandle"),
+ CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle,
reflectedType.ToString(), declaredType.ToString()));
}
@@ -1883,7 +1882,7 @@ namespace System
{
// declaredType is not Array, not generic, and not assignable from reflectedType
throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_ResolveMethodHandle"),
+ CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle,
reflectedType.ToString(), declaredType.ToString()));
}
}
@@ -1938,7 +1937,7 @@ namespace System
RuntimeFieldHandleInternal fieldHandle = field.Value;
// verify the type/method relationship
- if (reflectedType == null)
+ if (reflectedType == null)
{
reflectedType = RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle);
}
@@ -1951,7 +1950,7 @@ namespace System
!RuntimeTypeHandle.CompareCanonicalHandles(declaredType, reflectedType))
{
throw new ArgumentException(String.Format(
- CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_ResolveFieldHandle"),
+ CultureInfo.CurrentCulture, SR.Argument_ResolveFieldHandle,
reflectedType.ToString(),
declaredType.ToString()));
}
@@ -1967,7 +1966,7 @@ namespace System
private unsafe static PropertyInfo GetPropertyInfo(RuntimeType reflectedType, int tkProperty)
{
RuntimePropertyInfo property = null;
- RuntimePropertyInfo[] candidates =
+ RuntimePropertyInfo[] candidates =
reflectedType.Cache.GetPropertyList(MemberListType.All, null);
for (int i = 0; i < candidates.Length; i++)
@@ -1985,7 +1984,7 @@ namespace System
{
if (type.IsPointer || type.IsByRef || type == typeof(void))
throw new ArgumentException(
- Environment.GetResourceString("Argument_NeverValidGenericArgument", type.ToString()));
+ SR.Format(SR.Argument_NeverValidGenericArgument, type.ToString()));
}
@@ -1995,29 +1994,29 @@ namespace System
throw new ArgumentNullException();
Contract.EndContractBlock();
- for(int i = 0; i < genericArguments.Length; i++)
- {
+ for (int i = 0; i < genericArguments.Length; i++)
+ {
if (genericArguments[i] == null)
throw new ArgumentNullException();
-
+
ThrowIfTypeNeverValidGenericArgument(genericArguments[i]);
}
if (genericArguments.Length != genericParamters.Length)
throw new ArgumentException(
- Environment.GetResourceString("Argument_NotEnoughGenArguments", genericArguments.Length, genericParamters.Length));
+ SR.Format(SR.Argument_NotEnoughGenArguments, genericArguments.Length, genericParamters.Length));
}
-
+
internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e)
{
RuntimeType[] typeContext = null;
RuntimeType[] methodContext = null;
RuntimeType[] genericParamters = null;
-
+
if (definition is Type)
{
RuntimeType genericTypeDefinition = (RuntimeType)definition;
- genericParamters = genericTypeDefinition.GetGenericArgumentsInternal();
+ genericParamters = genericTypeDefinition.GetGenericArgumentsInternal();
typeContext = genericArguments;
}
else
@@ -2025,14 +2024,14 @@ namespace System
RuntimeMethodInfo genericMethodDefinition = (RuntimeMethodInfo)definition;
genericParamters = genericMethodDefinition.GetGenericArgumentsInternal();
methodContext = genericArguments;
-
+
RuntimeType declaringType = (RuntimeType)genericMethodDefinition.DeclaringType;
if (declaringType != null)
{
typeContext = declaringType.GetTypeHandleInternal().GetInstantiationInternal();
}
}
-
+
for (int i = 0; i < genericArguments.Length; i++)
{
Type genericArgument = genericArguments[i];
@@ -2042,8 +2041,7 @@ namespace System
typeContext, methodContext, genericArgument.GetTypeHandleInternal().GetTypeChecked()))
{
throw new ArgumentException(
- Environment.GetResourceString("Argument_GenConstraintViolation",
- i.ToString(CultureInfo.CurrentCulture), genericArgument.ToString(), definition.ToString(), genericParameter.ToString()), e);
+ SR.Format(SR.Argument_GenConstraintViolation, i.ToString(CultureInfo.CurrentCulture), genericArgument.ToString(), definition.ToString(), genericParameter.ToString()), e);
}
}
}
@@ -2058,7 +2056,7 @@ namespace System
// Get namespace
int nsDelimiter = fullname.LastIndexOf(".", StringComparison.Ordinal);
- if (nsDelimiter != -1 )
+ if (nsDelimiter != -1)
{
ns = fullname.Substring(0, nsDelimiter);
int nameLength = fullname.Length - ns.Length - 1;
@@ -2072,7 +2070,6 @@ namespace System
{
name = fullname;
}
-
}
#endregion
@@ -2081,10 +2078,10 @@ namespace System
{
BindingFlags bindingFlags = isPublic ? BindingFlags.Public : BindingFlags.NonPublic;
- if (isInherited)
- {
+ if (isInherited)
+ {
// We arrange things so the DeclaredOnly flag means "include inherited members"
- bindingFlags |= BindingFlags.DeclaredOnly;
+ bindingFlags |= BindingFlags.DeclaredOnly;
if (isStatic)
{
@@ -2112,7 +2109,7 @@ namespace System
// Calculate prefixLookup, ignoreCase, and listType for use by GetXXXCandidates
private static void FilterHelper(
- BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup,
+ BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup,
out bool ignoreCase, out MemberListType listType)
{
prefixLookup = false;
@@ -2169,7 +2166,7 @@ namespace System
{
if (!memberInfo.Name.StartsWith(name, StringComparison.Ordinal))
return false;
- }
+ }
return true;
}
@@ -2206,7 +2203,7 @@ namespace System
#endregion
#region Filter by Static & Instance
- if (memberInfo.MemberType != MemberTypes.TypeInfo &&
+ if (memberInfo.MemberType != MemberTypes.TypeInfo &&
memberInfo.MemberType != MemberTypes.NestedType)
{
if (isStatic)
@@ -2237,8 +2234,8 @@ namespace System
// @Asymmetry - Internal, inherited, instance, non-protected, non-virtual, non-abstract members returned
// iff BindingFlags !DeclaredOnly, Instance and Public are present except for fields
if (((bindingFlags & BindingFlags.DeclaredOnly) == 0) && // DeclaredOnly not present
- isInherited && // Is inherited Member
-
+ isInherited && // Is inherited Member
+
(isNonProtectedInternal) && // Is non-protected internal member
((bindingFlags & BindingFlags.NonPublic) != 0) && // BindingFlag.NonPublic present
@@ -2310,11 +2307,11 @@ namespace System
#region Check CallingConvention
if ((callConv & CallingConventions.Any) == 0)
{
- if ((callConv & CallingConventions.VarArgs) != 0 &&
+ if ((callConv & CallingConventions.VarArgs) != 0 &&
(methodBase.CallingConvention & CallingConventions.VarArgs) == 0)
return false;
- if ((callConv & CallingConventions.Standard) != 0 &&
+ if ((callConv & CallingConventions.Standard) != 0 &&
(methodBase.CallingConvention & CallingConventions.Standard) == 0)
return false;
}
@@ -2330,14 +2327,14 @@ namespace System
#region Invoke Member, Get\Set & Create Instance specific case
// If the number of supplied arguments differs than the number in the signature AND
// we are not filtering for a dynamic call -- InvokeMethod or CreateInstance -- filter out the method.
- if ((bindingFlags &
+ if ((bindingFlags &
(BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0)
return false;
-
+
bool testForParamArray = false;
bool excessSuppliedArguments = argumentTypes.Length > parameterInfos.Length;
- if (excessSuppliedArguments)
+ if (excessSuppliedArguments)
{ // more supplied arguments than parameters, additional arguments could be vararg
#region Varargs
// If method is not vararg, additional arguments can not be passed as vararg
@@ -2345,7 +2342,7 @@ namespace System
{
testForParamArray = true;
}
- else
+ else
{
// If Binding flags did not include varargs we would have filtered this vararg method.
// This Invariant established during callConv check.
@@ -2353,7 +2350,7 @@ namespace System
}
#endregion
}
- else
+ else
{// fewer supplied arguments than parameters, missing arguments could be optional
#region OptionalParamBinding
if ((bindingFlags & BindingFlags.OptionalParamBinding) == 0)
@@ -2375,7 +2372,7 @@ namespace System
#region ParamArray
if (testForParamArray)
{
- if (parameterInfos.Length == 0)
+ if (parameterInfos.Length == 0)
return false;
// The last argument of the signature could be a param array.
@@ -2408,7 +2405,7 @@ namespace System
// in this if statement? That's just InvokeMethod with a constructor, right?
if ((bindingFlags & (BindingFlags.InvokeMethod)) == 0)
{
- for(int i = 0; i < parameterInfos.Length; i ++)
+ 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]))
@@ -2420,7 +2417,7 @@ namespace System
}
}
#endregion
-
+
return true;
}
@@ -2433,65 +2430,6 @@ namespace System
private IntPtr m_cache;
internal IntPtr m_handle;
-#if FEATURE_APPX
- private INVOCATION_FLAGS m_invocationFlags;
-
- internal bool IsNonW8PFrameworkAPI()
- {
- if (IsGenericParameter)
- return false;
-
- if (HasElementType)
- return ((RuntimeType)GetElementType()).IsNonW8PFrameworkAPI();
-
- if (IsSimpleTypeNonW8PFrameworkAPI())
- return true;
-
- if (IsGenericType && !IsGenericTypeDefinition)
- {
- foreach (Type t in GetGenericArguments())
- {
- if (((RuntimeType)t).IsNonW8PFrameworkAPI())
- return true;
- }
- }
-
- return false;
- }
-
- private bool IsSimpleTypeNonW8PFrameworkAPI()
- {
- RuntimeAssembly rtAssembly = GetRuntimeAssembly();
- if (rtAssembly.IsFrameworkAssembly())
- {
- int ctorToken = rtAssembly.InvocableAttributeCtorToken;
- if (System.Reflection.MetadataToken.IsNullToken(ctorToken) ||
- !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken))
- return true;
- }
-
- return false;
- }
-
- internal INVOCATION_FLAGS InvocationFlags
- {
- get
- {
- if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
- {
- INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
-
- if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI())
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API;
-
- m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
- }
-
- return m_invocationFlags;
- }
- }
-#endif // FEATURE_APPX
-
internal static readonly RuntimeType ValueType = (RuntimeType)typeof(System.ValueType);
internal static readonly RuntimeType EnumType = (RuntimeType)typeof(System.Enum);
@@ -2525,16 +2463,16 @@ namespace System
IntPtr gcHandle = Interlocked.CompareExchange(ref m_cache, newgcHandle, (IntPtr)0);
// Leak the handle if the type is collectible. It will be reclaimed when
// the type goes away.
- if (!gcHandle.IsNull() && !IsCollectible())
+ if (!gcHandle.IsNull() && !IsCollectible())
GCHandle.InternalFree(newgcHandle);
}
RuntimeTypeCache cache = GCHandle.InternalGet(m_cache) as RuntimeTypeCache;
- if (cache == null)
+ if (cache == null)
{
cache = new RuntimeTypeCache(this);
RuntimeTypeCache existingCache = GCHandle.InternalCompareExchange(m_cache, cache, null, false) as RuntimeTypeCache;
- if (existingCache != null)
+ if (existingCache != null)
cache = existingCache;
}
@@ -2543,24 +2481,6 @@ namespace System
}
}
- internal bool IsSpecialSerializableType()
- {
- RuntimeType rt = this;
- do
- {
- // In all sane cases we only need to compare the direct level base type with
- // System.Enum and System.MulticastDelegate. However, a generic argument can
- // have a base type constraint that is Delegate or even a real delegate type.
- // Let's maintain compatibility and return true for them.
- if (rt == RuntimeType.DelegateType || rt == RuntimeType.EnumType)
- return true;
-
- rt = rt.GetBaseType();
- } while (rt != null);
-
- return false;
- }
-
private string GetDefaultMemberName()
{
return Cache.GetDefaultMemberName();
@@ -2595,7 +2515,7 @@ namespace System
}
private ListBuilder<ConstructorInfo> GetConstructorCandidates(
- string name, BindingFlags bindingAttr, CallingConventions callConv,
+ string name, BindingFlags bindingAttr, CallingConventions callConv,
Type[] types, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
@@ -2610,7 +2530,7 @@ namespace System
RuntimeConstructorInfo constructorInfo = cache[i];
if (FilterApplyConstructorInfo(constructorInfo, bindingAttr, callConv, types) &&
(!prefixLookup || RuntimeType.FilterApplyPrefixLookup(constructorInfo, name, ignoreCase)))
- {
+ {
candidates.Add(constructorInfo);
}
}
@@ -2621,7 +2541,7 @@ namespace System
private ListBuilder<PropertyInfo> GetPropertyCandidates(
String name, BindingFlags bindingAttr, Type[] types, bool allowPrefixLookup)
- {
+ {
bool prefixLookup, ignoreCase;
MemberListType listType;
RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);
@@ -2683,7 +2603,7 @@ namespace System
for (int i = 0; i < cache.Length; i++)
{
RuntimeFieldInfo fieldInfo = cache[i];
- if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags &&
+ if ((bindingAttr & fieldInfo.BindingFlags) == fieldInfo.BindingFlags &&
(!prefixLookup || FilterApplyPrefixLookup(fieldInfo, name, ignoreCase)))
{
candidates.Add(fieldInfo);
@@ -2699,7 +2619,7 @@ namespace System
bindingAttr &= ~BindingFlags.Static;
string name, ns;
MemberListType listType;
- SplitName(fullname, out name, out ns);
+ SplitName(fullname, out name, out ns);
RuntimeType.FilterHelper(bindingAttr, ref name, allowPrefixLookup, out prefixLookup, out ignoreCase, out listType);
RuntimeType[] cache = Cache.GetNestedTypeList(listType, name);
@@ -2746,12 +2666,12 @@ namespace System
public override Type[] GetInterfaces()
{
- RuntimeType[] candidates = this.Cache.GetInterfaceList(MemberListType.All, null);
- Type[] interfaces = new Type[candidates.Length];
- for (int i = 0; i < candidates.Length; i++)
- JitHelpers.UnsafeSetArrayElement(interfaces, i, candidates[i]);
+ RuntimeType[] candidates = this.Cache.GetInterfaceList(MemberListType.All, null);
+ Type[] interfaces = new Type[candidates.Length];
+ for (int i = 0; i < candidates.Length; i++)
+ JitHelpers.UnsafeSetArrayElement(interfaces, i, candidates[i]);
- return interfaces;
+ return interfaces;
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
@@ -2792,8 +2712,8 @@ namespace System
public override InterfaceMapping GetInterfaceMap(Type ifaceType)
{
if (IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter"));
-
+ throw new InvalidOperationException(SR.Arg_GenericParameter);
+
if ((object)ifaceType == null)
throw new ArgumentNullException(nameof(ifaceType));
Contract.EndContractBlock();
@@ -2801,7 +2721,7 @@ namespace System
RuntimeType ifaceRtType = ifaceType as RuntimeType;
if (ifaceRtType == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(ifaceType));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(ifaceType));
RuntimeTypeHandle ifaceRtTypeHandle = ifaceRtType.GetTypeHandleInternal();
@@ -2811,8 +2731,8 @@ namespace System
// SZArrays implement the methods on IList`1, IEnumerable`1, and ICollection`1 with
// SZArrayHelper and some runtime magic. We don't have accurate interface maps for them.
- if (IsSzArray && ifaceType.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_ArrayGetInterfaceMap"));
+ if (IsSZArray && ifaceType.IsGenericType)
+ throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap);
int ifaceInstanceMethodCount = RuntimeTypeHandle.GetNumVirtuals(ifaceRtType);
@@ -2851,15 +2771,15 @@ namespace System
#region Find XXXInfo
protected override MethodInfo GetMethodImpl(
- String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
- Type[] types, ParameterModifier[] modifiers)
- {
+ String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
+ Type[] types, ParameterModifier[] modifiers)
+ {
ListBuilder<MethodInfo> candidates = GetMethodCandidates(name, bindingAttr, callConv, types, false);
- if (candidates.Count == 0)
+ if (candidates.Count == 0)
return null;
- if (types == null || types.Length == 0)
+ if (types == null || types.Length == 0)
{
MethodInfo firstCandidate = candidates[0];
@@ -2867,44 +2787,44 @@ namespace System
{
return firstCandidate;
}
- else if (types == null)
- {
+ else if (types == null)
+ {
for (int j = 1; j < candidates.Count; j++)
{
MethodInfo methodInfo = candidates[j];
- if (!System.DefaultBinder.CompareMethodSigAndName(methodInfo, firstCandidate))
+ if (!System.DefaultBinder.CompareMethodSig(methodInfo, firstCandidate))
{
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
}
}
// All the methods have the exact same name and sig so return the most derived one.
return System.DefaultBinder.FindMostDerivedNewSlotMeth(candidates.ToArray(), candidates.Count) as MethodInfo;
}
- }
+ }
- if (binder == null)
+ if (binder == null)
binder = DefaultBinder;
- return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo;
+ return binder.SelectMethod(bindingAttr, candidates.ToArray(), types, modifiers) as MethodInfo;
}
protected override ConstructorInfo GetConstructorImpl(
- BindingFlags bindingAttr, Binder binder, CallingConventions callConvention,
- Type[] types, ParameterModifier[] modifiers)
+ BindingFlags bindingAttr, Binder binder, CallingConventions callConvention,
+ Type[] types, ParameterModifier[] modifiers)
{
ListBuilder<ConstructorInfo> candidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, types, false);
if (candidates.Count == 0)
return null;
-
- if (types.Length == 0 && candidates.Count == 1)
+
+ if (types.Length == 0 && candidates.Count == 1)
{
ConstructorInfo firstCandidate = candidates[0];
ParameterInfo[] parameters = firstCandidate.GetParametersNoCopy();
- if (parameters == null || parameters.Length == 0)
+ if (parameters == null || parameters.Length == 0)
{
return firstCandidate;
}
@@ -2921,7 +2841,7 @@ namespace System
protected override PropertyInfo GetPropertyImpl(
- String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
+ String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (name == null) throw new ArgumentNullException();
Contract.EndContractBlock();
@@ -2930,11 +2850,11 @@ namespace System
if (candidates.Count == 0)
return null;
-
- if (types == null || types.Length == 0)
+
+ if (types == null || types.Length == 0)
{
// no arguments
- if (candidates.Count == 1)
+ if (candidates.Count == 1)
{
PropertyInfo firstCandidate = candidates[0];
@@ -2943,25 +2863,25 @@ namespace System
return firstCandidate;
}
- else
+ else
{
if ((object)returnType == null)
// if we are here we have no args or property type to select over and we have more than one property with that name
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
}
}
-
+
if ((bindingAttr & BindingFlags.ExactBinding) != 0)
return System.DefaultBinder.ExactPropertyBinding(candidates.ToArray(), returnType, types, modifiers);
if (binder == null)
binder = DefaultBinder;
-
+
return binder.SelectProperty(bindingAttr, candidates.ToArray(), returnType, types, modifiers);
}
- public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
+ public override EventInfo GetEvent(String name, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
Contract.EndContractBlock();
@@ -2969,7 +2889,7 @@ namespace System
bool ignoreCase;
MemberListType listType;
RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
-
+
RuntimeEventInfo[] cache = Cache.GetEventList(listType, name);
EventInfo match = null;
@@ -2981,7 +2901,7 @@ namespace System
if ((bindingAttr & eventInfo.BindingFlags) == eventInfo.BindingFlags)
{
if (match != null)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
match = eventInfo;
}
@@ -2990,7 +2910,7 @@ namespace System
return match;
}
- public override FieldInfo GetField(String name, BindingFlags bindingAttr)
+ public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
Contract.EndContractBlock();
@@ -3013,30 +2933,30 @@ namespace System
if (match != null)
{
if (Object.ReferenceEquals(fieldInfo.DeclaringType, match.DeclaringType))
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
if ((match.DeclaringType.IsInterface == true) && (fieldInfo.DeclaringType.IsInterface == true))
multipleStaticFieldMatches = true;
}
-
+
if (match == null || fieldInfo.DeclaringType.IsSubclassOf(match.DeclaringType) || match.DeclaringType.IsInterface)
match = fieldInfo;
}
}
if (multipleStaticFieldMatches && match.DeclaringType.IsInterface)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
return match;
}
- public override Type GetInterface(String fullname, bool ignoreCase)
+ public override Type GetInterface(String fullname, bool ignoreCase)
{
if (fullname == null) throw new ArgumentNullException();
Contract.EndContractBlock();
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.NonPublic;
-
+
bindingAttr &= ~BindingFlags.Static;
if (ignoreCase)
@@ -3044,10 +2964,10 @@ namespace System
string name, ns;
MemberListType listType;
- SplitName(fullname, out name, out ns);
+ SplitName(fullname, out name, out ns);
RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
- RuntimeType[] cache = Cache.GetInterfaceList(listType, name);
+ RuntimeType[] cache = Cache.GetInterfaceList(listType, name);
RuntimeType match = null;
@@ -3057,7 +2977,7 @@ namespace System
if (RuntimeType.FilterApplyType(iface, bindingAttr, name, false, ns))
{
if (match != null)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
match = iface;
}
@@ -3066,7 +2986,7 @@ namespace System
return match;
}
- public override Type GetNestedType(String fullname, BindingFlags bindingAttr)
+ public override Type GetNestedType(String fullname, BindingFlags bindingAttr)
{
if (fullname == null) throw new ArgumentNullException();
Contract.EndContractBlock();
@@ -3075,7 +2995,7 @@ namespace System
bindingAttr &= ~BindingFlags.Static;
string name, ns;
MemberListType listType;
- SplitName(fullname, out name, out ns);
+ SplitName(fullname, out name, out ns);
RuntimeType.FilterHelper(bindingAttr, ref name, out ignoreCase, out listType);
RuntimeType[] cache = Cache.GetNestedTypeList(listType, name);
@@ -3088,7 +3008,7 @@ namespace System
if (RuntimeType.FilterApplyType(nestedType, bindingAttr, name, false, ns))
{
if (match != null)
- throw new AmbiguousMatchException(Environment.GetResourceString("Arg_AmbiguousMatchException"));
+ throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException);
match = nestedType;
}
@@ -3097,7 +3017,7 @@ namespace System
return match;
}
- public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
+ public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
if (name == null) throw new ArgumentNullException();
Contract.EndContractBlock();
@@ -3106,7 +3026,7 @@ namespace System
ListBuilder<ConstructorInfo> constructors = new ListBuilder<ConstructorInfo>();
ListBuilder<PropertyInfo> properties = new ListBuilder<PropertyInfo>();
ListBuilder<EventInfo> events = new ListBuilder<EventInfo>();
- ListBuilder<FieldInfo> fields = new ListBuilder<FieldInfo>();
+ ListBuilder<FieldInfo> fields = new ListBuilder<FieldInfo>();
ListBuilder<Type> nestedTypes = new ListBuilder<Type>();
int totalCount = 0;
@@ -3195,9 +3115,9 @@ namespace System
return RuntimeTypeHandle.GetModule(this);
}
- public override Assembly Assembly
+ public override Assembly Assembly
{
- get
+ get
{
return GetRuntimeAssembly();
}
@@ -3208,9 +3128,9 @@ namespace System
return RuntimeTypeHandle.GetAssembly(this);
}
- public override RuntimeTypeHandle TypeHandle
+ public override RuntimeTypeHandle TypeHandle
{
- get
+ get
{
return new RuntimeTypeHandle(this);
}
@@ -3226,7 +3146,7 @@ namespace System
return RuntimeTypeHandle.IsCollectible(GetTypeHandleInternal());
}
- protected override TypeCode GetTypeCodeImpl()
+ protected override TypeCode GetTypeCodeImpl()
{
TypeCode typeCode = Cache.TypeCode;
@@ -3234,7 +3154,7 @@ namespace System
return typeCode;
CorElementType corElementType = RuntimeTypeHandle.GetCorElementType(this);
- switch (corElementType)
+ switch (corElementType)
{
case CorElementType.Boolean:
typeCode = TypeCode.Boolean; break;
@@ -3270,7 +3190,7 @@ namespace System
else if (this.IsEnum)
typeCode = Type.GetTypeCode(Enum.GetUnderlyingType(this));
else
- typeCode = TypeCode.Object;
+ typeCode = TypeCode.Object;
break;
default:
if (this == Convert.ConvertTypes[(int)TypeCode.DBNull])
@@ -3292,7 +3212,7 @@ namespace System
get
{
if (!IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
+ throw new InvalidOperationException(SR.Arg_NotGenericParameter);
Contract.EndContractBlock();
IRuntimeMethodInfo declaringMethod = RuntimeTypeHandle.GetDeclaringMethod(this);
@@ -3312,7 +3232,7 @@ namespace System
}
[Pure]
- public override bool IsSubclassOf(Type type)
+ public override bool IsSubclassOf(Type type)
{
if ((object)type == null)
throw new ArgumentNullException(nameof(type));
@@ -3334,14 +3254,15 @@ namespace System
// pretty much everything is a subclass of object, even interfaces
// notice that interfaces are really odd because they do not have a BaseType
// yet IsSubclassOf(typeof(object)) returns true
- if (rtType == RuntimeType.ObjectType && rtType != this)
+ if (rtType == RuntimeType.ObjectType && rtType != this)
return true;
return false;
}
- public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
- if(typeInfo==null) return false;
+ public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo)
+ {
+ if (typeInfo == null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
@@ -3388,9 +3309,9 @@ namespace System
return false;
}
- public override Type BaseType
+ public override Type BaseType
{
- get
+ get
{
return GetBaseType();
}
@@ -3441,9 +3362,9 @@ namespace System
return RuntimeTypeHandle.GetBaseType(this);
}
- public override Type UnderlyingSystemType
+ public override Type UnderlyingSystemType
{
- get
+ get
{
return this;
}
@@ -3451,34 +3372,34 @@ namespace System
#endregion
#region Name
- public override String FullName
+ public override String FullName
{
- get
+ get
{
return GetCachedName(TypeNameKind.FullName);
}
}
- public override String AssemblyQualifiedName
+ public override String AssemblyQualifiedName
{
- get
+ get
{
string fullname = FullName;
// FullName is null if this type contains generic parameters but is not a generic type definition.
if (fullname == null)
return null;
-
- return Assembly.CreateQualifiedName(this.Assembly.FullName, fullname);
+
+ return Assembly.CreateQualifiedName(this.Assembly.FullName, fullname);
}
}
- public override String Namespace
+ public override String Namespace
{
- get
+ get
{
string ns = Cache.GetNameSpace();
-
+
if (ns == null || ns.Length == 0)
return null;
@@ -3488,45 +3409,45 @@ namespace System
#endregion
#region Attributes
- protected override TypeAttributes GetAttributeFlagsImpl()
+ protected override TypeAttributes GetAttributeFlagsImpl()
{
return RuntimeTypeHandle.GetAttributes(this);
}
- public override Guid GUID
+ public override Guid GUID
{
- get
+ get
{
- Guid result = new Guid ();
+ Guid result = new Guid();
GetGUID(ref result);
return result;
}
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetGUID(ref Guid result);
- protected override bool IsContextfulImpl()
+ protected override bool IsContextfulImpl()
{
return false;
}
- protected override bool IsByRefImpl()
+ protected override bool IsByRefImpl()
{
return RuntimeTypeHandle.IsByRef(this);
}
- protected override bool IsPrimitiveImpl()
+ protected override bool IsPrimitiveImpl()
{
return RuntimeTypeHandle.IsPrimitive(this);
}
- protected override bool IsPointerImpl()
+ protected override bool IsPointerImpl()
{
return RuntimeTypeHandle.IsPointer(this);
}
- protected override bool IsCOMObjectImpl()
+ protected override bool IsCOMObjectImpl()
{
return RuntimeTypeHandle.IsComObject(this, false);
}
@@ -3560,13 +3481,13 @@ namespace System
// We need to return true for generic parameters with the ValueType constraint.
// So we cannot use the faster RuntimeTypeHandle.IsValueType because it returns
// false for all generic parameters.
- if (this == typeof(ValueType) || this == typeof(Enum))
+ if (this == typeof(ValueType) || this == typeof(Enum))
return false;
return IsSubclassOf(typeof(ValueType));
}
- protected override bool HasElementTypeImpl()
+ protected override bool HasElementTypeImpl()
{
return RuntimeTypeHandle.HasElementType(this);
}
@@ -3576,7 +3497,7 @@ namespace System
get
{
if (!IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
+ throw new InvalidOperationException(SR.Arg_NotGenericParameter);
Contract.EndContractBlock();
GenericParameterAttributes attributes;
@@ -3587,9 +3508,9 @@ namespace System
}
}
- public override bool IsSecurityCritical
+ public override bool IsSecurityCritical
{
- get { return new RuntimeTypeHandle(this).IsSecurityCritical(); }
+ get { return new RuntimeTypeHandle(this).IsSecurityCritical(); }
}
public override bool IsSecuritySafeCritical
{
@@ -3602,28 +3523,28 @@ namespace System
#endregion
#region Arrays
- internal override bool IsSzArray
+ public sealed override bool IsSZArray
{
- get
+ get
{
- return RuntimeTypeHandle.IsSzArray(this);
+ return RuntimeTypeHandle.IsSZArray(this);
}
}
- protected override bool IsArrayImpl()
+ protected override bool IsArrayImpl()
{
return RuntimeTypeHandle.IsArray(this);
}
- public override int GetArrayRank()
+ public override int GetArrayRank()
{
if (!IsArrayImpl())
- throw new ArgumentException(Environment.GetResourceString("Argument_HasToBeArrayClass"));
+ throw new ArgumentException(SR.Argument_HasToBeArrayClass);
return RuntimeTypeHandle.GetArrayRank(this);
}
- public override Type GetElementType()
+ public override Type GetElementType()
{
return RuntimeTypeHandle.GetElementType(this);
}
@@ -3633,7 +3554,7 @@ namespace System
public override string[] GetEnumNames()
{
if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
Contract.EndContractBlock();
String[] ret = Enum.InternalGetNames(this);
@@ -3649,7 +3570,7 @@ namespace System
public override Array GetEnumValues()
{
if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
Contract.EndContractBlock();
// Get all of the values
@@ -3670,7 +3591,7 @@ namespace System
public override Type GetEnumUnderlyingType()
{
if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
+ throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
Contract.EndContractBlock();
return Enum.InternalGetUnderlyingType(this);
@@ -3689,7 +3610,7 @@ namespace System
if (valueType.IsEnum)
{
if (!valueType.IsEquivalentTo(this))
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), this.ToString()));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), this.ToString()));
valueType = (RuntimeType)valueType.GetEnumUnderlyingType();
}
@@ -3710,7 +3631,7 @@ namespace System
{
RuntimeType underlyingType = Enum.InternalGetUnderlyingType(this);
if (underlyingType != valueType)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString()));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString()));
ulong[] ulValues = Enum.InternalGetValues(this);
ulong ulValue = Enum.ToUInt64(value);
@@ -3719,7 +3640,7 @@ namespace System
}
else
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
+ throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
@@ -3732,7 +3653,7 @@ namespace System
Type valueType = value.GetType();
if (!(valueType.IsEnum || IsIntegerType(valueType)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), nameof(value));
+ throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
ulong ulValue = Enum.ToUInt64(value);
@@ -3746,12 +3667,12 @@ namespace System
return GetRootElementType().GetTypeHandleInternal().GetInstantiationInternal();
}
- public override Type[] GetGenericArguments()
+ public override Type[] GetGenericArguments()
{
Type[] types = GetRootElementType().GetTypeHandleInternal().GetInstantiationPublic();
if (types == null)
- types = EmptyArray<Type>.Value;
+ types = Array.Empty<Type>();
return types;
}
@@ -3766,12 +3687,12 @@ namespace System
if (!IsGenericTypeDefinition)
throw new InvalidOperationException(
- Environment.GetResourceString("Arg_NotGenericTypeDefinition", this));
+ SR.Format(SR.Arg_NotGenericTypeDefinition, this));
if (GetGenericArguments().Length != instantiation.Length)
- throw new ArgumentException(Environment.GetResourceString("Argument_GenericArgsCount"), nameof(instantiation));
+ throw new ArgumentException(SR.Argument_GenericArgsCount, nameof(instantiation));
- for (int i = 0; i < instantiation.Length; i ++)
+ for (int i = 0; i < instantiation.Length; i++)
{
Type instantiationElem = instantiation[i];
if (instantiationElem == null)
@@ -3796,7 +3717,7 @@ namespace System
SanityCheckGenericArguments(instantiationRuntimeType, genericParameters);
Type ret = null;
- try
+ try
{
ret = new RuntimeTypeHandle(this).Instantiate(instantiationRuntimeType);
}
@@ -3821,20 +3742,20 @@ namespace System
public override int GenericParameterPosition
{
- get
+ get
{
if (!IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
+ throw new InvalidOperationException(SR.Arg_NotGenericParameter);
Contract.EndContractBlock();
-
- return new RuntimeTypeHandle(this).GetGenericVariableIndex();
+
+ return new RuntimeTypeHandle(this).GetGenericVariableIndex();
}
}
- public override Type GetGenericTypeDefinition()
+ public override Type GetGenericTypeDefinition()
{
if (!IsGenericType)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotGenericType"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
Contract.EndContractBlock();
return RuntimeTypeHandle.GetGenericTypeDefinition(this);
@@ -3852,19 +3773,19 @@ namespace System
public override bool ContainsGenericParameters
{
- get { return GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); }
+ get { return GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); }
}
public override Type[] GetGenericParameterConstraints()
{
if (!IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
+ throw new InvalidOperationException(SR.Arg_NotGenericParameter);
Contract.EndContractBlock();
Type[] constraints = new RuntimeTypeHandle(this).GetConstraints();
if (constraints == null)
- constraints = EmptyArray<Type>.Value;
+ constraints = Array.Empty<Type>();
return constraints;
}
@@ -3874,44 +3795,44 @@ namespace System
public override Type MakePointerType() { return new RuntimeTypeHandle(this).MakePointer(); }
public override Type MakeByRefType() { return new RuntimeTypeHandle(this).MakeByRef(); }
public override Type MakeArrayType() { return new RuntimeTypeHandle(this).MakeSZArray(); }
- public override Type MakeArrayType(int rank)
+ public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
- return new RuntimeTypeHandle(this).MakeArray(rank);
+ return new RuntimeTypeHandle(this).MakeArray(rank);
}
public override StructLayoutAttribute StructLayoutAttribute
{
- get
- {
- return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this);
- }
+ get
+ {
+ return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this);
+ }
}
#endregion
#region Invoke Member
- private const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF;
- private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
- private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;
- private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty;
- private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty;
- private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
- private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod;
- private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300;
- private const BindingFlags ClassicBindingMask =
- BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty |
+ private const BindingFlags MemberBindingMask = (BindingFlags)0x000000FF;
+ private const BindingFlags InvocationMask = (BindingFlags)0x0000FF00;
+ private const BindingFlags BinderNonCreateInstance = BindingFlags.InvokeMethod | BinderGetSetField | BinderGetSetProperty;
+ private const BindingFlags BinderGetSetProperty = BindingFlags.GetProperty | BindingFlags.SetProperty;
+ private const BindingFlags BinderSetInvokeProperty = BindingFlags.InvokeMethod | BindingFlags.SetProperty;
+ private const BindingFlags BinderGetSetField = BindingFlags.GetField | BindingFlags.SetField;
+ private const BindingFlags BinderSetInvokeField = BindingFlags.SetField | BindingFlags.InvokeMethod;
+ private const BindingFlags BinderNonFieldGetSet = (BindingFlags)0x00FFF300;
+ private const BindingFlags ClassicBindingMask =
+ BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty |
BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty;
private static RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static private extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- static private extern Object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange);
+ static private extern Object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange);
- internal unsafe Object CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
+ internal unsafe Object CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
{
// this method is used by invocation in reflection to check whether a value can be assigned to type.
if (IsInstanceOfType(value))
@@ -3935,16 +3856,16 @@ namespace System
// if this is a ByRef get the element type and check if it's compatible
bool isByRef = IsByRef;
- if (isByRef)
+ if (isByRef)
{
RuntimeType elementType = RuntimeTypeHandle.GetElementType(this);
- if (elementType.IsInstanceOfType(value) || value == null)
+ if (elementType.IsInstanceOfType(value) || value == null)
{
// need to create an instance of the ByRef if null was provided, but only if primitive, enum or value type
return AllocateValueType(elementType, value, false);
}
}
- else if (value == null)
+ else if (value == null)
return value;
else if (this == s_typedRef)
// everything works for a typedref
@@ -3955,26 +3876,26 @@ namespace System
// - enum treated as underlying type
// - IntPtr and System.Reflection.Pointer to pointer types
bool needsSpecialCast = IsPointer || IsEnum || IsPrimitive;
- if (needsSpecialCast)
+ if (needsSpecialCast)
{
RuntimeType valueType;
Pointer pointer = value as Pointer;
- if (pointer != null)
- valueType = pointer.GetPointerType();
+ if (pointer != null)
+ valueType = (RuntimeType)pointer.GetPointerType();
else
valueType = (RuntimeType)value.GetType();
if (CanValueSpecialCast(valueType, this))
{
- if (pointer != null)
+ if (pointer != null)
return pointer.GetPointerValue();
else
return value;
}
}
-
+
if ((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding)
- throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value.GetType(), this));
+ throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, SR.Arg_ObjObjEx, value.GetType(), this));
return TryChangeType(value, binder, culture, needsSpecialCast);
}
@@ -3982,32 +3903,32 @@ namespace System
// Factored out of CheckValue to reduce code complexity.
private Object TryChangeType(Object value, Binder binder, CultureInfo culture, bool needsSpecialCast)
{
- if (binder != null && binder != Type.DefaultBinder)
+ if (binder != null && binder != Type.DefaultBinder)
{
- value = binder.ChangeType(value, this, culture);
- if (IsInstanceOfType(value))
+ value = binder.ChangeType(value, this, culture);
+ if (IsInstanceOfType(value))
return value;
// if this is a ByRef get the element type and check if it's compatible
- if (IsByRef)
+ if (IsByRef)
{
RuntimeType elementType = RuntimeTypeHandle.GetElementType(this);
- if (elementType.IsInstanceOfType(value) || value == null)
+ if (elementType.IsInstanceOfType(value) || value == null)
return AllocateValueType(elementType, value, false);
}
- else if (value == null)
+ else if (value == null)
return value;
- if (needsSpecialCast)
+ if (needsSpecialCast)
{
RuntimeType valueType;
Pointer pointer = value as Pointer;
- if (pointer != null)
- valueType = pointer.GetPointerType();
+ if (pointer != null)
+ valueType = (RuntimeType)pointer.GetPointerType();
else
valueType = (RuntimeType)value.GetType();
- if (CanValueSpecialCast(valueType, this))
+ if (CanValueSpecialCast(valueType, this))
{
- if (pointer != null)
+ if (pointer != null)
return pointer.GetPointerValue();
else
return value;
@@ -4015,7 +3936,7 @@ namespace System
}
}
- throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_ObjObjEx"), value.GetType(), this));
+ throw new ArgumentException(String.Format(CultureInfo.CurrentUICulture, SR.Arg_ObjObjEx, value.GetType(), this));
}
// GetDefaultMembers
@@ -4032,7 +3953,7 @@ namespace System
}
if (members == null)
- members = EmptyArray<MemberInfo>.Value;
+ members = Array.Empty<MemberInfo>();
return members;
}
@@ -4042,24 +3963,24 @@ namespace System
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object InvokeMember(
- String name, BindingFlags bindingFlags, Binder binder, Object target,
- Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
+ String name, BindingFlags bindingFlags, Binder binder, Object target,
+ Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
{
if (IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_GenericParameter"));
+ throw new InvalidOperationException(SR.Arg_GenericParameter);
Contract.EndContractBlock();
-
+
#region Preconditions
if ((bindingFlags & InvocationMask) == 0)
// "Must specify binding flags describing the invoke operation required."
- throw new ArgumentException(Environment.GetResourceString("Arg_NoAccessSpec"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_NoAccessSpec, nameof(bindingFlags));
// Provide a default binding mask if none is provided
- if ((bindingFlags & MemberBindingMask) == 0)
+ if ((bindingFlags & MemberBindingMask) == 0)
{
bindingFlags |= BindingFlags.Instance | BindingFlags.Public;
- if ((bindingFlags & BindingFlags.CreateInstance) == 0)
+ if ((bindingFlags & BindingFlags.CreateInstance) == 0)
bindingFlags |= BindingFlags.Static;
}
@@ -4070,13 +3991,13 @@ namespace System
{
if (namedParams.Length > providedArgs.Length)
// "Named parameter array can not be bigger than argument array."
- throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), nameof(namedParams));
+ throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
}
else
{
if (namedParams.Length != 0)
// "Named parameter array can not be bigger than argument array."
- throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamTooBig"), nameof(namedParams));
+ throw new ArgumentException(SR.Arg_NamedParamTooBig, nameof(namedParams));
}
}
#endregion
@@ -4087,22 +4008,22 @@ namespace System
{
#region Preconditions
if ((bindingFlags & ClassicBindingMask) == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMAccess"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_COMAccess, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.GetProperty) != 0 && (bindingFlags & ClassicBindingMask & ~(BindingFlags.GetProperty | BindingFlags.InvokeMethod)) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.InvokeMethod) != 0 && (bindingFlags & ClassicBindingMask & ~(BindingFlags.GetProperty | BindingFlags.InvokeMethod)) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.SetProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.SetProperty) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.PutDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutDispProperty) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.PutRefDispProperty) != 0 && (bindingFlags & ClassicBindingMask & ~BindingFlags.PutRefDispProperty) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_COMPropSetPut"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_COMPropSetPut, nameof(bindingFlags));
#endregion
{
@@ -4111,7 +4032,7 @@ namespace System
throw new ArgumentNullException(nameof(name));
bool[] isByRef = modifiers == null ? null : modifiers[0].IsByRefArray;
-
+
// pass LCID_ENGLISH_US if no explicit culture is specified to match the behavior of VB
int lcid = (culture == null ? 0x0409 : culture.LCID);
@@ -4121,28 +4042,28 @@ namespace System
}
#endif // FEATURE_COMINTEROP && FEATURE_USE_LCID
#endregion
-
+
#region Check that any named paramters are not null
if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
// "Named parameter value must not be null."
- throw new ArgumentException(Environment.GetResourceString("Arg_NamedParamNull"),nameof(namedParams));
+ throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
#endregion
int argCnt = (providedArgs != null) ? providedArgs.Length : 0;
-
+
#region Get a Binder
if (binder == null)
binder = DefaultBinder;
bool bDefaultBinder = (binder == DefaultBinder);
#endregion
-
+
#region Delegate to Activator.CreateInstance
- if ((bindingFlags & BindingFlags.CreateInstance) != 0)
+ if ((bindingFlags & BindingFlags.CreateInstance) != 0)
{
if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & BinderNonCreateInstance) != 0)
// "Can not specify both CreateInstance and another access type."
- throw new ArgumentException(Environment.GetResourceString("Arg_CreatInstAccess"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_CreatInstAccess, nameof(bindingFlags));
return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture);
}
@@ -4155,12 +4076,12 @@ namespace System
#region Name
if (name == null)
throw new ArgumentNullException(nameof(name));
-
- if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
+
+ if (name.Length == 0 || name.Equals(@"[DISPID=0]"))
{
name = GetDefaultMemberName();
- if (name == null)
+ if (name == null)
{
// in InvokeMember we always pretend there is a default member if none is provided and we make it ToString
name = "ToString";
@@ -4179,31 +4100,31 @@ namespace System
{
if (IsSetField)
// "Can not specify both Get and Set on a field."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetGet"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_FldSetGet, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.SetProperty) != 0)
// "Can not specify both GetField and SetProperty."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldGetPropSet"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_FldGetPropSet, nameof(bindingFlags));
}
else
{
Debug.Assert(IsSetField);
- if (providedArgs == null)
+ if (providedArgs == null)
throw new ArgumentNullException(nameof(providedArgs));
if ((bindingFlags & BindingFlags.GetProperty) != 0)
// "Can not specify both SetField and GetProperty."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetPropGet"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_FldSetPropGet, nameof(bindingFlags));
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
// "Can not specify Set on a Field and Invoke on a method."
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetInvoke"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_FldSetInvoke, nameof(bindingFlags));
}
#endregion
-
+
#region Lookup Field
- FieldInfo selFld = null;
+ FieldInfo selFld = null;
FieldInfo[] flds = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[];
Debug.Assert(flds != null);
@@ -4217,8 +4138,8 @@ namespace System
selFld = binder.BindToField(bindingFlags, flds, IsGetField ? Empty.Value : providedArgs[0], culture);
}
#endregion
-
- if (selFld != null)
+
+ if (selFld != null)
{
#region Invocation on a field
if (selFld.FieldType.IsArray || Object.ReferenceEquals(selFld.FieldType, typeof(System.Array)))
@@ -4226,53 +4147,53 @@ namespace System
#region Invocation of an array Field
int idxCnt;
- if ((bindingFlags & BindingFlags.GetField) != 0)
+ if ((bindingFlags & BindingFlags.GetField) != 0)
{
- idxCnt = argCnt;
+ idxCnt = argCnt;
}
else
{
idxCnt = argCnt - 1;
}
- if (idxCnt > 0)
+ if (idxCnt > 0)
{
// Verify that all of the index values are ints
int[] idx = new int[idxCnt];
- for (int i=0;i<idxCnt;i++)
+ for (int i = 0; i < idxCnt; i++)
{
- try
+ try
{
idx[i] = ((IConvertible)providedArgs[i]).ToInt32(null);
}
catch (InvalidCastException)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_IndexMustBeInt"));
+ throw new ArgumentException(SR.Arg_IndexMustBeInt);
}
}
-
+
// Set or get the value...
- Array a = (Array) selFld.GetValue(target);
-
+ Array a = (Array)selFld.GetValue(target);
+
// Set or get the value in the array
- if ((bindingFlags & BindingFlags.GetField) != 0)
+ if ((bindingFlags & BindingFlags.GetField) != 0)
{
return a.GetValue(idx);
}
- else
+ else
{
- a.SetValue(providedArgs[idxCnt],idx);
+ a.SetValue(providedArgs[idxCnt], idx);
return null;
- }
+ }
}
#endregion
}
-
+
if (IsGetField)
{
#region Get the field value
if (argCnt != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_FldGetArgErr"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_FldGetArgErr, nameof(bindingFlags));
return selFld.GetValue(target);
#endregion
@@ -4281,9 +4202,9 @@ namespace System
{
#region Set the field Value
if (argCnt != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_FldSetArgErr"),nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_FldSetArgErr, nameof(bindingFlags));
- selFld.SetValue(target,providedArgs[0],bindingFlags,binder,culture);
+ selFld.SetValue(target, providedArgs[0], bindingFlags, binder, culture);
return null;
#endregion
@@ -4291,7 +4212,7 @@ namespace System
#endregion
}
- if ((bindingFlags & BinderNonFieldGetSet) == 0)
+ if ((bindingFlags & BinderNonFieldGetSet) == 0)
throw new MissingFieldException(FullName, name);
}
#endregion
@@ -4324,7 +4245,7 @@ namespace System
bool isGetProperty = (bindingFlags & BindingFlags.GetProperty) != 0;
bool isSetProperty = (bindingFlags & BindingFlags.SetProperty) != 0;
- if (isGetProperty || isSetProperty)
+ if (isGetProperty || isSetProperty)
{
#region Preconditions
if (isGetProperty)
@@ -4332,16 +4253,16 @@ namespace System
Debug.Assert(!IsSetField);
if (isSetProperty)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetGet"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_PropSetGet, nameof(bindingFlags));
}
else
{
Debug.Assert(isSetProperty);
Debug.Assert(!IsGetField);
-
+
if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_PropSetInvoke"), nameof(bindingFlags));
+ throw new ArgumentException(SR.Arg_PropSetInvoke, nameof(bindingFlags));
}
#endregion
}
@@ -4351,20 +4272,20 @@ namespace System
MethodInfo finalist = null;
#region BindingFlags.InvokeMethod
- if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
+ if ((bindingFlags & BindingFlags.InvokeMethod) != 0)
{
#region Lookup Methods
MethodInfo[] semiFinalists = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[];
List<MethodInfo> results = null;
-
- for(int i = 0; i < semiFinalists.Length; i ++)
+
+ for (int i = 0; i < semiFinalists.Length; i++)
{
MethodInfo semiFinalist = semiFinalists[i];
Debug.Assert(semiFinalist != null);
if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
-
+
if (finalist == null)
{
finalist = semiFinalist;
@@ -4380,7 +4301,7 @@ namespace System
results.Add(semiFinalist);
}
}
-
+
if (results != null)
{
Debug.Assert(results.Count > 1);
@@ -4390,17 +4311,17 @@ namespace System
#endregion
}
#endregion
-
+
Debug.Assert(finalists == null || finalist != null);
#region BindingFlags.GetProperty or BindingFlags.SetProperty
- if (finalist == null && isGetProperty || isSetProperty)
+ if (finalist == null && isGetProperty || isSetProperty)
{
#region Lookup Property
- PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
+ PropertyInfo[] semiFinalists = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[];
List<MethodInfo> results = null;
- for(int i = 0; i < semiFinalists.Length; i ++)
+ for (int i = 0; i < semiFinalists.Length; i++)
{
MethodInfo semiFinalist = null;
@@ -4418,7 +4339,7 @@ namespace System
if (!FilterApplyMethodInfo((RuntimeMethodInfo)semiFinalist, bindingFlags, CallingConventions.Any, new Type[argCnt]))
continue;
-
+
if (finalist == null)
{
finalist = semiFinalist;
@@ -4445,12 +4366,12 @@ namespace System
}
#endregion
- if (finalist != null)
+ if (finalist != null)
{
#region Invoke
- if (finalists == null &&
- argCnt == 0 &&
- finalist.GetParametersNoCopy().Length == 0 &&
+ if (finalists == null &&
+ argCnt == 0 &&
+ finalist.GetParametersNoCopy().Length == 0 &&
(bindingFlags & BindingFlags.OptionalParamBinding) == 0)
{
//if (useCache && argCnt == props[0].GetParameters().Length)
@@ -4458,20 +4379,20 @@ namespace System
return finalist.Invoke(target, bindingFlags, binder, providedArgs, culture);
}
-
+
if (finalists == null)
finalists = new MethodInfo[] { finalist };
if (providedArgs == null)
- providedArgs = EmptyArray<Object>.Value;
+ providedArgs = Array.Empty<Object>();
Object state = null;
-
+
MethodBase invokeMethod = null;
try { invokeMethod = binder.BindToMethod(bindingFlags, finalists, ref providedArgs, modifiers, culture, namedParams, out state); }
- catch(MissingMethodException) { }
+ catch (MissingMethodException) { }
if (invokeMethod == null)
throw new MissingMethodException(FullName, name);
@@ -4487,9 +4408,9 @@ namespace System
return result;
#endregion
}
-
+
throw new MissingMethodException(FullName, name);
- }
+ }
#endregion
#endregion
@@ -4502,28 +4423,28 @@ namespace System
return obj == (object)this;
}
- public override int GetHashCode()
+ public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
- public override String ToString()
+ public override String ToString()
{
return GetCachedName(TypeNameKind.ToString);
}
#endregion
#region ICloneable
- public Object Clone()
+ public Object Clone()
{
return this;
}
#endregion
#region ISerializable
- public void GetObjectData(SerializationInfo info, StreamingContext context)
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info==null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
@@ -4545,8 +4466,8 @@ namespace System
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
@@ -4559,8 +4480,8 @@ namespace System
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
- if (attributeRuntimeType == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
+ if (attributeRuntimeType == null)
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
@@ -4572,9 +4493,9 @@ namespace System
#endregion
#region MemberInfo Overrides
- public override String Name
+ public override String Name
{
- get
+ get
{
return GetCachedName(TypeNameKind.Name);
}
@@ -4623,9 +4544,9 @@ namespace System
return Cache.GetName(kind);
}
- public override MemberTypes MemberType
+ public override MemberTypes MemberType
{
- get
+ get
{
if (this.IsPublic || this.IsNotPublic)
return MemberTypes.TypeInfo;
@@ -4634,17 +4555,17 @@ namespace System
}
}
- public override Type DeclaringType
+ public override Type DeclaringType
{
- get
+ get
{
return Cache.GetEnclosingType();
}
}
- public override Type ReflectedType
+ public override Type ReflectedType
{
- get
+ get
{
return DeclaringType;
}
@@ -4652,7 +4573,7 @@ namespace System
public override int MetadataToken
{
- get
+ get
{
return RuntimeTypeHandle.GetToken(this);
}
@@ -4663,31 +4584,31 @@ namespace System
private void CreateInstanceCheckThis()
{
if (this is ReflectionOnlyType)
- throw new ArgumentException(Environment.GetResourceString("Arg_ReflectionOnlyInvoke"));
+ throw new ArgumentException(SR.Arg_ReflectionOnlyInvoke);
if (ContainsGenericParameters)
throw new ArgumentException(
- Environment.GetResourceString("Acc_CreateGenericEx", this));
+ SR.Format(SR.Acc_CreateGenericEx, this));
Contract.EndContractBlock();
Type elementType = this.GetRootElementType();
if (Object.ReferenceEquals(elementType, typeof(ArgIterator)))
- throw new NotSupportedException(Environment.GetResourceString("Acc_CreateArgIterator"));
+ throw new NotSupportedException(SR.Acc_CreateArgIterator);
if (Object.ReferenceEquals(elementType, typeof(void)))
- throw new NotSupportedException(Environment.GetResourceString("Acc_CreateVoid"));
+ throw new NotSupportedException(SR.Acc_CreateVoid);
}
-
+
internal Object CreateInstanceImpl(
BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, ref StackCrawlMark stackMark)
- {
+ {
CreateInstanceCheckThis();
-
+
Object server = null;
if (args == null)
- args = EmptyArray<Object>.Value;
+ args = Array.Empty<Object>();
int argCnt = args.Length;
@@ -4698,9 +4619,9 @@ 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
if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
- && (IsGenericCOMObjectImpl() || IsValueType))
+ && (IsGenericCOMObjectImpl() || IsValueType))
{
- server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0 , false, true, ref stackMark);
+ server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0, false, true, ref stackMark);
}
else
{
@@ -4717,7 +4638,7 @@ namespace System
}
}
- for(int i = 0; i < candidates.Length; i ++)
+ for (int i = 0; i < candidates.Length; i++)
{
if (FilterApplyConstructorInfo((RuntimeConstructorInfo)candidates[i], bindingAttr, CallingConventions.Any, argsType))
matches.Add(candidates[i]);
@@ -4730,7 +4651,7 @@ namespace System
if (cons == null)
{
- throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
+ throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName));
}
MethodBase invokeMethod;
@@ -4744,18 +4665,17 @@ namespace System
if (invokeMethod == null)
{
- throw new MissingMethodException(Environment.GetResourceString("MissingConstructor_Name", FullName));
+ throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName));
}
if (invokeMethod.GetParametersNoCopy().Length == 0)
{
if (args.Length != 0)
{
-
- Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
- CallingConventions.VarArgs);
- throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
- Environment.GetResourceString("NotSupported_CallToVarArg")));
+ Debug.Assert((invokeMethod.CallingConvention & CallingConventions.VarArgs) ==
+ CallingConventions.VarArgs);
+ throw new NotSupportedException(String.Format(CultureInfo.CurrentCulture,
+ SR.NotSupported_CallToVarArg));
}
// fast path??
@@ -4773,7 +4693,7 @@ namespace System
}
// the cache entry
- class ActivatorCacheEntry
+ private class ActivatorCacheEntry
{
// the type to cache
internal readonly RuntimeType m_type;
@@ -4781,15 +4701,12 @@ namespace System
internal volatile CtorDelegate m_ctor;
internal readonly RuntimeMethodHandleInternal m_hCtorMethodHandle;
internal readonly MethodAttributes m_ctorAttributes;
- // Is a security check needed before this constructor is invoked?
- internal readonly bool m_bNeedSecurityCheck;
// Lazy initialization was performed
internal volatile bool m_bFullyInitialized;
- internal ActivatorCacheEntry(RuntimeType t, RuntimeMethodHandleInternal rmh, bool bNeedSecurityCheck)
+ internal ActivatorCacheEntry(RuntimeType t, RuntimeMethodHandleInternal rmh)
{
m_type = t;
- m_bNeedSecurityCheck = bNeedSecurityCheck;
m_hCtorMethodHandle = rmh;
if (!m_hCtorMethodHandle.IsNullHandle())
m_ctorAttributes = RuntimeMethodHandle.GetAttributes(m_hCtorMethodHandle);
@@ -4797,16 +4714,17 @@ namespace System
}
//ActivatorCache
- class ActivatorCache
+ private class ActivatorCache
{
- const int CACHE_SIZE = 16;
- volatile int hash_counter; //Counter for wrap around
- readonly ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CACHE_SIZE];
+ private const int CACHE_SIZE = 16;
+ private volatile int hash_counter; //Counter for wrap around
+ private readonly ActivatorCacheEntry[] cache = new ActivatorCacheEntry[CACHE_SIZE];
- volatile ConstructorInfo delegateCtorInfo;
+ private volatile ConstructorInfo delegateCtorInfo;
- private void InitializeDelegateCreator() {
- ConstructorInfo ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] {typeof(Object), typeof(IntPtr)});
+ private void InitializeDelegateCreator()
+ {
+ ConstructorInfo ctorInfo = typeof(CtorDelegate).GetConstructor(new Type[] { typeof(Object), typeof(IntPtr) });
delegateCtorInfo = ctorInfo; // this assignment should be last
}
@@ -4815,7 +4733,7 @@ namespace System
if (!ace.m_type.IsValueType)
{
Debug.Assert(!ace.m_hCtorMethodHandle.IsNullHandle(), "Expected the default ctor method handle for a reference type.");
-
+
if (delegateCtorInfo == null)
InitializeDelegateCreator();
@@ -4829,7 +4747,7 @@ namespace System
internal ActivatorCacheEntry GetEntry(RuntimeType t)
{
int index = hash_counter;
- for(int i = 0; i < CACHE_SIZE; i++)
+ for (int i = 0; i < CACHE_SIZE; i++)
{
ActivatorCacheEntry ace = Volatile.Read(ref cache[index]);
if (ace != null && ace.m_type == t) //check for type match..
@@ -4838,7 +4756,7 @@ namespace System
InitializeCacheEntry(ace);
return ace;
}
- index = (index+1)&(ActivatorCache.CACHE_SIZE-1);
+ index = (index + 1) & (ActivatorCache.CACHE_SIZE - 1);
}
return null;
}
@@ -4846,7 +4764,7 @@ namespace System
internal void SetEntry(ActivatorCacheEntry ace)
{
// fill the the array backwards to hit the most recently filled entries first in GetEntry
- int index = (hash_counter-1)&(ActivatorCache.CACHE_SIZE-1);
+ int index = (hash_counter - 1) & (ActivatorCache.CACHE_SIZE - 1);
hash_counter = index;
Volatile.Write(ref cache[index], ace);
}
@@ -4858,33 +4776,12 @@ namespace System
internal Object CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
{
RuntimeMethodHandleInternal runtime_ctor = default(RuntimeMethodHandleInternal);
- bool bNeedSecurityCheck = true;
bool bCanBeCached = false;
- bool bSecurityCheckOff = false;
if (!skipCheckThis)
CreateInstanceCheckThis();
- if (!fillCache)
- bSecurityCheckOff = true;
-
-#if FEATURE_APPX
- INVOCATION_FLAGS invocationFlags = InvocationFlags;
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0)
- {
- RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark);
- if (caller != null && !caller.IsSafeForReflection())
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", this.FullName));
-
- // Allow it because the caller is framework code, but don't cache the result
- // because we need to do the stack walk every time this type is instantiated.
- bSecurityCheckOff = false;
- bCanBeCached = false;
- }
-#endif
- bSecurityCheckOff = true; // CoreCLR does not use security at all.
-
- Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, bSecurityCheckOff, ref bCanBeCached, ref runtime_ctor, ref bNeedSecurityCheck);
+ Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, ref bCanBeCached, ref runtime_ctor);
if (bCanBeCached && fillCache)
{
@@ -4897,7 +4794,7 @@ namespace System
}
// cache the ctor
- ActivatorCacheEntry ace = new ActivatorCacheEntry(this, runtime_ctor, bNeedSecurityCheck);
+ ActivatorCacheEntry ace = new ActivatorCacheEntry(this, runtime_ctor);
activatorCache.SetEntry(ace);
}
@@ -4911,7 +4808,7 @@ namespace System
internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
{
if (GetType() == typeof(ReflectionOnlyType))
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
ActivatorCache activatorCache = s_ActivatorCache;
if (activatorCache != null)
@@ -4921,16 +4818,16 @@ namespace System
{
if (publicOnly)
{
- if (ace.m_ctor != null &&
+ if (ace.m_ctor != null &&
(ace.m_ctorAttributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public)
{
- throw new MissingMethodException(Environment.GetResourceString("Arg_NoDefCTor"));
+ throw new MissingMethodException(SR.Arg_NoDefCTor);
}
}
-
+
// Allocate empty object
Object instance = RuntimeTypeHandle.Allocate(this);
-
+
// if m_ctor is null, this type doesn't have a default ctor
Debug.Assert(ace.m_ctor != null || this.IsValueType);
@@ -5012,19 +4909,18 @@ namespace System
// first place. However given RuntimeType is not public all its methods are protected and require full trust
// to be accessed
[Serializable]
- internal class ReflectionOnlyType : RuntimeType {
-
- private ReflectionOnlyType() {}
+ internal class ReflectionOnlyType : RuntimeType
+ {
+ private ReflectionOnlyType() { }
// always throw
- public override RuntimeTypeHandle TypeHandle
+ public override RuntimeTypeHandle TypeHandle
{
- get
+ get
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
}
}
-
}
#region Library
@@ -5162,7 +5058,6 @@ namespace System.Reflection
internal void Insert(K key, V value)
{
-
int hashcode = GetHashCodeHelper(key);
if (hashcode < 0)
hashcode = ~hashcode;
@@ -5208,15 +5103,14 @@ namespace System.Reflection
string sKey = key as string;
// For strings we don't want the key to differ across domains as CerHashtable might be shared.
- if(sKey == null)
+ if (sKey == null)
{
- return key.GetHashCode();
-
+ return key.GetHashCode();
}
else
{
return sKey.GetLegacyNonRandomizedHashCode();
- }
+ }
}
private void Rehash(int newSize)
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
deleted file mode 100644
index 34e66beade..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs
+++ /dev/null
@@ -1,30 +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.
-
-//------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
-namespace System.Runtime.CompilerServices
-{
- using System;
-
- [AttributeUsage(AttributeTargets.Field)]
- public sealed class AccessedThroughPropertyAttribute : Attribute
- {
- private readonly string propertyName;
-
- public AccessedThroughPropertyAttribute(string propertyName)
- {
- this.propertyName = propertyName;
- }
-
- public string PropertyName
- {
- get
- {
- return propertyName;
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs
deleted file mode 100644
index 5251122629..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AssemblySettingAttributes.cs
+++ /dev/null
@@ -1,94 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-
-namespace System.Runtime.CompilerServices
-{
-
- using System;
- using System.Runtime.InteropServices;
-
- /*
- NGenHint is not supported in Whidbey
-
- [Serializable]
- public enum NGenHint
- {
- Default = 0x0000, // No preference specified
-
- Eager = 0x0001, // NGen at install time
- Lazy = 0x0002, // NGen after install time
- Never = 0x0003, // Assembly should not be ngened
- }
- */
-
- [Serializable]
- public enum LoadHint
- {
- Default = 0x0000, // No preference specified
-
- Always = 0x0001, // Dependency is always loaded
- Sometimes = 0x0002, // Dependency is sometimes loaded
- //Never = 0x0003, // Dependency is never loaded
- }
-
- [Serializable]
- [AttributeUsage(AttributeTargets.Assembly)]
- public sealed class DefaultDependencyAttribute : Attribute
- {
- private LoadHint loadHint;
-
- public DefaultDependencyAttribute (
- LoadHint loadHintArgument
- )
- {
- loadHint = loadHintArgument;
- }
-
- public LoadHint LoadHint
- {
- get
- {
- return loadHint;
- }
- }
- }
-
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
- public sealed class DependencyAttribute : Attribute
- {
- private String dependentAssembly;
- private LoadHint loadHint;
-
- public DependencyAttribute (
- String dependentAssemblyArgument,
- LoadHint loadHintArgument
- )
- {
- dependentAssembly = dependentAssemblyArgument;
- loadHint = loadHintArgument;
- }
-
- public String DependentAssembly
- {
- get
- {
- return dependentAssembly;
- }
- }
-
- public LoadHint LoadHint
- {
- get
- {
- return loadHint;
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
index afb0c22778..fc7a7f01a3 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
@@ -63,7 +63,7 @@ namespace System.Runtime.CompilerServices
// See comment on AsyncMethodBuilderCore.Start
// AsyncMethodBuilderCore.Start(ref stateMachine);
- if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
+ if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine);
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -72,7 +72,6 @@ namespace System.Runtime.CompilerServices
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher);
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs);
@@ -240,15 +239,8 @@ namespace System.Runtime.CompilerServices
}
}
- // This property lazily instantiates the Task in a non-thread-safe manner.
- private Task Task
- {
- get
- {
- if (m_task == null) m_task = new Task();
- return m_task;
- }
- }
+ /// <summary>Lazily instantiate the Task in a non-thread-safe manner.</summary>
+ private Task Task => m_task ?? (m_task = new Task());
/// <summary>
/// Gets an object that may be used to uniquely identify this builder to the debugger.
@@ -295,7 +287,7 @@ namespace System.Runtime.CompilerServices
// See comment on AsyncMethodBuilderCore.Start
// AsyncMethodBuilderCore.Start(ref stateMachine);
- if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
+ if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine);
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -304,7 +296,6 @@ namespace System.Runtime.CompilerServices
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher);
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs);
@@ -358,7 +349,11 @@ namespace System.Runtime.CompilerServices
/// <summary>Gets the <see cref="System.Threading.Tasks.Task"/> for this builder.</summary>
/// <returns>The <see cref="System.Threading.Tasks.Task"/> representing the builder's asynchronous operation.</returns>
/// <exception cref="System.InvalidOperationException">The builder is not initialized.</exception>
- public Task Task { get { return m_builder.Task; } }
+ public Task Task
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return m_builder.Task; }
+ }
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task"/> in the
@@ -449,7 +444,7 @@ namespace System.Runtime.CompilerServices
// See comment on AsyncMethodBuilderCore.Start
// AsyncMethodBuilderCore.Start(ref stateMachine);
- if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
+ if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine);
Contract.EndContractBlock();
// Run the MoveNext method within a copy-on-write ExecutionContext scope.
@@ -458,7 +453,6 @@ namespace System.Runtime.CompilerServices
Thread currentThread = Thread.CurrentThread;
ExecutionContextSwitcher ecs = default(ExecutionContextSwitcher);
- RuntimeHelpers.PrepareConstrainedRegions();
try
{
ExecutionContext.EstablishCopyOnWriteScope(currentThread, ref ecs);
@@ -502,7 +496,7 @@ namespace System.Runtime.CompilerServices
{
// Force the Task to be initialized prior to the first suspending await so
// that the original stack-based builder has a reference to the right Task.
- var builtTask = this.Task;
+ Task builtTask = this.Task;
// Box the state machine, then tell the boxed instance to call back into its own builder,
// so we can cache the boxed reference. NOTE: The language compiler may choose to use
@@ -542,7 +536,7 @@ namespace System.Runtime.CompilerServices
{
// Force the Task to be initialized prior to the first suspending await so
// that the original stack-based builder has a reference to the right Task.
- var builtTask = this.Task;
+ Task<TResult> builtTask = this.Task;
// Box the state machine, then tell the boxed instance to call back into its own builder,
// so we can cache the boxed reference. NOTE: The language compiler may choose to use
@@ -563,15 +557,14 @@ namespace System.Runtime.CompilerServices
/// <returns>The <see cref="System.Threading.Tasks.Task{TResult}"/> representing the builder's asynchronous operation.</returns>
public Task<TResult> Task
{
- get
- {
- // Get and return the task. If there isn't one, first create one and store it.
- var task = m_task;
- if (task == null) { m_task = task = new Task<TResult>(); }
- return task;
- }
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get { return m_task ?? InitializeTask(); }
}
+ /// <summary>Initializes the task, which must not yet be initialized.</summary>
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private Task<TResult> InitializeTask() => (m_task = new Task<TResult>());
+
/// <summary>
/// Completes the <see cref="System.Threading.Tasks.Task{TResult}"/> in the
/// <see cref="System.Threading.Tasks.TaskStatus">RanToCompletion</see> state with the specified result.
@@ -582,28 +575,49 @@ namespace System.Runtime.CompilerServices
{
// Get the currently stored task, which will be non-null if get_Task has already been accessed.
// If there isn't one, get a task and store it.
- var task = m_task;
- if (task == null)
+ if (m_task == null)
{
m_task = GetTaskForResult(result);
Debug.Assert(m_task != null, "GetTaskForResult should never return null");
}
- // Slow path: complete the existing task.
else
{
- if (AsyncCausalityTracer.LoggingOn)
- AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, task.Id, AsyncCausalityStatus.Completed);
+ // Slow path: complete the existing task.
+ SetExistingTaskResult(result);
+ }
+ }
- //only log if we have a real task that was previously created
- if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled)
- {
- System.Threading.Tasks.Task.RemoveFromActiveTasks(task.Id);
- }
+ /// <summary>Completes the already initialized task with the specified result.</summary>
+ /// <param name="result">The result to use to complete the task.</param>
+ private void SetExistingTaskResult(TResult result)
+ {
+ Debug.Assert(m_task != null, "Expected non-null task");
- if (!task.TrySetResult(result))
- {
- throw new InvalidOperationException(Environment.GetResourceString("TaskT_TransitionToFinal_AlreadyCompleted"));
- }
+ if (AsyncCausalityTracer.LoggingOn || System.Threading.Tasks.Task.s_asyncDebuggingEnabled)
+ {
+ LogExistingTaskCompletion();
+ }
+
+ if (!m_task.TrySetResult(result))
+ {
+ ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
+ }
+ }
+
+ /// <summary>Handles logging for the successful completion of an operation.</summary>
+ private void LogExistingTaskCompletion()
+ {
+ Debug.Assert(m_task != null);
+
+ if (AsyncCausalityTracer.LoggingOn)
+ {
+ AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, m_task.Id, AsyncCausalityStatus.Completed);
+ }
+
+ // only log if we have a real task that was previously created
+ if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled)
+ {
+ System.Threading.Tasks.Task.RemoveFromActiveTasks(m_task.Id);
}
}
@@ -620,15 +634,14 @@ namespace System.Runtime.CompilerServices
// Get the currently stored task, which will be non-null if get_Task has already been accessed.
// If there isn't one, store the supplied completed task.
- var task = m_task;
- if (task == null)
+ if (m_task == null)
{
m_task = completedTask;
}
else
{
// Otherwise, complete the task that's there.
- SetResult(default(TResult));
+ SetExistingTaskResult(default(TResult));
}
}
@@ -667,7 +680,7 @@ namespace System.Runtime.CompilerServices
if (!successfullySet)
{
- throw new InvalidOperationException(Environment.GetResourceString("TaskT_TransitionToFinal_AlreadyCompleted"));
+ ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
@@ -704,6 +717,7 @@ namespace System.Runtime.CompilerServices
/// </summary>
/// <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)
{
Contract.Ensures(
@@ -846,9 +860,9 @@ namespace System.Runtime.CompilerServices
/// <exception cref="System.InvalidOperationException">The builder is incorrectly initialized.</exception>
public void SetStateMachine(IAsyncStateMachine stateMachine)
{
- if (stateMachine == null) throw new ArgumentNullException(nameof(stateMachine));
+ if (stateMachine == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine);
Contract.EndContractBlock();
- if (m_stateMachine != null) throw new InvalidOperationException(Environment.GetResourceString("AsyncMethodBuilder_InstanceNotInitialized"));
+ if (m_stateMachine != null) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized);
m_stateMachine = stateMachine;
}
@@ -1104,12 +1118,12 @@ namespace System.Runtime.CompilerServices
return action;
}
- ///<summary>
- /// Given an action, see if it is a contiunation wrapper and has a Task associated with it. If so return it (null otherwise)
- ///</summary>
+ ///<summary>
+ /// Given an action, see if it is a contiunation wrapper and has a Task associated with it. If so return it (null otherwise)
+ ///</summary>
internal static Task TryGetContinuationTask(Action action)
{
- if (action != null)
+ if (action != null)
{
var asWrapper = action.Target as ContinuationWrapper;
if (asWrapper != null)
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
deleted file mode 100644
index f1fc9ced82..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs
+++ /dev/null
@@ -1,18 +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;
-
-namespace System.Runtime.CompilerServices
-{
- [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
- public sealed class AsyncStateMachineAttribute : StateMachineAttribute
- {
- public AsyncStateMachineAttribute(Type stateMachineType)
- : base(stateMachineType)
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs
deleted file mode 100644
index 4fc70908fb..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs
+++ /dev/null
@@ -1,17 +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;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- public sealed class CallerMemberNameAttribute : Attribute
- {
- public CallerMemberNameAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
deleted file mode 100644
index c3679b610c..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilationRelaxations.cs
+++ /dev/null
@@ -1,50 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-
-namespace System.Runtime.CompilerServices
-{
-
- using System;
-
- /// IMPORTANT: Keep this in sync with corhdr.h
-[Serializable]
-[Flags]
- public enum CompilationRelaxations : int
- {
- NoStringInterning = 0x0008, // Start in 0x0008, we had other non public flags in this enum before,
- // so we'll start here just in case somebody used them. This flag is only
- // valid when set for Assemblies.
- };
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)]
- public class CompilationRelaxationsAttribute : Attribute
- {
- private int m_relaxations; // The relaxations.
-
- public CompilationRelaxationsAttribute (
- int relaxations)
- {
- m_relaxations = relaxations;
- }
-
- public CompilationRelaxationsAttribute (
- CompilationRelaxations relaxations)
- {
- m_relaxations = (int) relaxations;
- }
-
- public int CompilationRelaxations
- {
- get
- {
- return m_relaxations;
- }
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
deleted file mode 100644
index 1778506c7c..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs
+++ /dev/null
@@ -1,16 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices {
-
-[Serializable]
-[AttributeUsage(AttributeTargets.All, Inherited = true)]
- public sealed class CompilerGeneratedAttribute : Attribute
- {
- public CompilerGeneratedAttribute () {}
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
deleted file mode 100644
index 1cd830cfca..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs
+++ /dev/null
@@ -1,26 +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: Attribute used to communicate to the VS7 debugger
-** that a class should be treated as if it has
-** global scope.
-**
-**
-===========================================================*/
-
-
-namespace System.Runtime.CompilerServices
-{
- [Serializable]
- [AttributeUsage(AttributeTargets.Class)]
- public class CompilerGlobalScopeAttribute : Attribute
- {
- public CompilerGlobalScopeAttribute () {}
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs
deleted file mode 100644
index a7b4aca480..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CompilerMarshalOverride.cs
+++ /dev/null
@@ -1,23 +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.
-
-namespace System.Runtime.CompilerServices
-{
- // The CLR data marshaler has some behaviors that are incompatible with
- // C++. Specifically, C++ treats boolean variables as byte size, whereas
- // the marshaller treats them as 4-byte size. Similarly, C++ treats
- // wchar_t variables as 4-byte size, whereas the marshaller treats them
- // as single byte size under certain conditions. In order to work around
- // such issues, the C++ compiler will emit a type that the marshaller will
- // marshal using the correct sizes. In addition, the compiler will place
- // this modopt onto the variables to indicate that the specified type is
- // not the true type. Any compiler that needed to deal with similar
- // marshalling incompatibilities could use this attribute as well.
- //
- // Indicates that the modified instance differs from its true type for
- // correct marshalling.
- public static class CompilerMarshalOverride
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
index 4b2648ba6f..f32cc2b510 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ConditionalWeakTable.cs
@@ -61,6 +61,7 @@
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
@@ -164,7 +165,6 @@ namespace System.Runtime.CompilerServices
{
CreateEntry(key, value);
}
-
}
}
@@ -797,7 +797,7 @@ namespace System.Runtime.CompilerServices
}
return Resize(newSize);
- }
+ }
internal Container Resize(int newSize)
{
@@ -974,7 +974,7 @@ namespace System.Runtime.CompilerServices
{
if (_invalid)
{
- throw new InvalidOperationException(Environment.GetResourceString("CollectionCorrupted"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionCorrupted);
}
}
@@ -1114,7 +1114,7 @@ namespace System.Runtime.CompilerServices
{
IntPtr handle = _handle;
_handle = (IntPtr)0;
- nFree(handle);
+ nFree(handle);
}
}
#endregion
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
index 1a5dcfdc11..8f4c79cd94 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
@@ -8,7 +8,7 @@ using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
[Serializable]
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
public abstract class CustomConstantAttribute : Attribute
{
public abstract Object Value { get; }
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
index 148d916be1..7aca42b627 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
@@ -8,7 +8,7 @@ using System.Diagnostics.Contracts;
namespace System.Runtime.CompilerServices
{
[Serializable]
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
public sealed class DateTimeConstantAttribute : CustomConstantAttribute
{
public DateTimeConstantAttribute(long ticks)
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
index f05191840d..0e2b6f8418 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
@@ -13,7 +13,7 @@ using System.Collections.Generic;
namespace System.Runtime.CompilerServices
{
[Serializable]
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited=false)]
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
public sealed class DecimalConstantAttribute : Attribute
{
[CLSCompliant(false)]
@@ -25,7 +25,7 @@ namespace System.Runtime.CompilerServices
uint low
)
{
- dec = new System.Decimal((int) low, (int)mid, (int)hi, (sign != 0), scale);
+ dec = new System.Decimal((int)low, (int)mid, (int)hi, (sign != 0), scale);
}
public DecimalConstantAttribute(
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs
deleted file mode 100644
index 46dae10fdd..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs
+++ /dev/null
@@ -1,18 +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.
-
-//------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
-
-namespace System.Runtime.CompilerServices
-{
- using System;
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false, Inherited=false)]
- public sealed class DisablePrivateReflectionAttribute : Attribute
- {
- public DisablePrivateReflectionAttribute() {}
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
deleted file mode 100644
index 3fda4624d4..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DiscardableAttribute.cs
+++ /dev/null
@@ -1,18 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.CompilerServices {
-
- using System;
-
- // Custom attribute to indicating a TypeDef is a discardable attribute
- public class DiscardableAttribute : Attribute
- {
- public DiscardableAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs
deleted file mode 100644
index 6ec8fa04f5..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ExtensionAttribute.cs
+++ /dev/null
@@ -1,13 +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;
-
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// Indicates that a method is an extension method, or that a class or assembly contains extension methods.
- /// </summary>
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]
- public sealed class ExtensionAttribute : Attribute { }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
deleted file mode 100644
index 679e304ad1..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs
+++ /dev/null
@@ -1,14 +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.
-
-namespace System.Runtime.CompilerServices
-{
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Field)]
- sealed public class FixedAddressValueTypeAttribute : Attribute
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs
deleted file mode 100644
index a7d01b12c4..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FixedBufferAttribute.cs
+++ /dev/null
@@ -1,43 +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 by a compiler for generating value types
-** in-place within other value types containing a certain
-** number of elements of the given (primitive) type. Somewhat
-** similar to P/Invoke's ByValTStr attribute.
-** Used by C# with this syntax: "fixed int buffer[10];"
-**
-===========================================================*/
-using System;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Field, Inherited=false)]
- public sealed class FixedBufferAttribute : Attribute
- {
- private Type elementType;
- private int length;
-
- public FixedBufferAttribute(Type elementType, int length)
- {
- this.elementType = elementType;
- this.length = length;
- }
-
- public Type ElementType {
- get {
- return elementType;
- }
- }
-
- public int Length {
- get {
- return length;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
deleted file mode 100644
index 4b99a8a5d9..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/FormattableStringFactory.cs
+++ /dev/null
@@ -1,58 +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.
-
-/*============================================================
-**
-** Class: FormattableStringFactory
-**
-**
-** Purpose: implementation of the FormattableStringFactory
-** class.
-**
-===========================================================*/
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// A factory type used by compilers to create instances of the type <see cref="FormattableString"/>.
- /// </summary>
- public static class FormattableStringFactory
- {
- /// <summary>
- /// Create a <see cref="FormattableString"/> from a composite format string and object
- /// array containing zero or more objects to format.
- /// </summary>
- public static FormattableString Create(string format, params object[] arguments)
- {
- if (format == null)
- {
- throw new ArgumentNullException(nameof(format));
- }
-
- if (arguments == null)
- {
- throw new ArgumentNullException(nameof(arguments));
- }
-
- return new ConcreteFormattableString(format, arguments);
- }
-
- private sealed class ConcreteFormattableString : FormattableString
- {
- private readonly string _format;
- private readonly object[] _arguments;
-
- internal ConcreteFormattableString(string format, object[] arguments)
- {
- _format = format;
- _arguments = arguments;
- }
-
- public override string Format { get { return _format; } }
- public override object[] GetArguments() { return _arguments; }
- public override int ArgumentCount { get { return _arguments.Length; } }
- public override object GetArgument(int index) { return _arguments[index]; }
- public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, _format, _arguments); }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/FriendAccessAllowedAttribute.cs
index ee7807a5dd..9d380e1070 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/FriendAccessAllowedAttribute.cs
@@ -2,40 +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.
-//------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
-
namespace System.Runtime.CompilerServices
{
- using System;
-
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
- public sealed class InternalsVisibleToAttribute : Attribute
- {
- private string _assemblyName;
- private bool _allInternalsVisible = true;
-
- public InternalsVisibleToAttribute(string assemblyName)
- {
- this._assemblyName = assemblyName;
- }
-
- public string AssemblyName
- {
- get
- {
- return _assemblyName;
- }
- }
-
- public bool AllInternalsVisible
- {
- get { return _allInternalsVisible; }
- set { _allInternalsVisible = value; }
- }
- }
-
/// <summary>
/// If AllInternalsVisible is not true for a friend assembly, the FriendAccessAllowed attribute
/// indicates which internals are shared with that friend assembly.
@@ -52,7 +20,7 @@ namespace System.Runtime.CompilerServices
AllowMultiple = false,
Inherited = false)]
[FriendAccessAllowed]
- internal sealed class FriendAccessAllowedAttribute : Attribute {
+ internal sealed class FriendAccessAllowedAttribute : Attribute
+ {
}
}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.cs
deleted file mode 100644
index 7fb7ea5395..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IAsyncStateMachine.cs
+++ /dev/null
@@ -1,27 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// Represents state machines generated for asynchronous methods.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// Represents state machines generated for asynchronous methods.
- /// This type is intended for compiler use only.
- /// </summary>
- public interface IAsyncStateMachine
- {
- /// <summary>Moves the state machine to its next state.</summary>
- void MoveNext();
- /// <summary>Configures the state machine with a heap-allocated replica.</summary>
- /// <param name="stateMachine">The heap-allocated replica.</param>
- void SetStateMachine(IAsyncStateMachine stateMachine);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs
index 7ba9434575..e2b76ed973 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/ICastable.cs
@@ -61,22 +61,22 @@ namespace System.Runtime.CompilerServices
// IsInstanceOfInterface.
RuntimeTypeHandle GetImplType(RuntimeTypeHandle interfaceType);
}
-
+
/// <summary>
/// Helpers that allows VM to call into ICastable methods without having to deal with RuntimeTypeHandle.
/// RuntimeTypeHandle is a struct and is always passed in stack in x86, which our VM call helpers don't
/// particularly like.
/// </summary>
- class ICastableHelpers
+ internal class ICastableHelpers
{
internal static bool IsInstanceOfInterface(ICastable castable, RuntimeType type, out Exception castError)
{
return castable.IsInstanceOfInterface(new RuntimeTypeHandle(type), out castError);
- }
-
+ }
+
internal static RuntimeType GetImplType(ICastable castable, RuntimeType interfaceType)
{
- return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType();
- }
+ return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType();
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs b/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs
deleted file mode 100644
index aba0a0691f..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/INotifyCompletion.cs
+++ /dev/null
@@ -1,39 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
-//
-//
-//
-// Interfaces used to represent instances that notify listeners of their completion via continuations.
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-using System;
-using System.Security;
-
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// Represents an operation that will schedule continuations when the operation completes.
- /// </summary>
- public interface INotifyCompletion
- {
- /// <summary>Schedules the continuation action to be invoked when the instance completes.</summary>
- /// <param name="continuation">The action to invoke when the operation completes.</param>
- /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
- void OnCompleted(Action continuation);
- }
-
- /// <summary>
- /// Represents an awaiter used to schedule continuations when an await operation completes.
- /// </summary>
- public interface ICriticalNotifyCompletion : INotifyCompletion
- {
- /// <summary>Schedules the continuation action to be invoked when the instance completes.</summary>
- /// <param name="continuation">The action to invoke when the operation completes.</param>
- /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception>
- /// <remarks>Unlike OnCompleted, UnsafeOnCompleted need not propagate ExecutionContext information.</remarks>
- void UnsafeOnCompleted(Action continuation);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs
deleted file mode 100644
index cafee11f8a..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ITuple.cs
+++ /dev/null
@@ -1,22 +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.
-
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// This interface is required for types that want to be indexed into by dynamic patterns.
- /// </summary>
- public interface ITuple
- {
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int Length { get; }
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object this[int index] { get; }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
deleted file mode 100644
index c32be6f3a2..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IndexerNameAttribute.cs
+++ /dev/null
@@ -1,16 +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.
-
-namespace System.Runtime.CompilerServices
-{
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Property, Inherited = true)]
- public sealed class IndexerNameAttribute: Attribute
- {
- public IndexerNameAttribute(String indexerName)
- {}
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
deleted file mode 100644
index 5287e82b7b..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IsVolatile.cs
+++ /dev/null
@@ -1,12 +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.
-
-namespace System.Runtime.CompilerServices
-{
- public static class IsVolatile
- {
- // no instantiation, please!
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs
deleted file mode 100644
index 4bb9b4eb8f..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs
+++ /dev/null
@@ -1,18 +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;
-
-namespace System.Runtime.CompilerServices
-{
- [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
- public sealed class IteratorStateMachineAttribute : StateMachineAttribute
- {
- public IteratorStateMachineAttribute(Type stateMachineType)
- : base(stateMachineType)
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
index b4991110f8..b24018cf78 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
@@ -2,72 +2,47 @@
// 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 {
-
- using System;
- using System.Reflection;
-
+
+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.
-
- [Serializable]
- [Flags]
- public enum MethodImplOptions
- {
- Unmanaged = System.Reflection.MethodImplAttributes.Unmanaged,
- ForwardRef = System.Reflection.MethodImplAttributes.ForwardRef,
- PreserveSig = System.Reflection.MethodImplAttributes.PreserveSig,
- InternalCall = System.Reflection.MethodImplAttributes.InternalCall,
- Synchronized = System.Reflection.MethodImplAttributes.Synchronized,
- NoInlining = System.Reflection.MethodImplAttributes.NoInlining,
- AggressiveInlining = System.Reflection.MethodImplAttributes.AggressiveInlining,
- NoOptimization = System.Reflection.MethodImplAttributes.NoOptimization,
- // **** If you add something, update internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)! ****
- }
+ // Custom attribute to specify additional method properties.
[Serializable]
- public enum MethodCodeType
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
+ sealed public class MethodImplAttribute : Attribute
{
- IL = System.Reflection.MethodImplAttributes.IL,
- Native = System.Reflection.MethodImplAttributes.Native,
- /// <internalonly/>
- OPTIL = System.Reflection.MethodImplAttributes.OPTIL,
- Runtime = System.Reflection.MethodImplAttributes.Runtime
- }
-
- // Custom attribute to specify additional method properties.
-[Serializable]
-[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
- sealed public class MethodImplAttribute : Attribute
- {
- internal MethodImplOptions _val;
- public MethodCodeType MethodCodeType;
+ internal MethodImplOptions _val;
+ public MethodCodeType MethodCodeType;
internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)
{
- MethodImplOptions all =
- MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig |
+ 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;} }
- }
+ public MethodImplOptions Value { get { return _val; } }
+ }
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
deleted file mode 100644
index d5e64a1177..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs
+++ /dev/null
@@ -1,39 +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.
-
-/*============================================================
-**
-** Attribute: ReferenceAssemblyAttribute
-**
-** Purpose: Identifies an assembly as being a "reference
-** assembly", meaning it contains public surface area but
-** no usable implementation. Reference assemblies
-** should be loadable for introspection, but not execution.
-**
-============================================================*/
-namespace System.Runtime.CompilerServices
-{
- using System;
-
- [Serializable]
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=false)]
- public sealed class ReferenceAssemblyAttribute : Attribute
- {
- private String _description; // Maybe ".NET FX v4.0 SP1, partial trust"?
-
- public ReferenceAssemblyAttribute()
- {
- }
-
- public ReferenceAssemblyAttribute(String description)
- {
- _description = description;
- }
-
- public String Description
- {
- get { return _description; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
deleted file mode 100644
index 40a9b7c568..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs
+++ /dev/null
@@ -1,48 +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: Mark up the program to indicate various legacy or new opt-in behaviors.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.CompilerServices
-{
-
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Assembly, Inherited=false, AllowMultiple=false)]
- public sealed class RuntimeCompatibilityAttribute : Attribute
- {
- // fields
- private bool m_wrapNonExceptionThrows;
-
- // constructors
- public RuntimeCompatibilityAttribute() {
- // legacy behavior is the default, and m_wrapNonExceptionThrows is implicitly
- // false thanks to the CLR's guarantee of zeroed memory.
- }
-
- // properties
-
- // If a non-CLSCompliant exception (i.e. one that doesn't derive from System.Exception) is
- // thrown, should it be wrapped up in a System.Runtime.CompilerServices.RuntimeWrappedException
- // instance when presented to catch handlers?
- public bool WrapNonExceptionThrows {
- get {
- return m_wrapNonExceptionThrows;
- }
- set {
- m_wrapNonExceptionThrows = value;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
index 509e527ecb..0338b18bee 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeHelpers.cs
@@ -9,8 +9,9 @@
// This class defines a set of static methods that provide support for compilers.
//
//
-namespace System.Runtime.CompilerServices {
+namespace System.Runtime.CompilerServices
+{
using System;
using System.Security;
using System.Runtime;
@@ -32,7 +33,7 @@ namespace System.Runtime.CompilerServices {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle);
+ public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle);
// GetObjectValue is intended to allow value classes to be manipulated as 'Object'
// but have aliasing behavior of a value class. The intent is that you would use
@@ -61,7 +62,7 @@ namespace System.Runtime.CompilerServices {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _RunClassConstructor(RuntimeType type);
- public static void RunClassConstructor(RuntimeTypeHandle type)
+ public static void RunClassConstructor(RuntimeTypeHandle type)
{
_RunClassConstructor(type.GetRuntimeType());
}
@@ -77,24 +78,24 @@ namespace System.Runtime.CompilerServices {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module);
- public static void RunModuleConstructor(ModuleHandle module)
+ public static void RunModuleConstructor(ModuleHandle module)
{
- _RunModuleConstructor(module.GetRuntimeModule());
+ _RunModuleConstructor(module.GetRuntimeModule());
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
internal static extern void _CompileMethod(IRuntimeMethodInfo method);
- public static void PrepareMethod(RuntimeMethodHandle method){}
- public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation){}
- public static void PrepareContractedDelegate(Delegate d){}
-
+ public static void PrepareMethod(RuntimeMethodHandle method) { }
+ public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { }
+ public static void PrepareContractedDelegate(Delegate d) { }
+
public static void PrepareDelegate(Delegate d)
{
if (d == null)
{
- throw new ArgumentNullException ("d");
+ throw new ArgumentNullException("d");
}
}
@@ -108,8 +109,9 @@ namespace System.Runtime.CompilerServices {
{
// This offset is baked in by string indexer intrinsic, so there is no harm
// in getting it baked in here as well.
- [System.Runtime.Versioning.NonVersionable]
- get {
+ [System.Runtime.Versioning.NonVersionable]
+ get
+ {
// Number of bytes from the address pointed to by a reference to
// a String to the first 16-bit character in the String. Skip
// over the MethodTable pointer, & String
@@ -167,6 +169,14 @@ namespace System.Runtime.CompilerServices {
{
((CleanupCode)backoutCode)(userData, exceptionThrown);
}
+
+ /// <returns>true if given type is reference type or value type that contains references</returns>
+ static public bool IsReferenceOrContainsReferences<T>()
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementation for how this happens.
+ throw new InvalidOperationException();
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
index e3b2d2ce62..c050000169 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
@@ -11,29 +11,34 @@
**
=============================================================================*/
-namespace System.Runtime.CompilerServices {
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.Remoting;
- using System.Diagnostics.Contracts;
-
+using System;
+using System.Runtime.Serialization;
+using System.Runtime.Remoting;
+using System.Diagnostics.Contracts;
+
+namespace System.Runtime.CompilerServices
+{
[Serializable]
public sealed class RuntimeWrappedException : Exception
{
private RuntimeWrappedException(Object thrownObject)
- : base(Environment.GetResourceString("RuntimeWrappedException")) {
- SetErrorCode(System.__HResults.COR_E_RUNTIMEWRAPPED);
+ : base(SR.RuntimeWrappedException)
+ {
+ HResult = System.__HResults.COR_E_RUNTIMEWRAPPED;
m_wrappedException = thrownObject;
}
-
- public Object WrappedException {
+
+ public Object WrappedException
+ {
get { return m_wrappedException; }
}
private Object m_wrappedException;
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -42,7 +47,8 @@ namespace System.Runtime.CompilerServices {
}
internal RuntimeWrappedException(SerializationInfo info, StreamingContext context)
- : base(info, context) {
+ : base(info, context)
+ {
m_wrappedException = info.GetValue("WrappedException", typeof(Object));
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs
deleted file mode 100644
index 38e5538b44..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/SpecialNameAttribute.cs
+++ /dev/null
@@ -1,27 +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.Runtime.InteropServices;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Method |
- AttributeTargets.Property |
- AttributeTargets.Field |
- AttributeTargets.Event |
- AttributeTargets.Struct)]
-
-
- public sealed class SpecialNameAttribute : Attribute
- {
- public SpecialNameAttribute() { }
- }
-}
-
-
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs
deleted file mode 100644
index 7c84009e1f..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/StateMachineAttribute.cs
+++ /dev/null
@@ -1,20 +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;
-
-namespace System.Runtime.CompilerServices
-{
- [Serializable, AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)]
- public class StateMachineAttribute : Attribute
- {
- public Type StateMachineType { get; private set; }
-
- public StateMachineAttribute(Type stateMachineType)
- {
- this.StateMachineType = stateMachineType;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs
deleted file mode 100644
index eb019eecbf..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs
+++ /dev/null
@@ -1,19 +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.
-
-//------------------------------------------------------------------------------
-//------------------------------------------------------------------------------
-namespace System.Runtime.CompilerServices
-{
- using System;
-
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module)]
- public sealed class SuppressIldasmAttribute : Attribute
- {
- public SuppressIldasmAttribute()
- {
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs
deleted file mode 100644
index 6bb36c4bf5..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/SuppressMergeCheckAttribute.cs
+++ /dev/null
@@ -1,23 +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.Runtime.InteropServices;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Constructor |
- AttributeTargets.Method |
- AttributeTargets.Field |
- AttributeTargets.Event |
- AttributeTargets.Property)]
-
- internal sealed class SuppressMergeCheckAttribute : Attribute
- {
- public SuppressMergeCheckAttribute()
- {}
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
index f01900a5bf..e2fa6caa2d 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TaskAwaiter.cs
@@ -72,7 +72,7 @@ namespace System.Runtime.CompilerServices
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
- public bool IsCompleted
+ public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
@@ -84,7 +84,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void OnCompleted(Action continuation)
{
- OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
+ OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
@@ -94,7 +94,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void UnsafeOnCompleted(Action continuation)
{
- OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
+ OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary>
@@ -240,7 +240,7 @@ namespace System.Runtime.CompilerServices
etwLog.TaskWaitBegin(
(currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id),
(currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0),
- task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous,
+ task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous,
(continuationTask != null ? continuationTask.Id : 0));
}
@@ -303,7 +303,7 @@ namespace System.Runtime.CompilerServices
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
- public bool IsCompleted
+ public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
@@ -315,7 +315,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void OnCompleted(Action continuation)
{
- TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true);
+ TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
@@ -325,7 +325,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void UnsafeOnCompleted(Action continuation)
{
- TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false);
+ TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
@@ -390,7 +390,7 @@ namespace System.Runtime.CompilerServices
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
- public bool IsCompleted
+ public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
@@ -402,7 +402,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void OnCompleted(Action continuation)
{
- TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
+ TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
@@ -412,7 +412,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void UnsafeOnCompleted(Action continuation)
{
- TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
+ TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary>
@@ -475,7 +475,7 @@ namespace System.Runtime.CompilerServices
/// <summary>Gets whether the task being awaited is completed.</summary>
/// <remarks>This property is intended for compiler user rather than use directly in code.</remarks>
/// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception>
- public bool IsCompleted
+ public bool IsCompleted
{
get { return m_task.IsCompleted; }
}
@@ -487,7 +487,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void OnCompleted(Action continuation)
{
- TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true);
+ TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true);
}
/// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary>
@@ -497,7 +497,7 @@ namespace System.Runtime.CompilerServices
/// <remarks>This method is intended for compiler user rather than use directly in code.</remarks>
public void UnsafeOnCompleted(Action continuation)
{
- TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false);
+ TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false);
}
/// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary>
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
deleted file mode 100644
index 65b120e6b4..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs
+++ /dev/null
@@ -1,57 +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.Collections.Generic;
-
-namespace System.Runtime.CompilerServices
-{
- /// <summary>
- /// Indicates that the use of <see cref="System.ValueTuple"/> on a member is meant to be treated as a tuple with element names.
- /// </summary>
- [CLSCompliant(false)]
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Event)]
- public sealed class TupleElementNamesAttribute : Attribute
- {
- private readonly string[] _transformNames;
-
- /// <summary>
- /// Initializes a new instance of the <see
- /// cref="TupleElementNamesAttribute"/> class.
- /// </summary>
- /// <param name="transformNames">
- /// Specifies, in a pre-order depth-first traversal of a type's
- /// construction, which <see cref="System.ValueType"/> occurrences are
- /// meant to carry element names.
- /// </param>
- /// <remarks>
- /// This constructor is meant to be used on types that contain an
- /// instantiation of <see cref="System.ValueType"/> that contains
- /// element names. For instance, if <c>C</c> is a generic type with
- /// two type parameters, then a use of the constructed type <c>C{<see
- /// cref="System.ValueTuple{T1, T2}"/>, <see
- /// cref="System.ValueTuple{T1, T2, T3}"/></c> might be intended to
- /// treat the first type argument as a tuple with element names and the
- /// second as a tuple without element names. In which case, the
- /// appropriate attribute specification should use a
- /// <c>transformNames</c> value of <c>{ "name1", "name2", null, null,
- /// null }</c>.
- /// </remarks>
- public TupleElementNamesAttribute(string[] transformNames)
- {
- if (transformNames == null)
- {
- throw new ArgumentNullException(nameof(transformNames));
- }
-
- _transformNames = transformNames;
- }
-
- /// <summary>
- /// Specifies, in a pre-order depth-first traversal of a type's
- /// construction, which <see cref="System.ValueTuple"/> elements are
- /// meant to carry element names.
- /// </summary>
- public IList<string> TransformNames => _transformNames;
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
index 2de9c1f785..929cbe7608 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/TypeDependencyAttribute.cs
@@ -2,28 +2,26 @@
// 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
-{
- using System;
- using System.Diagnostics.Contracts;
+using System;
+using System.Diagnostics.Contracts;
+namespace System.Runtime.CompilerServices
+{
// We might want to make this inherited someday. But I suspect it shouldn't
// be necessary.
[AttributeUsage(AttributeTargets.Struct | AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
- internal sealed class TypeDependencyAttribute: Attribute
+ internal sealed class TypeDependencyAttribute : Attribute
{
-
private string typeName;
- public TypeDependencyAttribute (string typeName)
+ public TypeDependencyAttribute(string typeName)
{
- if(typeName == null) throw new ArgumentNullException(nameof(typeName));
+ if (typeName == null) throw new ArgumentNullException(nameof(typeName));
Contract.EndContractBlock();
this.typeName = typeName;
}
}
-
}
-
+
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs
deleted file mode 100644
index 671d1f0071..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedFromAttribute.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.
-
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)]
- public sealed class TypeForwardedFromAttribute : Attribute
- {
- string assemblyFullName;
-
- private TypeForwardedFromAttribute()
- {
- // Disallow default constructor
- }
-
-
- public TypeForwardedFromAttribute(string assemblyFullName)
- {
- if (String.IsNullOrEmpty(assemblyFullName))
- {
- throw new ArgumentNullException(nameof(assemblyFullName));
- }
- this.assemblyFullName = assemblyFullName;
- }
-
- public string AssemblyFullName
- {
- get {
- return assemblyFullName;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
deleted file mode 100644
index 147c103047..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs
+++ /dev/null
@@ -1,34 +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
-{
- using System;
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true, Inherited=false)]
- public sealed class TypeForwardedToAttribute : Attribute
- {
- private Type _destination;
-
- public TypeForwardedToAttribute(Type destination)
- {
- _destination = destination;
- }
-
- public Type Destination
- {
- get {
- return _destination;
- }
- }
-
- }
-}
-
-
-
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
index adfa015161..b184cd9fa8 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
@@ -4,6 +4,12 @@
using System.Runtime.Versioning;
+#if BIT64
+using nuint = System.UInt64;
+#else
+using nuint = System.UInt32;
+#endif
+
namespace System.Runtime.CompilerServices
{
//
@@ -37,6 +43,7 @@ namespace System.Runtime.CompilerServices
{
// The body of this function will be replaced by the EE with unsafe code that just returns sizeof !!T
// See getILIntrinsicImplementationForUnsafe for how this happens.
+ typeof(T).ToString(); // Type token used by the actual method body
throw new InvalidOperationException();
}
@@ -61,7 +68,19 @@ namespace System.Runtime.CompilerServices
{
// The body of this function will be replaced by the EE with unsafe code!!!
// See getILIntrinsicImplementationForUnsafe for how this happens.
- typeof(T).ToString(); // Type used by the actual method body
+ 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!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
throw new InvalidOperationException();
}
@@ -89,5 +108,45 @@ namespace System.Runtime.CompilerServices
// See getILIntrinsicImplementationForUnsafe for how this happens.
throw new InvalidOperationException();
}
+
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static T ReadUnaligned<T>(void* source)
+ {
+ // 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();
+ }
+
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static T ReadUnaligned<T>(ref byte source)
+ {
+ // 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();
+ }
+
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void WriteUnaligned<T>(void* destination, T value)
+ {
+ // 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();
+ }
+
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void WriteUnaligned<T>(ref byte destination, T value)
+ {
+ // 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();
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
deleted file mode 100644
index bc210ccb71..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs
+++ /dev/null
@@ -1,14 +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.
-
-namespace System.Runtime.CompilerServices
-{
- using System;
-
-[Serializable]
-[AttributeUsage(AttributeTargets.Struct)]
- sealed public class UnsafeValueTypeAttribute : Attribute
- {
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
index 92d1b4f95b..f1c7772526 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/YieldAwaitable.cs
@@ -144,7 +144,6 @@ namespace System.Runtime.CompilerServices
etwLog.TaskWaitContinuationComplete(continuationId);
});
-
}
/// <summary>WaitCallback that invokes the Action supplied as object state.</summary>
@@ -157,7 +156,7 @@ namespace System.Runtime.CompilerServices
private static void RunAction(object state) { ((Action)state)(); }
/// <summary>Ends the await operation.</summary>
- public void GetResult() {} // Nop. It exists purely because the compiler pattern demands it.
+ public void GetResult() { } // Nop. It exists purely because the compiler pattern demands it.
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
index 080e42f46f..b86835f778 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/jithelpers.cs
@@ -16,8 +16,8 @@ using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
-namespace System.Runtime.CompilerServices {
-
+namespace System.Runtime.CompilerServices
+{
// Wrapper for address of a string variable on stack
internal struct StringHandleOnStack
{
@@ -114,14 +114,14 @@ namespace System.Runtime.CompilerServices {
static internal int UnsafeEnumCast<T>(T val) where T : struct // Actually T must be 4 byte (or less) enum
{
- Debug.Assert(typeof(T).IsEnum
- && (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
- || Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
+ Debug.Assert(typeof(T).IsEnum
+ && (Enum.GetUnderlyingType(typeof(T)) == typeof(int)
+ || Enum.GetUnderlyingType(typeof(T)) == typeof(uint)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(short)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(ushort)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(byte)
|| Enum.GetUnderlyingType(typeof(T)) == typeof(sbyte)),
- "Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!");
+ "Error, T must be an 4 byte (or less) enum JitHelpers.UnsafeEnumCast!");
return UnsafeEnumCastInternal<T>(val);
}
@@ -134,9 +134,9 @@ namespace System.Runtime.CompilerServices {
static internal long UnsafeEnumCastLong<T>(T val) where T : struct // Actually T must be 8 byte enum
{
- Debug.Assert(typeof(T).IsEnum
- && (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
- || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
+ Debug.Assert(typeof(T).IsEnum
+ && (Enum.GetUnderlyingType(typeof(T)) == typeof(long)
+ || Enum.GetUnderlyingType(typeof(T)) == typeof(ulong)),
"Error, T must be an 8 byte enum JitHelpers.UnsafeEnumCastLong!");
return UnsafeEnumCastLongInternal<T>(val);
}
@@ -213,7 +213,7 @@ namespace System.Runtime.CompilerServices {
#if _DEBUG
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern static bool IsAddressInStack(IntPtr ptr);
+ private extern static bool IsAddressInStack(IntPtr ptr);
#endif
static internal bool ByRefLessThan<T>(ref T refA, ref T refB)
@@ -223,14 +223,6 @@ namespace System.Runtime.CompilerServices {
throw new InvalidOperationException();
}
- /// <returns>true if given type is reference type or value type that contains references</returns>
- static internal bool ContainsReferences<T>()
- {
- // The body of this function will be replaced by the EE with unsafe code!!!
- // See getILIntrinsicImplementation for how this happens.
- throw new InvalidOperationException();
- }
-
static internal ref T GetArrayData<T>(T[] array)
{
// The body of this function will be replaced by the EE with unsafe code!!!
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
index f04ddf065a..00067748f2 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
@@ -14,9 +14,10 @@
**
=============================================================================*/
-namespace System.Runtime.ExceptionServices {
- using System;
-
+using System;
+
+namespace System.Runtime.ExceptionServices
+{
// This attribute can be applied to methods to indicate that ProcessCorruptedState
// Exceptions should be delivered to them.
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
index 1b3e25b8b2..d986ea9c24 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionNotification.cs
@@ -1,22 +1,21 @@
-// 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.
/*=============================================================================
**
-** File: ExceptionNotification.cs
**
**
** Purpose: Contains definitions for supporting Exception Notifications.
**
** Created: 10/07/2008
**
-** <owner>gkhanna</owner>
**
=============================================================================*/
-namespace System.Runtime.ExceptionServices {
- using System;
- using System.Runtime.ConstrainedExecution;
-
+using System;
+using System.Runtime.ConstrainedExecution;
+
+namespace System.Runtime.ExceptionServices
+{
// Definition of the argument-type passed to the FirstChanceException event handler
public class FirstChanceExceptionEventArgs : EventArgs
{
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
index e8eb6916b7..8d5ced089f 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
+++ b/src/mscorlib/src/System/Runtime/ExceptionServices/ExceptionServicesCommon.cs
@@ -15,9 +15,10 @@
**
=============================================================================*/
-namespace System.Runtime.ExceptionServices {
- using System;
-
+using System;
+
+namespace System.Runtime.ExceptionServices
+{
// This class defines support for seperating the exception dispatch details
// (like stack trace, watson buckets, etc) from the actual managed exception
// object. This allows us to track error (via the exception object) independent
@@ -34,13 +35,13 @@ namespace System.Runtime.ExceptionServices {
private object m_dynamicMethods;
private UIntPtr m_IPForWatsonBuckets;
private Object m_WatsonBuckets;
-
+
private ExceptionDispatchInfo(Exception exception)
{
// Copy over the details we need to save.
m_Exception = exception;
m_remoteStackTrace = exception.RemoteStackTrace;
-
+
// NOTE: don't be tempted to pass the fields for the out params; the containing object
// might be relocated during the call so the pointers will no longer be valid.
object stackTrace;
@@ -50,14 +51,14 @@ namespace System.Runtime.ExceptionServices {
m_dynamicMethods = dynamicMethods;
m_IPForWatsonBuckets = exception.IPForWatsonBuckets;
- m_WatsonBuckets = exception.WatsonBuckets;
+ m_WatsonBuckets = exception.WatsonBuckets;
}
internal UIntPtr IPForWatsonBuckets
{
get
{
- return m_IPForWatsonBuckets;
+ return m_IPForWatsonBuckets;
}
}
@@ -65,10 +66,10 @@ namespace System.Runtime.ExceptionServices {
{
get
{
- return m_WatsonBuckets;
+ return m_WatsonBuckets;
}
}
-
+
internal object BinaryStackTraceArray
{
get
@@ -100,22 +101,21 @@ namespace System.Runtime.ExceptionServices {
{
if (source == null)
{
- throw new ArgumentNullException(nameof(source), Environment.GetResourceString("ArgumentNull_Obj"));
+ throw new ArgumentNullException(nameof(source), SR.ArgumentNull_Obj);
}
-
+
return new ExceptionDispatchInfo(source);
}
-
+
// Return the exception object represented by this ExceptionDispatchInfo instance
public Exception SourceException
{
-
get
{
- return m_Exception;
+ return m_Exception;
}
}
-
+
// When a framework needs to "Rethrow" an exception on a thread different (but not necessarily so) from
// where it was thrown, it should invoke this method against the ExceptionDispatchInfo (EDI)
// created for the exception in question.
@@ -127,7 +127,11 @@ namespace System.Runtime.ExceptionServices {
{
// Restore the exception dispatch details before throwing the exception.
m_Exception.RestoreExceptionDispatchInfo(this);
- throw m_Exception;
+ throw m_Exception;
}
+
+ // Throws the source exception, maintaining the original bucketing details and augmenting
+ // rather than replacing the original stack trace.
+ public static void Throw(Exception source) => Capture(source).Throw();
}
}
diff --git a/src/mscorlib/src/System/Runtime/GcSettings.cs b/src/mscorlib/src/System/Runtime/GcSettings.cs
index 11143c5ee2..993a24f986 100644
--- a/src/mscorlib/src/System/Runtime/GcSettings.cs
+++ b/src/mscorlib/src/System/Runtime/GcSettings.cs
@@ -3,12 +3,13 @@
// See the LICENSE file in the project root for more information.
-namespace System.Runtime {
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Diagnostics.Contracts;
+namespace System.Runtime
+{
// These settings are the same format as in clr\src\vm\gcpriv.h
// make sure you change that file if you change this file!
@@ -22,34 +23,34 @@ namespace System.Runtime {
[Serializable]
public enum GCLatencyMode
{
- Batch = 0,
+ Batch = 0,
Interactive = 1,
LowLatency = 2,
SustainedLowLatency = 3,
NoGCRegion = 4
}
- public static class GCSettings
+ public static class GCSettings
{
- enum SetLatencyModeStatus
+ private enum SetLatencyModeStatus
{
Succeeded = 0,
NoGCInProgress = 1 // NoGCRegion is in progress, can't change pause mode.
};
-
+
public static GCLatencyMode LatencyMode
{
- get
+ get
{
return (GCLatencyMode)(GC.GetGCLatencyMode());
}
// We don't want to allow this API when hosted.
- set
+ set
{
if ((value < GCLatencyMode.Batch) || (value > GCLatencyMode.SustainedLowLatency))
{
- throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum);
}
Contract.EndContractBlock();
@@ -60,18 +61,18 @@ namespace System.Runtime {
public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode
{
- get
+ get
{
return (GCLargeObjectHeapCompactionMode)(GC.GetLOHCompactionMode());
}
// We don't want to allow this API when hosted.
- set
+ set
{
- if ((value < GCLargeObjectHeapCompactionMode.Default) ||
+ if ((value < GCLargeObjectHeapCompactionMode.Default) ||
(value > GCLargeObjectHeapCompactionMode.CompactOnce))
{
- throw new ArgumentOutOfRangeException(Environment.GetResourceString("ArgumentOutOfRange_Enum"));
+ throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Enum);
}
Contract.EndContractBlock();
@@ -79,11 +80,12 @@ namespace System.Runtime {
}
}
- public static bool IsServerGC
+ public static bool IsServerGC
{
- get {
+ get
+ {
return GC.IsServerGC();
}
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
index fc15f4e1a7..c4beb024b1 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ArrayWithOffset.cs
@@ -2,12 +2,13 @@
// 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 {
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+namespace System.Runtime.InteropServices
+{
[Serializable]
public struct ArrayWithOffset
{
@@ -15,30 +16,30 @@ namespace System.Runtime.InteropServices {
//{
// throw new Exception();
//}
-
+
public ArrayWithOffset(Object array, int offset)
{
- m_array = array;
+ m_array = array;
m_offset = offset;
- m_count = 0;
- m_count = CalculateCount();
+ m_count = 0;
+ m_count = CalculateCount();
}
-
+
public Object GetArray()
{
return m_array;
}
-
+
public int GetOffset()
{
return m_offset;
}
-
+
public override int GetHashCode()
{
return m_count + m_offset;
}
-
+
public override bool Equals(Object obj)
{
if (obj is ArrayWithOffset)
@@ -51,12 +52,12 @@ namespace System.Runtime.InteropServices {
{
return obj.m_array == m_array && obj.m_offset == m_offset && obj.m_count == m_count;
}
-
+
public static bool operator ==(ArrayWithOffset a, ArrayWithOffset b)
{
return a.Equals(b);
}
-
+
public static bool operator !=(ArrayWithOffset a, ArrayWithOffset b)
{
return !(a == b);
@@ -64,10 +65,9 @@ namespace System.Runtime.InteropServices {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern int CalculateCount();
-
+
private Object m_array;
- private int m_offset;
- private int m_count;
+ private int m_offset;
+ private int m_count;
}
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
index b5bde22057..ccba51e840 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
@@ -4,33 +4,14 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices{
- using System;
- using System.Reflection;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
- public sealed class UnmanagedFunctionPointerAttribute : Attribute
- {
- CallingConvention m_callingConvention;
-
- public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention) { m_callingConvention = callingConvention; }
-
- public CallingConvention CallingConvention { get { return m_callingConvention; } }
-
- public CharSet CharSet;
- public bool BestFitMapping;
- public bool ThrowOnUnmappableChar;
-
- // This field is ignored and marshaling behaves as if it was true (for historical reasons).
- public bool SetLastError;
-
- // P/Invoke via delegate always preserves signature, HRESULT swapping is not supported.
- //public bool PreserveSig;
- }
+using System;
+using System.Reflection;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+namespace System.Runtime.InteropServices
+{
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public sealed class TypeIdentifierAttribute : Attribute
{
@@ -118,7 +99,6 @@ namespace System.Runtime.InteropServices{
public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType)
{
_val = classInterfaceType;
-
}
public ClassInterfaceAttribute(short classInterfaceType)
{
@@ -127,17 +107,6 @@ namespace System.Runtime.InteropServices{
public ClassInterfaceType Value { get { return _val; } }
}
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Delegate | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)]
- public sealed class ComVisibleAttribute : Attribute
- {
- internal bool _val;
- public ComVisibleAttribute(bool visibility)
- {
- _val = visibility;
- }
- public bool Value { get { return _val; } }
- }
-
[AttributeUsage(AttributeTargets.Method, Inherited = false)]
public sealed class LCIDConversionAttribute : Attribute
{
@@ -146,7 +115,7 @@ namespace System.Runtime.InteropServices{
{
_val = lcid;
}
- public int Value { get {return _val;} }
+ public int Value { get { return _val; } }
}
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
@@ -157,10 +126,10 @@ namespace System.Runtime.InteropServices{
{
_val = progId;
}
- public String Value { get {return _val;} }
+ public String Value { get { return _val; } }
}
- [AttributeUsage(AttributeTargets.Class, Inherited = true)]
+ [AttributeUsage(AttributeTargets.Class, Inherited = true)]
public sealed class ComSourceInterfacesAttribute : Attribute
{
internal String _val;
@@ -184,137 +153,7 @@ namespace System.Runtime.InteropServices{
{
_val = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName;
}
- public String Value { get {return _val;} }
- }
-
- [Serializable]
- public enum VarEnum
- {
- VT_EMPTY = 0,
- VT_NULL = 1,
- VT_I2 = 2,
- VT_I4 = 3,
- VT_R4 = 4,
- VT_R8 = 5,
- VT_CY = 6,
- VT_DATE = 7,
- VT_BSTR = 8,
- VT_DISPATCH = 9,
- VT_ERROR = 10,
- VT_BOOL = 11,
- VT_VARIANT = 12,
- VT_UNKNOWN = 13,
- VT_DECIMAL = 14,
- VT_I1 = 16,
- VT_UI1 = 17,
- VT_UI2 = 18,
- VT_UI4 = 19,
- VT_I8 = 20,
- VT_UI8 = 21,
- VT_INT = 22,
- VT_UINT = 23,
- VT_VOID = 24,
- VT_HRESULT = 25,
- VT_PTR = 26,
- VT_SAFEARRAY = 27,
- VT_CARRAY = 28,
- VT_USERDEFINED = 29,
- VT_LPSTR = 30,
- VT_LPWSTR = 31,
- VT_RECORD = 36,
- VT_FILETIME = 64,
- VT_BLOB = 65,
- VT_STREAM = 66,
- VT_STORAGE = 67,
- VT_STREAMED_OBJECT = 68,
- VT_STORED_OBJECT = 69,
- VT_BLOB_OBJECT = 70,
- VT_CF = 71,
- VT_CLSID = 72,
- VT_VECTOR = 0x1000,
- VT_ARRAY = 0x2000,
- VT_BYREF = 0x4000
- }
-
- [Serializable]
- // Note that this enum should remain in-sync with the CorNativeType enum in corhdr.h
- public enum UnmanagedType
- {
- Bool = 0x2, // 4 byte boolean value (true != 0, false == 0)
-
- I1 = 0x3, // 1 byte signed value
-
- U1 = 0x4, // 1 byte unsigned value
-
- I2 = 0x5, // 2 byte signed value
-
- U2 = 0x6, // 2 byte unsigned value
-
- I4 = 0x7, // 4 byte signed value
-
- U4 = 0x8, // 4 byte unsigned value
-
- I8 = 0x9, // 8 byte signed value
-
- U8 = 0xa, // 8 byte unsigned value
-
- R4 = 0xb, // 4 byte floating point
-
- R8 = 0xc, // 8 byte floating point
-
- Currency = 0xf, // A currency
-
- BStr = 0x13, // OLE Unicode BSTR
-
- LPStr = 0x14, // Ptr to SBCS string
-
- LPWStr = 0x15, // Ptr to Unicode string
-
- LPTStr = 0x16, // Ptr to OS preferred (SBCS/Unicode) string
-
- ByValTStr = 0x17, // OS preferred (SBCS/Unicode) inline string (only valid in structs)
-
- IUnknown = 0x19, // COM IUnknown pointer.
-
- IDispatch = 0x1a, // COM IDispatch pointer
-
- Struct = 0x1b, // Structure
-
- Interface = 0x1c, // COM interface
-
- SafeArray = 0x1d, // OLE SafeArray
-
- ByValArray = 0x1e, // Array of fixed size (only valid in structs)
-
- SysInt = 0x1f, // Hardware natural sized signed integer
-
- SysUInt = 0x20,
-
- VBByRefStr = 0x22,
-
- AnsiBStr = 0x23, // OLE BSTR containing SBCS characters
-
- TBStr = 0x24, // Ptr to OS preferred (SBCS/Unicode) BSTR
-
- VariantBool = 0x25, // OLE defined BOOLEAN (2 bytes, true == -1, false == 0)
-
- FunctionPtr = 0x26, // Function pointer
-
- AsAny = 0x28, // Paired with Object type and does runtime marshalling determination
-
- LPArray = 0x2a, // C style array
-
- LPStruct = 0x2b, // Pointer to a structure
-
- CustomMarshaler = 0x2c,
-
- Error = 0x2d,
-
- IInspectable = 0x2e,
-
- HString = 0x2f, // Windows Runtime HSTRING
-
- LPUTF8Str = 0x30, // UTF8 string
+ public String Value { get { return _val; } }
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)]
@@ -403,11 +242,11 @@ namespace System.Runtime.InteropServices{
public UnmanagedType Value { get { return _val; } }
// Fields used with SubType = SafeArray.
- public VarEnum SafeArraySubType;
- public Type SafeArrayUserDefinedSubType;
+ public VarEnum SafeArraySubType;
+ public Type SafeArrayUserDefinedSubType;
// Field used with iid_is attribute (interface pointers).
- public int IidParameterIndex;
+ public int IidParameterIndex;
// Fields used with SubType = ByValArray and LPArray.
// Array size = parameter(PI) * PM + C
@@ -639,7 +478,6 @@ namespace System.Runtime.InteropServices{
public CallingConvention CallingConvention;
public bool BestFitMapping;
public bool ThrowOnUnmappableChar;
-
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
index d36f8cfa39..77c38139cd 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/BStrWrapper.cs
@@ -11,11 +11,12 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Security;
+using System;
+using System.Security;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
public sealed class BStrWrapper
{
@@ -29,9 +30,9 @@ namespace System.Runtime.InteropServices {
m_WrappedObject = (String)value;
}
- public String WrappedObject
+ public String WrappedObject
{
- get
+ get
{
return m_WrappedObject;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
index 87e6be6d4e..889a74f6bc 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
@@ -12,55 +12,63 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Runtime.Serialization;
- using System.Globalization;
- using System.Security;
- using Microsoft.Win32;
+using System;
+using System.Runtime.Serialization;
+using System.Globalization;
+using System.Security;
+using Microsoft.Win32;
+namespace System.Runtime.InteropServices
+{
// Exception for COM Interop errors where we don't recognize the HResult.
//
[Serializable]
- public class COMException : ExternalException {
- public COMException()
- : base(Environment.GetResourceString("Arg_COMException"))
+ public class COMException : ExternalException
+ {
+ public COMException()
+ : base(SR.Arg_COMException)
{
- SetErrorCode(__HResults.E_FAIL);
+ HResult = __HResults.E_FAIL;
}
-
- public COMException(String message)
+
+ public COMException(String message)
: base(message)
{
- SetErrorCode(__HResults.E_FAIL);
+ HResult = __HResults.E_FAIL;
}
-
- public COMException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.E_FAIL);
+
+ public COMException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.E_FAIL;
}
-
- public COMException(String message,int errorCode)
- : base(message) {
- SetErrorCode(errorCode);
+
+ public COMException(String message, int errorCode)
+ : base(message)
+ {
+ HResult = errorCode;
}
- protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected COMException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
- public override String ToString() {
+ public override String ToString()
+ {
String message = Message;
String s;
String _className = GetType().ToString();
s = _className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")";
- if (!(message == null || message.Length <= 0)) {
+ if (!(message == null || message.Length <= 0))
+ {
s = s + ": " + message;
}
Exception _innerException = InnerException;
- if (_innerException!=null) {
+ if (_innerException != null)
+ {
s = s + " ---> " + _innerException.ToString();
}
@@ -70,7 +78,5 @@ namespace System.Runtime.InteropServices {
return s;
}
-
-
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs b/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
deleted file mode 100644
index 2ef1cf496e..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/CallingConvention.cs
+++ /dev/null
@@ -1,21 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
-
- using System;
- // Used for the CallingConvention named argument to the DllImport attribute
- [Serializable]
- public enum CallingConvention
- {
- Winapi = 1,
- Cdecl = 2,
- StdCall = 3,
- ThisCall = 4,
- FastCall = 5,
- }
-
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs b/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
deleted file mode 100644
index e60d676557..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/CharSet.cs
+++ /dev/null
@@ -1,23 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
- // Use this in P/Direct function prototypes to specify
- // which character set to use when marshalling Strings.
- // Using Ansi will marshal the strings as 1 byte char*'s.
- // Using Unicode will marshal the strings as 2 byte wchar*'s.
- // Generally you probably want to use Auto, which does the
- // right thing 99% of the time.
- [Serializable]
- public enum CharSet
- {
- None = 1, // User didn't specify how to marshal strings.
- Ansi = 2, // Strings should be marshalled as ANSI 1 byte chars.
- Unicode = 3, // Strings should be marshalled as Unicode 2 byte chars.
- Auto = 4, // Marshal Strings in the right way for the target system.
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
index 82692c1c54..8198d9fd18 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
@@ -10,104 +10,105 @@
** managed delegates to COM's connection point based events.
**
**/
-namespace System.Runtime.InteropServices {
- //
- // #ComEventsFeature
- //
- // code:#ComEventsFeature defines two public methods allowing to add/remove .NET delegates handling
- // events from COM objects. Those methods are defined as part of code:ComEventsHelper static class
- // * code:ComEventsHelper.Combine - will create/reuse-an-existing COM event sink and register the
- // specified delegate to be raised when corresponding COM event is raised
- // * code:ComEventsHelper.Remove
- //
- //
- // To bind an event handler to the COM object you need to provide the following data:
- // * rcw - the instance of the COM object you want to bind to
- // * iid - Guid of the source interface you want the sink to implement
- // * dispid - dispatch identifier of the event on the source interface you are interested in
- // * d - delegate to invoked when corresponding COM event is raised.
- //
- // #ComEventsArchitecture:
- // In COM world, events are handled by so-called event sinks. What these are? COM-based Object Models
- // (OMs) define "source" interfaces that need to be implemented by the COM clients to receive events. So,
- // event sinks are COM objects implementing a source interfaces. Once an event sink is passed to the COM
- // server (through a mechanism known as 'binding/advising to connection point'), COM server will be
- // calling source interface methods to "fire events" (advising, connection points, firing events etc. -
- // is all COM jargon).
- //
- // There are few interesting obervations about source interfaces. Usually source interfaces are defined
- // as 'dispinterface' - meaning that only late-bound invocations on this interface are allowed. Even
- // though it is not illegal to use early bound invocations on source interfaces - the practice is
- // discouraged because of versioning concerns.
- //
- // Notice also that each COM server object might define multiple source interfaces and hence have
- // multiple connection points (each CP handles exactly one source interface). COM objects that want to
- // fire events are required to implement IConnectionPointContainer interface which is used by the COM
- // clients to discovery connection poitns - objects implementing IConnectionPoint interface. Once
- // connection point is found - clients can bind to it using IConnectionPoint::Advise (see
- // code:ComEventsSink.Advise).
- //
- // The idea behind code:#ComEventsFeature is to write a "universal event sink" COM component that is
- // generic enough to handle all late-bound event firings and invoke corresponding COM delegates (through
- // reflection).
- //
- // When delegate is registered (using code:ComEventsHelper.Combine) we will verify we have corresponding
- // event sink created and bound.
- //
- // But what happens when COM events are fired? code:ComEventsSink.Invoke implements IDispatch::Invoke method
- // and this is the entry point that is called. Once our event sink is invoked, we need to find the
- // corresponding delegate to invoke . We need to match the dispid of the call that is coming in to a
- // dispid of .NET delegate that has been registered for this object. Once this is found we do call the
- // delegates using reflection (code:ComEventsMethod.Invoke).
- //
- // #ComEventsArgsMarshalling
- // Notice, that we may not have a delegate registered against every method on the source interface. If we
- // were to marshal all the input parameters for methods that do not reach user code - we would end up
- // generatic RCWs that are not reachable for user code (the inconvenience it might create is there will
- // be RCWs that users can not call Marshal.ReleaseComObject on to explicitly manage the lifetime of these
- // COM objects). The above behavior was one of the shortcoimings of legacy TLBIMP's implementation of COM
- // event sinking. In our code we will not marshal any data if there is no delegate registered to handle
- // the event. (code:ComEventsMethod.Invoke)
- //
- // #ComEventsFinalization:
- // Additional area of interest is when COM sink should be unadvised from the connection point. Legacy
- // TLBIMP's implementation of COM event sinks will unadvises the sink when corresponding RCW is GCed.
- // This is achieved by rooting the event sinks in a finalizable object stored in RCW's property bag
- // (using Marshal.SetComObjectData). Hence, once RCW is no longer reachable - the finalizer is called and
- // it would unadvise all the event sinks. We are employing the same strategy here. See storing an
- // instance in the RCW at code:ComEventsInfo.FromObject and undadvsing the sinks at
- // code:ComEventsInfo.~ComEventsInfo
- //
- // Classes of interest:
- // * code:ComEventsHelpers - defines public methods but there are also a number of internal classes that
- // implement the actual COM event sink:
- // * code:ComEventsInfo - represents a finalizable container for all event sinks for a particular RCW.
- // Lifetime of this instance corresponds to the lifetime of the RCW object
- // * code:ComEventsSink - represents a single event sink. Maintains an internal pointer to the next
- // instance (in a singly linked list). A collection of code:ComEventsSink is stored at
- // code:ComEventsInfo._sinks
- // * code:ComEventsMethod - represents a single method from the source interface which has .NET delegates
- // attached to it. Maintains an internal pointer to the next instance (in a singly linked list). A
- // collection of code:ComEventMethod is stored at code:ComEventsSink._methods
- //
- // #ComEventsRetValIssue:
- // Issue: normally, COM events would not return any value. However, it may happen as described in
- // http://support.microsoft.com/kb/810228. Such design might represent a problem for us - e.g. what is
- // the return value of a chain of delegates - is it the value of the last call in the chain or the the
- // first one? As the above KB article indicates, in cases where OM has events returning values, it is
- // suggested that people implement their event sink by explicitly implementing the source interface. This
- // means that the problem is already quite complex and we should not be dealing with it - see
- // code:ComEventsMethod.Invoke
-
- using System;
- using System.Runtime.Remoting;
-
+//
+// #ComEventsFeature
+//
+// code:#ComEventsFeature defines two public methods allowing to add/remove .NET delegates handling
+// events from COM objects. Those methods are defined as part of code:ComEventsHelper static class
+// * code:ComEventsHelper.Combine - will create/reuse-an-existing COM event sink and register the
+// specified delegate to be raised when corresponding COM event is raised
+// * code:ComEventsHelper.Remove
+//
+//
+// To bind an event handler to the COM object you need to provide the following data:
+// * rcw - the instance of the COM object you want to bind to
+// * iid - Guid of the source interface you want the sink to implement
+// * dispid - dispatch identifier of the event on the source interface you are interested in
+// * d - delegate to invoked when corresponding COM event is raised.
+//
+// #ComEventsArchitecture:
+// In COM world, events are handled by so-called event sinks. What these are? COM-based Object Models
+// (OMs) define "source" interfaces that need to be implemented by the COM clients to receive events. So,
+// event sinks are COM objects implementing a source interfaces. Once an event sink is passed to the COM
+// server (through a mechanism known as 'binding/advising to connection point'), COM server will be
+// calling source interface methods to "fire events" (advising, connection points, firing events etc. -
+// is all COM jargon).
+//
+// There are few interesting obervations about source interfaces. Usually source interfaces are defined
+// as 'dispinterface' - meaning that only late-bound invocations on this interface are allowed. Even
+// though it is not illegal to use early bound invocations on source interfaces - the practice is
+// discouraged because of versioning concerns.
+//
+// Notice also that each COM server object might define multiple source interfaces and hence have
+// multiple connection points (each CP handles exactly one source interface). COM objects that want to
+// fire events are required to implement IConnectionPointContainer interface which is used by the COM
+// clients to discovery connection poitns - objects implementing IConnectionPoint interface. Once
+// connection point is found - clients can bind to it using IConnectionPoint::Advise (see
+// code:ComEventsSink.Advise).
+//
+// The idea behind code:#ComEventsFeature is to write a "universal event sink" COM component that is
+// generic enough to handle all late-bound event firings and invoke corresponding COM delegates (through
+// reflection).
+//
+// When delegate is registered (using code:ComEventsHelper.Combine) we will verify we have corresponding
+// event sink created and bound.
+//
+// But what happens when COM events are fired? code:ComEventsSink.Invoke implements IDispatch::Invoke method
+// and this is the entry point that is called. Once our event sink is invoked, we need to find the
+// corresponding delegate to invoke . We need to match the dispid of the call that is coming in to a
+// dispid of .NET delegate that has been registered for this object. Once this is found we do call the
+// delegates using reflection (code:ComEventsMethod.Invoke).
+//
+// #ComEventsArgsMarshalling
+// Notice, that we may not have a delegate registered against every method on the source interface. If we
+// were to marshal all the input parameters for methods that do not reach user code - we would end up
+// generatic RCWs that are not reachable for user code (the inconvenience it might create is there will
+// be RCWs that users can not call Marshal.ReleaseComObject on to explicitly manage the lifetime of these
+// COM objects). The above behavior was one of the shortcoimings of legacy TLBIMP's implementation of COM
+// event sinking. In our code we will not marshal any data if there is no delegate registered to handle
+// the event. (code:ComEventsMethod.Invoke)
+//
+// #ComEventsFinalization:
+// Additional area of interest is when COM sink should be unadvised from the connection point. Legacy
+// TLBIMP's implementation of COM event sinks will unadvises the sink when corresponding RCW is GCed.
+// This is achieved by rooting the event sinks in a finalizable object stored in RCW's property bag
+// (using Marshal.SetComObjectData). Hence, once RCW is no longer reachable - the finalizer is called and
+// it would unadvise all the event sinks. We are employing the same strategy here. See storing an
+// instance in the RCW at code:ComEventsInfo.FromObject and undadvsing the sinks at
+// code:ComEventsInfo.~ComEventsInfo
+//
+// Classes of interest:
+// * code:ComEventsHelpers - defines public methods but there are also a number of internal classes that
+// implement the actual COM event sink:
+// * code:ComEventsInfo - represents a finalizable container for all event sinks for a particular RCW.
+// Lifetime of this instance corresponds to the lifetime of the RCW object
+// * code:ComEventsSink - represents a single event sink. Maintains an internal pointer to the next
+// instance (in a singly linked list). A collection of code:ComEventsSink is stored at
+// code:ComEventsInfo._sinks
+// * code:ComEventsMethod - represents a single method from the source interface which has .NET delegates
+// attached to it. Maintains an internal pointer to the next instance (in a singly linked list). A
+// collection of code:ComEventMethod is stored at code:ComEventsSink._methods
+//
+// #ComEventsRetValIssue:
+// Issue: normally, COM events would not return any value. However, it may happen as described in
+// http://support.microsoft.com/kb/810228. Such design might represent a problem for us - e.g. what is
+// the return value of a chain of delegates - is it the value of the last call in the chain or the the
+// first one? As the above KB article indicates, in cases where OM has events returning values, it is
+// suggested that people implement their event sink by explicitly implementing the source interface. This
+// means that the problem is already quite complex and we should not be dealing with it - see
+// code:ComEventsMethod.Invoke
+
+using System;
+using System.Runtime.Remoting;
+
+namespace System.Runtime.InteropServices
+{
/// <summary>
/// The static methods provided in ComEventsHelper allow using .NET delegates to subscribe to events
/// raised COM objects.
/// </summary>
- public static class ComEventsHelper {
-
+ public static class ComEventsHelper
+ {
/// <summary>
/// Adds a delegate to the invocation list of events originating from the COM object.
/// </summary>
@@ -115,21 +116,24 @@ namespace System.Runtime.InteropServices {
/// <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>
- public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d) {
-
+ public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d)
+ {
rcw = UnwrapIfTransparentProxy(rcw);
- lock (rcw) {
+ lock (rcw)
+ {
ComEventsInfo eventsInfo = ComEventsInfo.FromObject(rcw);
ComEventsSink sink = eventsInfo.FindSink(ref iid);
- if (sink == null) {
+ if (sink == null)
+ {
sink = eventsInfo.AddSink(ref iid);
}
ComEventsMethod method = sink.FindMethod(dispid);
- if (method == null) {
+ if (method == null)
+ {
method = sink.AddMethod(dispid);
}
@@ -145,12 +149,12 @@ namespace System.Runtime.InteropServices {
/// <param name="dispid">dispatch identifier of the method on the source interface</param>
/// <param name="d">delegate to remove from the invocation list</param>
/// <returns></returns>
- public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d) {
-
+ public static Delegate Remove(object rcw, Guid iid, int dispid, System.Delegate d)
+ {
rcw = UnwrapIfTransparentProxy(rcw);
- lock (rcw) {
-
+ lock (rcw)
+ {
ComEventsInfo eventsInfo = ComEventsInfo.Find(rcw);
if (eventsInfo == null)
return null;
@@ -163,15 +167,18 @@ namespace System.Runtime.InteropServices {
method.RemoveDelegate(d);
- if (method.Empty) {
+ if (method.Empty)
+ {
// removed the last event handler for this dispid - need to remove dispid handler
method = sink.RemoveMethod(method);
}
- if (method == null) {
+ if (method == null)
+ {
// removed last dispid handler for this sink - need to remove the sink
sink = eventsInfo.RemoveSink(sink);
}
- if (sink == null) {
+ if (sink == null)
+ {
// removed last sink for this rcw - need to remove all traces of event info
Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), null);
GC.SuppressFinalize(eventsInfo);
@@ -186,5 +193,4 @@ namespace System.Runtime.InteropServices {
return rcw;
}
}
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
index 2456ba35bf..0fbe34db8d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsInfo.cs
@@ -11,64 +11,70 @@
**
**/
-namespace System.Runtime.InteropServices {
-
+namespace System.Runtime.InteropServices
+{
using System;
using ComTypes = System.Runtime.InteropServices.ComTypes;
// see code:ComEventsHelper#ComEventsArchitecture
- internal class ComEventsInfo {
-
-
-#region fields
+ internal class ComEventsInfo
+ {
+ #region fields
private ComEventsSink _sinks;
private object _rcw;
-#endregion
+ #endregion
-#region ctor/dtor
+ #region ctor/dtor
- ComEventsInfo(object rcw) {
+ private ComEventsInfo(object rcw)
+ {
_rcw = rcw;
}
- ~ComEventsInfo() {
+ ~ComEventsInfo()
+ {
// see code:ComEventsHelper#ComEventsFinalization
_sinks = ComEventsSink.RemoveAll(_sinks);
}
-#endregion
+ #endregion
-#region static methods
+ #region static methods
- internal static ComEventsInfo Find(object rcw) {
+ internal static ComEventsInfo Find(object rcw)
+ {
return (ComEventsInfo)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo));
}
// it is caller's responsibility to call this method under lock(rcw)
- internal static ComEventsInfo FromObject(object rcw) {
+ internal static ComEventsInfo FromObject(object rcw)
+ {
ComEventsInfo eventsInfo = Find(rcw);
- if (eventsInfo == null) {
+ if (eventsInfo == null)
+ {
eventsInfo = new ComEventsInfo(rcw);
Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), eventsInfo);
}
return eventsInfo;
}
-#endregion
+ #endregion
-#region internal methods
+ #region internal methods
- internal ComEventsSink FindSink(ref Guid iid) {
+ internal ComEventsSink FindSink(ref Guid iid)
+ {
return ComEventsSink.Find(_sinks, ref iid);
}
// it is caller's responsibility to call this method under lock(rcw)
- internal ComEventsSink AddSink(ref Guid iid) {
+ internal ComEventsSink AddSink(ref Guid iid)
+ {
ComEventsSink sink = new ComEventsSink(_rcw, iid);
_sinks = ComEventsSink.Add(_sinks, sink);
@@ -76,12 +82,12 @@ namespace System.Runtime.InteropServices {
}
// it is caller's responsibility to call this method under lock(rcw)
- internal ComEventsSink RemoveSink(ComEventsSink sink) {
+ internal ComEventsSink RemoveSink(ComEventsSink sink)
+ {
_sinks = ComEventsSink.Remove(_sinks, sink);
return _sinks;
}
-#endregion
-
+ #endregion
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs
index c2f56b0580..f7e84cabb5 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsMethod.cs
@@ -10,6 +10,7 @@
** managed delegates to COM's connection point based events.
**
**/
+
using System;
using System.Collections.Generic;
using System.Text;
@@ -18,11 +19,11 @@ using System.Runtime.InteropServices;
using System.Reflection;
-namespace System.Runtime.InteropServices {
-
+namespace System.Runtime.InteropServices
+{
// see code:ComEventsHelper#ComEventsArchitecture
- internal class ComEventsMethod {
-
+ internal class ComEventsMethod
+ {
// This delegate wrapper class handles dynamic invocation of delegates. The reason for the wrapper's
// existence is that under certain circumstances we need to coerce arguments to types expected by the
// delegates signature. Normally, reflection (Delegate.DynamicInvoke) handles types coercion
@@ -30,18 +31,21 @@ namespace System.Runtime.InteropServices {
// reflection by design does not do the coercion. Since we need to be compatible with COM interop
// handling of this scenario - we are pre-processing delegate's signature by looking for 'ref enums'
// and cache the types required for such coercion.
- internal class DelegateWrapper {
+ internal class DelegateWrapper
+ {
private Delegate _d;
private bool _once = false;
private int _expectedParamsCount;
private Type[] _cachedTargetTypes;
- public DelegateWrapper(Delegate d) {
+ public DelegateWrapper(Delegate d)
+ {
_d = d;
}
- public Delegate Delegate {
+ public Delegate Delegate
+ {
get { return _d; }
set { _d = value; }
}
@@ -54,42 +58,50 @@ namespace System.Runtime.InteropServices {
/// Since multicast delegate's built-in chaining supports only chaining instances of the same type,
/// we need to complement this design by using an explicit linked list data structure.
/// </summary>
- private DelegateWrapper [] _delegateWrappers;
+ private DelegateWrapper[] _delegateWrappers;
private int _dispid;
private ComEventsMethod _next;
#endregion
-
+
#region ctor
-
- internal ComEventsMethod(int dispid) {
+
+ internal ComEventsMethod(int dispid)
+ {
_delegateWrappers = null;
_dispid = dispid;
}
-
+
#endregion
-
+
#region static internal methods
-
- internal static ComEventsMethod Find(ComEventsMethod methods, int dispid) {
- while (methods != null && methods._dispid != dispid) {
+
+ internal static ComEventsMethod Find(ComEventsMethod methods, int dispid)
+ {
+ while (methods != null && methods._dispid != dispid)
+ {
methods = methods._next;
}
return methods;
}
- internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) {
+ internal static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method)
+ {
method._next = methods;
return method;
}
- internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) {
- if (methods == method) {
+ internal static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method)
+ {
+ if (methods == method)
+ {
methods = methods._next;
- } else {
+ }
+ else
+ {
ComEventsMethod current = methods;
while (current != null && current._next != method)
current = current._next;
@@ -100,28 +112,34 @@ namespace System.Runtime.InteropServices {
return methods;
}
-#endregion
-#region public properties / methods
+ #endregion
+ #region public properties / methods
- internal bool Empty {
+ internal bool Empty
+ {
get { return _delegateWrappers == null || _delegateWrappers.Length == 0; }
}
- internal void AddDelegate(Delegate d) {
+ internal void AddDelegate(Delegate d)
+ {
int count = 0;
- if (_delegateWrappers != null) {
+ if (_delegateWrappers != null)
+ {
count = _delegateWrappers.Length;
}
- for (int i = 0; i < count; i++) {
- if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) {
+ for (int i = 0; i < count; i++)
+ {
+ if (_delegateWrappers[i].Delegate.GetType() == d.GetType())
+ {
_delegateWrappers[i].Delegate = Delegate.Combine(_delegateWrappers[i].Delegate, d);
return;
}
}
- DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count + 1];
- if (count > 0) {
+ DelegateWrapper[] newDelegateWrappers = new DelegateWrapper[count + 1];
+ if (count > 0)
+ {
_delegateWrappers.CopyTo(newDelegateWrappers, 0);
}
@@ -131,13 +149,15 @@ namespace System.Runtime.InteropServices {
_delegateWrappers = newDelegateWrappers;
}
- internal void RemoveDelegate(Delegate d) {
-
+ internal void RemoveDelegate(Delegate d)
+ {
int count = _delegateWrappers.Length;
int removeIdx = -1;
- for (int i = 0; i < count; i++) {
- if (_delegateWrappers[i].Delegate.GetType() == d.GetType()) {
+ for (int i = 0; i < count; i++)
+ {
+ if (_delegateWrappers[i].Delegate.GetType() == d.GetType())
+ {
removeIdx = i;
break;
}
@@ -147,25 +167,29 @@ namespace System.Runtime.InteropServices {
return;
Delegate newDelegate = Delegate.Remove(_delegateWrappers[removeIdx].Delegate, d);
- if (newDelegate != null) {
+ if (newDelegate != null)
+ {
_delegateWrappers[removeIdx].Delegate = newDelegate;
return;
}
// now remove the found entry from the _delegates array
- if (count == 1) {
+ if (count == 1)
+ {
_delegateWrappers = null;
return;
}
- DelegateWrapper [] newDelegateWrappers = new DelegateWrapper[count - 1];
+ DelegateWrapper[] newDelegateWrappers = new DelegateWrapper[count - 1];
int j = 0;
- while (j < removeIdx) {
+ while (j < removeIdx)
+ {
newDelegateWrappers[j] = _delegateWrappers[j];
j++;
}
- while (j < count-1) {
+ while (j < count - 1)
+ {
newDelegateWrappers[j] = _delegateWrappers[j + 1];
j++;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
index f2b22e3ceb..08f27dc038 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsSink.cs
@@ -11,14 +11,15 @@
**
**/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Diagnostics;
+using System;
+using System.Diagnostics;
+namespace System.Runtime.InteropServices
+{
// see code:ComEventsHelper#ComEventsArchitecture
internal class ComEventsSink : ICustomQueryInterface
{
-#region private fields
+ #region private fields
private Guid _iidSourceItf;
private ComTypes.IConnectionPoint _connectionPoint;
@@ -26,38 +27,43 @@ namespace System.Runtime.InteropServices {
private ComEventsMethod _methods;
private ComEventsSink _next;
-#endregion
+ #endregion
-
-#region ctor
- internal ComEventsSink(object rcw, Guid iid) {
+ #region ctor
+
+ internal ComEventsSink(object rcw, Guid iid)
+ {
_iidSourceItf = iid;
this.Advise(rcw);
- }
+ }
-#endregion
+ #endregion
-
-#region static members
- internal static ComEventsSink Find(ComEventsSink sinks, ref Guid iid) {
+ #region static members
+ internal static ComEventsSink Find(ComEventsSink sinks, ref Guid iid)
+ {
ComEventsSink sink = sinks;
- while (sink != null && sink._iidSourceItf != iid) {
+ while (sink != null && sink._iidSourceItf != iid)
+ {
sink = sink._next;
}
return sink;
}
- internal static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink) {
+ internal static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink)
+ {
sink._next = sinks;
return sink;
}
- internal static ComEventsSink RemoveAll(ComEventsSink sinks) {
- while (sinks != null) {
+ internal static ComEventsSink RemoveAll(ComEventsSink sinks)
+ {
+ while (sinks != null)
+ {
sinks.Unadvise();
sinks = sinks._next;
}
@@ -65,18 +71,23 @@ namespace System.Runtime.InteropServices {
return null;
}
- internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) {
+ internal static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink)
+ {
BCLDebug.Assert(sinks != null, "removing event sink from empty sinks collection");
BCLDebug.Assert(sink != null, "specify event sink is null");
- if (sink == sinks) {
+ if (sink == sinks)
+ {
sinks = sinks._next;
- } else {
+ }
+ else
+ {
ComEventsSink current = sinks;
while (current != null && current._next != sink)
current = current._next;
- if (current != null) {
+ if (current != null)
+ {
current._next = sink._next;
}
}
@@ -84,35 +95,40 @@ namespace System.Runtime.InteropServices {
sink.Unadvise();
return sinks;
- }
+ }
-#endregion
+ #endregion
-#region public methods
+ #region public methods
- public ComEventsMethod RemoveMethod(ComEventsMethod method) {
+ public ComEventsMethod RemoveMethod(ComEventsMethod method)
+ {
_methods = ComEventsMethod.Remove(_methods, method);
return _methods;
}
- public ComEventsMethod FindMethod(int dispid) {
+ public ComEventsMethod FindMethod(int dispid)
+ {
return ComEventsMethod.Find(_methods, dispid);
}
- public ComEventsMethod AddMethod(int dispid) {
+ public ComEventsMethod AddMethod(int dispid)
+ {
ComEventsMethod method = new ComEventsMethod(dispid);
_methods = ComEventsMethod.Add(_methods, method);
return method;
- }
+ }
-#endregion
+ #endregion
- static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
+ private static Guid IID_IManagedObject = new Guid("{C3FCC19E-A970-11D2-8B5A-00A0C9B7C9C4}");
- CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) {
+ CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv)
+ {
ppv = IntPtr.Zero;
- if (iid == this._iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID) {
+ if (iid == _iidSourceItf || iid == typeof(NativeMethods.IDispatch).GUID)
+ {
ppv = Marshal.GetComInterfaceForObject(this, typeof(NativeMethods.IDispatch), CustomQueryInterfaceMode.Ignore);
return CustomQueryInterfaceResult.Handled;
}
@@ -124,10 +140,11 @@ namespace System.Runtime.InteropServices {
return CustomQueryInterfaceResult.NotHandled;
}
-#region private methods
+ #region private methods
- private void Advise(object rcw) {
+ private void Advise(object rcw)
+ {
BCLDebug.Assert(_connectionPoint == null, "comevent sink is already advised");
ComTypes.IConnectionPointContainer cpc = (ComTypes.IConnectionPointContainer)rcw;
@@ -141,21 +158,26 @@ namespace System.Runtime.InteropServices {
_connectionPoint = cp;
}
- private void Unadvise() {
+ private void Unadvise()
+ {
BCLDebug.Assert(_connectionPoint != null, "can not unadvise from empty connection point");
- try {
+ try
+ {
_connectionPoint.Unadvise(_cookie);
Marshal.ReleaseComObject(_connectionPoint);
- } catch (System.Exception) {
+ }
+ catch (System.Exception)
+ {
// swallow all exceptions on unadvise
// the host may not be available at this point
- } finally {
+ }
+ finally
+ {
_connectionPoint = null;
}
+ }
- }
-
-#endregion
+ #endregion
};
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
index c61d1b21be..ea99781975 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComMemberType.cs
@@ -4,15 +4,16 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
+using System;
+namespace System.Runtime.InteropServices
+{
[Serializable]
public enum ComMemberType
{
- Method = 0,
- PropGet = 1,
- PropSet = 2
+ Method = 0,
+ PropGet = 1,
+ PropSet = 2
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs
index aac3f59d0f..152f1cd655 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IBindCtx.cs
@@ -11,13 +11,13 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[StructLayout(LayoutKind.Sequential)]
- public struct BIND_OPTS
+ public struct BIND_OPTS
{
public int cbStruct;
public int grfFlags;
@@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.ComTypes
[Guid("0000000e-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
- public interface IBindCtx
+ public interface IBindCtx
{
void RegisterObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk);
void RevokeObjectBound([MarshalAs(UnmanagedType.Interface)] Object punk);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs
index f70973e60d..3933d528a9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPoint.cs
@@ -11,15 +11,15 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("B196B286-BAB4-101A-B69C-00AA00341D07")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IConnectionPoint
- {
+ {
void GetConnectionInterface(out Guid pIID);
void GetConnectionPointContainer(out IConnectionPointContainer ppCPC);
void Advise([MarshalAs(UnmanagedType.Interface)] Object pUnkSink, out int pdwCookie);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs
index fffff3c170..881dd8acfe 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IConnectionPointContainer.cs
@@ -11,11 +11,11 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
- [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")]
+ [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IConnectionPointContainer
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs
index d667925b7e..32ad1f7f06 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnectionPoints.cs
@@ -11,15 +11,15 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("B196B285-BAB4-101A-B69C-00AA00341D07")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IEnumConnectionPoints
- {
+ {
[PreserveSig]
int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] IConnectionPoint[] rgelt, IntPtr pceltFetched);
[PreserveSig]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs
index 8a2b4f0e6f..1acfe54657 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumConnections.cs
@@ -11,15 +11,15 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CONNECTDATA
- {
- [MarshalAs(UnmanagedType.Interface)]
+ {
+ [MarshalAs(UnmanagedType.Interface)]
public Object pUnk;
public int dwCookie;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs
index 57994b66bc..4513bc86ff 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumMoniker.cs
@@ -11,14 +11,14 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("00000102-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
- public interface IEnumMoniker
+ public interface IEnumMoniker
{
[PreserveSig]
int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] IMoniker[] rgelt, IntPtr pceltFetched);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs
index f1e9233581..5738a42751 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumString.cs
@@ -11,14 +11,14 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("00000101-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
- public interface IEnumString
+ public interface IEnumString
{
[PreserveSig]
int Next(int celt, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0), Out] String[] rgelt, IntPtr pceltFetched);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs
index ea9b74b7c1..b94ac5e4c9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IEnumVARIANT.cs
@@ -11,17 +11,17 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
- [Guid("00020404-0000-0000-C000-000000000046")]
+ [Guid("00020404-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IEnumVARIANT
{
[PreserveSig]
- int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0), Out] object[] rgVar, IntPtr pceltFetched);
+ int Next(int celt, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0), Out] object[] rgVar, IntPtr pceltFetched);
[PreserveSig]
int Skip(int celt);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs
index caee5e7fa3..ea45149b29 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IMoniker.cs
@@ -11,22 +11,22 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[StructLayout(LayoutKind.Sequential)]
- public struct FILETIME
+ public struct FILETIME
{
- public int dwLowDateTime;
- public int dwHighDateTime;
+ public int dwLowDateTime;
+ public int dwHighDateTime;
}
[Guid("0000000f-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
- public interface IMoniker
+ public interface IMoniker
{
// IPersist portion
void GetClassID(out Guid pClassID);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs
index a9f118a354..467a9e3a6a 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IPersistFile.cs
@@ -11,10 +11,10 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("0000010b-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
@@ -22,7 +22,7 @@ namespace System.Runtime.InteropServices.ComTypes
{
// IPersist portion
void GetClassID(out Guid pClassID);
-
+
// IPersistFile portion
[PreserveSig]
int IsDirty();
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs
index bebbdec70c..ffca35ae83 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IRunningObjectTable.cs
@@ -11,14 +11,14 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("00000010-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
- public interface IRunningObjectTable
+ public interface IRunningObjectTable
{
int Register(int grfFlags, [MarshalAs(UnmanagedType.Interface)] Object punkObject, IMoniker pmkObjectName);
void Revoke(int dwRegister);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs
index 616ecbfa18..1a2d81f7ea 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/IStream.cs
@@ -11,11 +11,11 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STATSTG
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
index f938ba91a7..967746f379 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeComp.cs
@@ -11,22 +11,22 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Serializable]
public enum DESCKIND
{
- DESCKIND_NONE = 0,
- DESCKIND_FUNCDESC = DESCKIND_NONE + 1,
- DESCKIND_VARDESC = DESCKIND_FUNCDESC + 1,
- DESCKIND_TYPECOMP = DESCKIND_VARDESC + 1,
- DESCKIND_IMPLICITAPPOBJ = DESCKIND_TYPECOMP + 1,
- DESCKIND_MAX = DESCKIND_IMPLICITAPPOBJ + 1
+ DESCKIND_NONE = 0,
+ DESCKIND_FUNCDESC = DESCKIND_NONE + 1,
+ DESCKIND_VARDESC = DESCKIND_FUNCDESC + 1,
+ DESCKIND_TYPECOMP = DESCKIND_VARDESC + 1,
+ DESCKIND_IMPLICITAPPOBJ = DESCKIND_TYPECOMP + 1,
+ DESCKIND_MAX = DESCKIND_IMPLICITAPPOBJ + 1
}
- [StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct BINDPTR
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
index 7a12605f20..1857fdbb35 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo.cs
@@ -11,61 +11,61 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Serializable]
- public enum TYPEKIND
+ public enum TYPEKIND
{
- TKIND_ENUM = 0,
- TKIND_RECORD = TKIND_ENUM + 1,
- TKIND_MODULE = TKIND_RECORD + 1,
+ TKIND_ENUM = 0,
+ TKIND_RECORD = TKIND_ENUM + 1,
+ TKIND_MODULE = TKIND_RECORD + 1,
TKIND_INTERFACE = TKIND_MODULE + 1,
- TKIND_DISPATCH = TKIND_INTERFACE + 1,
- TKIND_COCLASS = TKIND_DISPATCH + 1,
- TKIND_ALIAS = TKIND_COCLASS + 1,
- TKIND_UNION = TKIND_ALIAS + 1,
- TKIND_MAX = TKIND_UNION + 1
+ TKIND_DISPATCH = TKIND_INTERFACE + 1,
+ TKIND_COCLASS = TKIND_DISPATCH + 1,
+ TKIND_ALIAS = TKIND_COCLASS + 1,
+ TKIND_UNION = TKIND_ALIAS + 1,
+ TKIND_MAX = TKIND_UNION + 1
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
public enum TYPEFLAGS : short
{
- TYPEFLAG_FAPPOBJECT = 0x1,
- TYPEFLAG_FCANCREATE = 0x2,
- TYPEFLAG_FLICENSED = 0x4,
- TYPEFLAG_FPREDECLID = 0x8,
- TYPEFLAG_FHIDDEN = 0x10,
- TYPEFLAG_FCONTROL = 0x20,
- TYPEFLAG_FDUAL = 0x40,
- TYPEFLAG_FNONEXTENSIBLE = 0x80,
- TYPEFLAG_FOLEAUTOMATION = 0x100,
- TYPEFLAG_FRESTRICTED = 0x200,
- TYPEFLAG_FAGGREGATABLE = 0x400,
- TYPEFLAG_FREPLACEABLE = 0x800,
- TYPEFLAG_FDISPATCHABLE = 0x1000,
- TYPEFLAG_FREVERSEBIND = 0x2000,
- TYPEFLAG_FPROXY = 0x4000
+ TYPEFLAG_FAPPOBJECT = 0x1,
+ TYPEFLAG_FCANCREATE = 0x2,
+ TYPEFLAG_FLICENSED = 0x4,
+ TYPEFLAG_FPREDECLID = 0x8,
+ TYPEFLAG_FHIDDEN = 0x10,
+ TYPEFLAG_FCONTROL = 0x20,
+ TYPEFLAG_FDUAL = 0x40,
+ TYPEFLAG_FNONEXTENSIBLE = 0x80,
+ TYPEFLAG_FOLEAUTOMATION = 0x100,
+ TYPEFLAG_FRESTRICTED = 0x200,
+ TYPEFLAG_FAGGREGATABLE = 0x400,
+ TYPEFLAG_FREPLACEABLE = 0x800,
+ TYPEFLAG_FDISPATCHABLE = 0x1000,
+ TYPEFLAG_FREVERSEBIND = 0x2000,
+ TYPEFLAG_FPROXY = 0x4000
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
public enum IMPLTYPEFLAGS
{
- IMPLTYPEFLAG_FDEFAULT = 0x1,
- IMPLTYPEFLAG_FSOURCE = 0x2,
- IMPLTYPEFLAG_FRESTRICTED = 0x4,
+ IMPLTYPEFLAG_FDEFAULT = 0x1,
+ IMPLTYPEFLAG_FSOURCE = 0x2,
+ IMPLTYPEFLAG_FRESTRICTED = 0x4,
IMPLTYPEFLAG_FDEFAULTVTABLE = 0x8,
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TYPEATTR
- {
+ {
// Constant used with the memid fields.
- public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF);
+ public const int MEMBER_ID_NIL = unchecked((int)0xFFFFFFFF);
// Actual fields of the TypeAttr struct.
public Guid guid;
@@ -91,55 +91,55 @@ namespace System.Runtime.InteropServices.ComTypes
[StructLayout(LayoutKind.Sequential)]
public struct FUNCDESC
- {
+ {
public int memid; //MEMBERID memid;
public IntPtr lprgscode; // /* [size_is(cScodes)] */ SCODE RPC_FAR *lprgscode;
public IntPtr lprgelemdescParam; // /* [size_is(cParams)] */ ELEMDESC __RPC_FAR *lprgelemdescParam;
- public FUNCKIND funckind; //FUNCKIND funckind;
+ public FUNCKIND funckind; //FUNCKIND funckind;
public INVOKEKIND invkind; //INVOKEKIND invkind;
- public CALLCONV callconv; //CALLCONV callconv;
+ public CALLCONV callconv; //CALLCONV callconv;
public Int16 cParams; //short cParams;
public Int16 cParamsOpt; //short cParamsOpt;
public Int16 oVft; //short oVft;
public Int16 cScodes; //short cScodes;
- public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
+ public ELEMDESC elemdescFunc; //ELEMDESC elemdescFunc;
public Int16 wFuncFlags; //WORD wFuncFlags;
}
-[Serializable]
-[Flags()]
- public enum IDLFLAG : short
+ [Serializable]
+ [Flags()]
+ public enum IDLFLAG : short
{
- IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE,
- IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN,
- IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT,
- IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID,
+ IDLFLAG_NONE = PARAMFLAG.PARAMFLAG_NONE,
+ IDLFLAG_FIN = PARAMFLAG.PARAMFLAG_FIN,
+ IDLFLAG_FOUT = PARAMFLAG.PARAMFLAG_FOUT,
+ IDLFLAG_FLCID = PARAMFLAG.PARAMFLAG_FLCID,
IDLFLAG_FRETVAL = PARAMFLAG.PARAMFLAG_FRETVAL
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct IDLDESC
{
- public IntPtr dwReserved;
- public IDLFLAG wIDLFlags;
+ public IntPtr dwReserved;
+ public IDLFLAG wIDLFlags;
}
-[Serializable]
-[Flags()]
- public enum PARAMFLAG :short
+ [Serializable]
+ [Flags()]
+ public enum PARAMFLAG : short
{
- PARAMFLAG_NONE = 0,
- PARAMFLAG_FIN = 0x1,
- PARAMFLAG_FOUT = 0x2,
- PARAMFLAG_FLCID = 0x4,
+ PARAMFLAG_NONE = 0,
+ PARAMFLAG_FIN = 0x1,
+ PARAMFLAG_FOUT = 0x2,
+ PARAMFLAG_FLCID = 0x4,
PARAMFLAG_FRETVAL = 0x8,
- PARAMFLAG_FOPT = 0x10,
+ PARAMFLAG_FOPT = 0x10,
PARAMFLAG_FHASDEFAULT = 0x20,
PARAMFLAG_FHASCUSTDATA = 0x40
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PARAMDESC
{
@@ -147,21 +147,21 @@ namespace System.Runtime.InteropServices.ComTypes
public PARAMFLAG wParamFlags;
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct TYPEDESC
- {
+ {
public IntPtr lpValue;
public Int16 vt;
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ELEMDESC
{
public TYPEDESC tdesc;
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct DESCUNION
{
@@ -176,20 +176,20 @@ namespace System.Runtime.InteropServices.ComTypes
[Serializable]
public enum VARKIND : int
{
- VAR_PERINSTANCE = 0x0,
- VAR_STATIC = 0x1,
- VAR_CONST = 0x2,
- VAR_DISPATCH = 0x3
+ VAR_PERINSTANCE = 0x0,
+ VAR_STATIC = 0x1,
+ VAR_CONST = 0x2,
+ VAR_DISPATCH = 0x3
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct VARDESC
{
- public int memid;
+ public int memid;
public String lpstrSchema;
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet=CharSet.Unicode)]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
public struct DESCUNION
{
@@ -206,7 +206,7 @@ namespace System.Runtime.InteropServices.ComTypes
public VARKIND varkind;
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct DISPPARAMS
{
@@ -216,7 +216,7 @@ namespace System.Runtime.InteropServices.ComTypes
public int cNamedArgs;
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct EXCEPINFO
{
@@ -228,7 +228,7 @@ namespace System.Runtime.InteropServices.ComTypes
public int dwHelpContext;
public IntPtr pvReserved;
public IntPtr pfnDeferredFillIn;
- public Int32 scode;
+ public Int32 scode;
}
[Serializable]
@@ -241,8 +241,8 @@ namespace System.Runtime.InteropServices.ComTypes
FUNC_DISPATCH = 4
}
-[Serializable]
-[Flags]
+ [Serializable]
+ [Flags]
public enum INVOKEKIND : int
{
INVOKE_FUNC = 0x1,
@@ -254,54 +254,54 @@ namespace System.Runtime.InteropServices.ComTypes
[Serializable]
public enum CALLCONV : int
{
- CC_CDECL =1,
- CC_MSCPASCAL=2,
- CC_PASCAL =CC_MSCPASCAL,
- CC_MACPASCAL=3,
- CC_STDCALL =4,
- CC_RESERVED =5,
- CC_SYSCALL =6,
- CC_MPWCDECL =7,
- CC_MPWPASCAL=8,
- CC_MAX =9
+ CC_CDECL = 1,
+ CC_MSCPASCAL = 2,
+ CC_PASCAL = CC_MSCPASCAL,
+ CC_MACPASCAL = 3,
+ CC_STDCALL = 4,
+ CC_RESERVED = 5,
+ CC_SYSCALL = 6,
+ CC_MPWCDECL = 7,
+ CC_MPWPASCAL = 8,
+ CC_MAX = 9
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
public enum FUNCFLAGS : short
{
- FUNCFLAG_FRESTRICTED= 0x1,
- FUNCFLAG_FSOURCE = 0x2,
- FUNCFLAG_FBINDABLE = 0x4,
- FUNCFLAG_FREQUESTEDIT = 0x8,
- FUNCFLAG_FDISPLAYBIND = 0x10,
- FUNCFLAG_FDEFAULTBIND = 0x20,
- FUNCFLAG_FHIDDEN = 0x40,
- FUNCFLAG_FUSESGETLASTERROR= 0x80,
- FUNCFLAG_FDEFAULTCOLLELEM= 0x100,
- FUNCFLAG_FUIDEFAULT = 0x200,
- FUNCFLAG_FNONBROWSABLE = 0x400,
- FUNCFLAG_FREPLACEABLE = 0x800,
- FUNCFLAG_FIMMEDIATEBIND = 0x1000
+ FUNCFLAG_FRESTRICTED = 0x1,
+ FUNCFLAG_FSOURCE = 0x2,
+ FUNCFLAG_FBINDABLE = 0x4,
+ FUNCFLAG_FREQUESTEDIT = 0x8,
+ FUNCFLAG_FDISPLAYBIND = 0x10,
+ FUNCFLAG_FDEFAULTBIND = 0x20,
+ FUNCFLAG_FHIDDEN = 0x40,
+ FUNCFLAG_FUSESGETLASTERROR = 0x80,
+ FUNCFLAG_FDEFAULTCOLLELEM = 0x100,
+ FUNCFLAG_FUIDEFAULT = 0x200,
+ FUNCFLAG_FNONBROWSABLE = 0x400,
+ FUNCFLAG_FREPLACEABLE = 0x800,
+ FUNCFLAG_FIMMEDIATEBIND = 0x1000
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
public enum VARFLAGS : short
{
- VARFLAG_FREADONLY =0x1,
- VARFLAG_FSOURCE =0x2,
- VARFLAG_FBINDABLE =0x4,
- VARFLAG_FREQUESTEDIT =0x8,
- VARFLAG_FDISPLAYBIND =0x10,
- VARFLAG_FDEFAULTBIND =0x20,
- VARFLAG_FHIDDEN =0x40,
- VARFLAG_FRESTRICTED =0x80,
- VARFLAG_FDEFAULTCOLLELEM =0x100,
- VARFLAG_FUIDEFAULT =0x200,
- VARFLAG_FNONBROWSABLE =0x400,
- VARFLAG_FREPLACEABLE =0x800,
- VARFLAG_FIMMEDIATEBIND =0x1000
+ VARFLAG_FREADONLY = 0x1,
+ VARFLAG_FSOURCE = 0x2,
+ VARFLAG_FBINDABLE = 0x4,
+ VARFLAG_FREQUESTEDIT = 0x8,
+ VARFLAG_FDISPLAYBIND = 0x10,
+ VARFLAG_FDEFAULTBIND = 0x20,
+ VARFLAG_FHIDDEN = 0x40,
+ VARFLAG_FRESTRICTED = 0x80,
+ VARFLAG_FDEFAULTCOLLELEM = 0x100,
+ VARFLAG_FUIDEFAULT = 0x200,
+ VARFLAG_FNONBROWSABLE = 0x400,
+ VARFLAG_FREPLACEABLE = 0x800,
+ VARFLAG_FIMMEDIATEBIND = 0x1000
}
[Guid("00020401-0000-0000-C000-000000000046")]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs
index a782b9edd6..7bb7138c46 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeInfo2.cs
@@ -11,10 +11,10 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("00020412-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
index c39b088c0b..3ed6e42d08 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib.cs
@@ -11,36 +11,36 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Serializable]
public enum SYSKIND
{
- SYS_WIN16 = 0,
- SYS_WIN32 = SYS_WIN16 + 1,
- SYS_MAC = SYS_WIN32 + 1,
- SYS_WIN64 = SYS_MAC + 1
+ SYS_WIN16 = 0,
+ SYS_WIN32 = SYS_WIN16 + 1,
+ SYS_MAC = SYS_WIN32 + 1,
+ SYS_WIN64 = SYS_MAC + 1
}
-[Serializable]
-[Flags()]
+ [Serializable]
+ [Flags()]
public enum LIBFLAGS : short
{
- LIBFLAG_FRESTRICTED = 0x1,
- LIBFLAG_FCONTROL = 0x2,
- LIBFLAG_FHIDDEN = 0x4,
- LIBFLAG_FHASDISKIMAGE = 0x8
+ LIBFLAG_FRESTRICTED = 0x1,
+ LIBFLAG_FCONTROL = 0x2,
+ LIBFLAG_FHIDDEN = 0x4,
+ LIBFLAG_FHASDISKIMAGE = 0x8
}
- [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
[Serializable]
public struct TYPELIBATTR
- {
+ {
public Guid guid;
public int lcid;
- public SYSKIND syskind;
+ public SYSKIND syskind;
public Int16 wMajorVerNum;
public Int16 wMinorVerNum;
public LIBFLAGS wLibFlags;
@@ -54,12 +54,12 @@ namespace System.Runtime.InteropServices.ComTypes
[PreserveSig]
int GetTypeInfoCount();
void GetTypeInfo(int index, out ITypeInfo ppTI);
- void GetTypeInfoType(int index, out TYPEKIND pTKind);
- void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo);
- void GetLibAttr(out IntPtr ppTLibAttr);
- void GetTypeComp(out ITypeComp ppTComp);
+ void GetTypeInfoType(int index, out TYPEKIND pTKind);
+ void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo);
+ void GetLibAttr(out IntPtr ppTLibAttr);
+ void GetTypeComp(out ITypeComp ppTComp);
void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
- [return : MarshalAs(UnmanagedType.Bool)]
+ [return: MarshalAs(UnmanagedType.Bool)]
bool IsName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal);
void FindName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal, [MarshalAs(UnmanagedType.LPArray), Out] ITypeInfo[] ppTInfo, [MarshalAs(UnmanagedType.LPArray), Out] int[] rgMemId, ref Int16 pcFound);
[PreserveSig]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs
index 5a7d07c001..48f4fb3782 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComTypes/ITypeLib2.cs
@@ -11,10 +11,10 @@
**
=============================================================================*/
+using System;
+
namespace System.Runtime.InteropServices.ComTypes
{
- using System;
-
[Guid("00020411-0000-0000-C000-000000000046")]
[InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
@@ -23,12 +23,12 @@ namespace System.Runtime.InteropServices.ComTypes
[PreserveSig]
new int GetTypeInfoCount();
new void GetTypeInfo(int index, out ITypeInfo ppTI);
- new void GetTypeInfoType(int index, out TYPEKIND pTKind);
- new void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo);
+ new void GetTypeInfoType(int index, out TYPEKIND pTKind);
+ new void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo);
new void GetLibAttr(out IntPtr ppTLibAttr);
- new void GetTypeComp(out ITypeComp ppTComp);
+ new void GetTypeComp(out ITypeComp ppTComp);
new void GetDocumentation(int index, out String strName, out String strDocString, out int dwHelpContext, out String strHelpFile);
- [return : MarshalAs(UnmanagedType.Bool)]
+ [return: MarshalAs(UnmanagedType.Bool)]
new bool IsName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal);
new void FindName([MarshalAs(UnmanagedType.LPWStr)] String szNameBuf, int lHashVal, [MarshalAs(UnmanagedType.LPArray), Out] ITypeInfo[] ppTInfo, [MarshalAs(UnmanagedType.LPArray), Out] int[] rgMemId, ref Int16 pcFound);
[PreserveSig]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
index 840270141b..734a494bdb 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
@@ -130,122 +130,124 @@ using System.IO;
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.
-public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
-{
- // ! Do not add or rearrange fields as the EE depends on this layout.
- //------------------------------------------------------------------
+ // 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.
+ public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
+ {
+ // ! Do not add or rearrange fields as the EE depends on this layout.
+ //------------------------------------------------------------------
#if DEBUG
- private String _stackTrace; // Where we allocated this CriticalHandle.
+ private String _stackTrace; // Where we allocated this CriticalHandle.
#endif
- protected IntPtr handle; // This must be protected so derived classes can use out params.
- private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization.
+ protected IntPtr handle; // This must be protected so derived classes can use out params.
+ private bool _isClosed; // Set by SetHandleAsInvalid or Close/Dispose/finalization.
- // Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly.
- protected CriticalHandle(IntPtr invalidHandleValue)
- {
- handle = invalidHandleValue;
- _isClosed = false;
+ // Creates a CriticalHandle class. Users must then set the Handle property or allow P/Invoke marshaling to set it implicitly.
+ protected CriticalHandle(IntPtr invalidHandleValue)
+ {
+ handle = invalidHandleValue;
+ _isClosed = false;
#if DEBUG
- if (BCLDebug.SafeHandleStackTracesEnabled)
- _stackTrace = Environment.GetStackTrace(null, false);
- else
- _stackTrace = "For a stack trace showing who allocated this CriticalHandle, set SafeHandleStackTraces to 1 and rerun your app.";
+ if (BCLDebug.SafeHandleStackTracesEnabled)
+ _stackTrace = Environment.GetStackTrace(null, false);
+ else
+ _stackTrace = "For a stack trace showing who allocated this CriticalHandle, set SafeHandleStackTraces to 1 and rerun your app.";
#endif
+ }
+
+ // Adding an empty default constructor for annotation purposes
+ private CriticalHandle() { }
+
+ ~CriticalHandle()
+ {
+ Dispose(false);
+ }
+
+ private void Cleanup()
+ {
+ if (IsClosed)
+ return;
+ _isClosed = true;
+
+ if (IsInvalid)
+ return;
+
+ // Save last error from P/Invoke in case the implementation of
+ // ReleaseHandle trashes it (important because this ReleaseHandle could
+ // occur implicitly as part of unmarshaling another P/Invoke).
+ int lastError = Marshal.GetLastWin32Error();
+
+ if (!ReleaseHandle())
+ FireCustomerDebugProbe();
+
+ Marshal.SetLastWin32Error(lastError);
+
+ GC.SuppressFinalize(this);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern void FireCustomerDebugProbe();
+
+ protected void SetHandle(IntPtr handle)
+ {
+ this.handle = handle;
+ }
+
+ // Returns whether the handle has been explicitly marked as closed
+ // (Close/Dispose) or invalid (SetHandleAsInvalid).
+ public bool IsClosed
+ {
+ get { return _isClosed; }
+ }
+
+ // Returns whether the handle looks like an invalid value (i.e. matches one
+ // of the handle's designated illegal values). CriticalHandle itself doesn't
+ // know what an invalid handle looks like, so this method is abstract and
+ // must be provided by a derived type.
+ public abstract bool IsInvalid
+ {
+ get;
+ }
+
+ public void Close()
+ {
+ Dispose(true);
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ }
+
+ protected virtual void Dispose(bool disposing)
+ {
+ Cleanup();
+ }
+
+ // This should only be called for cases when you know for a fact that
+ // your handle is invalid and you want to record that information.
+ // An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
+ // This method will normally leak handles!
+ public void SetHandleAsInvalid()
+ {
+ _isClosed = true;
+ GC.SuppressFinalize(this);
+ }
+
+ // Implement this abstract method in your derived class to specify how to
+ // free the handle. Be careful not write any code that's subject to faults
+ // in this method (the runtime will prepare the infrastructure for you so
+ // that no jit allocations etc. will occur, but don't allocate memory unless
+ // you can deal with the failure and still free the handle).
+ // The boolean returned should be true for success and false if a
+ // catastrophic error occurred and you wish to trigger a diagnostic for
+ // debugging purposes (the SafeHandleCriticalFailure MDA).
+ protected abstract bool ReleaseHandle();
}
-
- // Adding an empty default constructor for annotation purposes
- private CriticalHandle(){}
-
- ~CriticalHandle()
- {
- Dispose(false);
- }
-
- private void Cleanup()
- {
- if (IsClosed)
- return;
- _isClosed = true;
-
- if (IsInvalid)
- return;
-
- // Save last error from P/Invoke in case the implementation of
- // ReleaseHandle trashes it (important because this ReleaseHandle could
- // occur implicitly as part of unmarshaling another P/Invoke).
- int lastError = Marshal.GetLastWin32Error();
-
- if (!ReleaseHandle())
- FireCustomerDebugProbe();
-
- Marshal.SetLastWin32Error(lastError);
-
- GC.SuppressFinalize(this);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void FireCustomerDebugProbe();
-
- protected void SetHandle(IntPtr handle) {
- this.handle = handle;
- }
-
- // Returns whether the handle has been explicitly marked as closed
- // (Close/Dispose) or invalid (SetHandleAsInvalid).
- public bool IsClosed {
- get { return _isClosed; }
- }
-
- // Returns whether the handle looks like an invalid value (i.e. matches one
- // of the handle's designated illegal values). CriticalHandle itself doesn't
- // know what an invalid handle looks like, so this method is abstract and
- // must be provided by a derived type.
- public abstract bool IsInvalid {
- get;
- }
-
- public void Close() {
- Dispose(true);
- }
-
- public void Dispose()
- {
- Dispose(true);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- Cleanup();
- }
-
- // This should only be called for cases when you know for a fact that
- // your handle is invalid and you want to record that information.
- // An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
- // This method will normally leak handles!
- public void SetHandleAsInvalid()
- {
- _isClosed = true;
- GC.SuppressFinalize(this);
- }
-
- // Implement this abstract method in your derived class to specify how to
- // free the handle. Be careful not write any code that's subject to faults
- // in this method (the runtime will prepare the infrastructure for you so
- // that no jit allocations etc. will occur, but don't allocate memory unless
- // you can deal with the failure and still free the handle).
- // The boolean returned should be true for success and false if a
- // catastrophic error occurred and you wish to trigger a diagnostic for
- // debugging purposes (the SafeHandleCriticalFailure MDA).
- protected abstract bool ReleaseHandle();
-}
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
index 304419e5b0..4b436825e8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CurrencyWrapper.cs
@@ -11,10 +11,11 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
+using System;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
public sealed class CurrencyWrapper
{
@@ -24,15 +25,15 @@ namespace System.Runtime.InteropServices {
}
public CurrencyWrapper(Object obj)
- {
+ {
if (!(obj is Decimal))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDecimal"), nameof(obj));
+ throw new ArgumentException(SR.Arg_MustBeDecimal, nameof(obj));
m_WrappedObject = (Decimal)obj;
}
- public Decimal WrappedObject
+ public Decimal WrappedObject
{
- get
+ get
{
return m_WrappedObject;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
index ccf25af0f9..87ec4ed15e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/DispatchWrapper.cs
@@ -11,11 +11,12 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Security;
+using System;
+using System.Security;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
public sealed class DispatchWrapper
{
@@ -32,9 +33,9 @@ namespace System.Runtime.InteropServices {
m_WrappedObject = obj;
}
- public Object WrappedObject
+ public Object WrappedObject
{
- get
+ get
{
return m_WrappedObject;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
index da02893b1e..73be2c5777 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ErrorWrapper.cs
@@ -11,10 +11,11 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
+using System;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
public sealed class ErrorWrapper
{
@@ -26,18 +27,18 @@ namespace System.Runtime.InteropServices {
public ErrorWrapper(Object errorCode)
{
if (!(errorCode is int))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"), nameof(errorCode));
+ throw new ArgumentException(SR.Arg_MustBeInt32, nameof(errorCode));
m_ErrorCode = (int)errorCode;
- }
+ }
public ErrorWrapper(Exception e)
{
m_ErrorCode = Marshal.GetHRForException(e);
}
- public int ErrorCode
+ public int ErrorCode
{
- get
+ get
{
return m_ErrorCode;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs b/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs
index 429ce13918..2bd398b7a9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Expando/IExpando.cs
@@ -11,11 +11,12 @@
//
//
// The IExpando Interface.
-namespace System.Runtime.InteropServices.Expando {
-
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+
+namespace System.Runtime.InteropServices.Expando
+{
[Guid("AFBF15E6-C37C-11d2-B88E-00A0C9B471B8")]
internal interface IExpando : IReflect
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs b/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
deleted file mode 100644
index 7e1f395e4e..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/ExternalException.cs
+++ /dev/null
@@ -1,77 +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 base class for all errors from Interop or Structured
-** Exception Handling code.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
- // Base exception for COM Interop errors &; Structured Exception Handler
- // exceptions.
- //
- [Serializable]
- public class ExternalException : SystemException {
- public ExternalException()
- : base(Environment.GetResourceString("Arg_ExternalException")) {
- SetErrorCode(__HResults.E_FAIL);
- }
-
- public ExternalException(String message)
- : base(message) {
- SetErrorCode(__HResults.E_FAIL);
- }
-
- public ExternalException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.E_FAIL);
- }
-
- public ExternalException(String message,int errorCode)
- : base(message) {
- SetErrorCode(errorCode);
- }
-
- protected ExternalException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
-
- public virtual int ErrorCode {
- get {
- return HResult;
- }
- }
-
- public override String ToString() {
- String message = Message;
- String s;
- String _className = GetType().ToString();
- s = _className + " (0x" + HResult.ToString("X8", CultureInfo.InvariantCulture) + ")";
-
- if (!(String.IsNullOrEmpty(message))) {
- s = s + ": " + message;
- }
-
- Exception _innerException = InnerException;
-
- if (_innerException!=null) {
- s = s + " ---> " + _innerException.ToString();
- }
-
-
- if (StackTrace != null)
- s += Environment.NewLine + StackTrace;
-
- return s;
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs
index 304f369879..9e813d9bd9 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/GCHandleCookieTable.cs
@@ -91,7 +91,7 @@ namespace System.Runtime.InteropServices
}
if (cookie == GCHandleCookie.Zero)
- throw new OutOfMemoryException(Environment.GetResourceString("OutOfMemory_GCHandleMDA"));
+ throw new OutOfMemoryException(SR.OutOfMemory_GCHandleMDA);
// This handle hasn't been added to the map yet so add it.
m_HandleToCookieMap.Add(handle, cookie);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
index 598fee0618..dcb9e24258 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/GcHandle.cs
@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
namespace System.Runtime.InteropServices
-{
+{
using System;
using System.Runtime.CompilerServices;
using System.Threading;
@@ -113,7 +113,7 @@ namespace System.Runtime.InteropServices
#endif
InternalFree(GetHandleValue(handle));
}
-
+
// Target property - allows getting / updating of the handle's referent.
public Object Target
{
@@ -122,7 +122,7 @@ namespace System.Runtime.InteropServices
ValidateHandle();
return InternalGet(GetHandleValue());
}
-
+
set
{
ValidateHandle();
@@ -140,7 +140,7 @@ namespace System.Runtime.InteropServices
ValidateHandle();
// You can only get the address of pinned handles.
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotPinned"));
+ throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned);
}
// Get the address.
@@ -198,7 +198,7 @@ namespace System.Runtime.InteropServices
}
#endif
return value.m_handle;
- }
+ }
public override int GetHashCode()
{
@@ -208,12 +208,12 @@ namespace System.Runtime.InteropServices
public override bool Equals(Object o)
{
GCHandle hnd;
-
+
// Check that o is a GCHandle first
- if(o == null || !(o is GCHandle))
+ if (o == null || !(o is GCHandle))
return false;
- else
- hnd = (GCHandle) o;
+ else
+ hnd = (GCHandle)o;
return m_handle == hnd.m_handle;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs b/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs
index b1171025ee..41eb1c24ba 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/HandleRef.cs
@@ -2,14 +2,13 @@
// 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.Runtime.InteropServices
{
-
- using System;
-
public struct HandleRef
{
-
// ! Do not add or rearrange fields as the EE depends on this layout.
//------------------------------------------------------------------
internal Object m_wrapper;
@@ -20,22 +19,26 @@ namespace System.Runtime.InteropServices
public HandleRef(Object wrapper, IntPtr handle)
{
m_wrapper = wrapper;
- m_handle = handle;
+ m_handle = handle;
}
- public Object Wrapper {
- get {
+ public Object Wrapper
+ {
+ get
+ {
return m_wrapper;
}
}
-
- public IntPtr Handle {
- get {
+
+ public IntPtr Handle
+ {
+ get
+ {
return m_handle;
}
}
-
-
+
+
public static explicit operator IntPtr(HandleRef value)
{
return value.m_handle;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs
index 002c48a171..f47d348699 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomAdapter.cs
@@ -12,11 +12,12 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
+using System;
+namespace System.Runtime.InteropServices
+{
public interface ICustomAdapter
- {
- [return:MarshalAs(UnmanagedType.IUnknown)] Object GetUnderlyingObject();
+ {
+ [return: MarshalAs(UnmanagedType.IUnknown)] Object GetUnderlyingObject();
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs
index 8e7af10b6e..e7bfc47281 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomFactory.cs
@@ -4,13 +4,13 @@
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
+using System;
+namespace System.Runtime.InteropServices
+{
public interface ICustomFactory
{
MarshalByRefObject CreateInstance(Type serverType);
}
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs
index d9ed289145..571d78dfe3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomMarshaler.cs
@@ -12,18 +12,19 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
+using System;
+namespace System.Runtime.InteropServices
+{
public interface ICustomMarshaler
- {
- Object MarshalNativeToManaged( IntPtr pNativeData );
+ {
+ Object MarshalNativeToManaged(IntPtr pNativeData);
- IntPtr MarshalManagedToNative( Object ManagedObj );
+ IntPtr MarshalManagedToNative(Object ManagedObj);
- void CleanUpNativeData( IntPtr pNativeData );
+ void CleanUpNativeData(IntPtr pNativeData);
- void CleanUpManagedData( Object ManagedObj );
+ void CleanUpManagedData(Object ManagedObj);
int GetNativeDataSize();
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
index 5675b1f2d6..4f4b10bbf0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ICustomQueryInterface.cs
@@ -12,18 +12,19 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
+using System;
+namespace System.Runtime.InteropServices
+{
//====================================================================
// The enum of the return value of IQuerable.GetInterface
//====================================================================
[Serializable]
public enum CustomQueryInterfaceResult
{
- Handled = 0,
- NotHandled = 1,
- Failed = 2,
+ Handled = 0,
+ NotHandled = 1,
+ Failed = 2,
}
//====================================================================
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs b/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs
index afa934caaf..85756cf84f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ITypeLibConverter.cs
@@ -16,9 +16,11 @@
// *** in src/inc/TlbImpExp.idl.
// ***************************************************************************
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Reflection;
- using System.Reflection.Emit;
+
+using System;
+using System.Reflection;
+using System.Reflection.Emit;
+
+namespace System.Runtime.InteropServices
+{
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
index 760210bc28..2fae2b6e52 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
@@ -11,29 +11,35 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+namespace System.Runtime.InteropServices
+{
[Serializable]
- public class InvalidComObjectException : SystemException {
- public InvalidComObjectException()
- : base(Environment.GetResourceString("Arg_InvalidComObjectException")) {
- SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT);
+ public class InvalidComObjectException : SystemException
+ {
+ public InvalidComObjectException()
+ : base(SR.Arg_InvalidComObjectException)
+ {
+ HResult = __HResults.COR_E_INVALIDCOMOBJECT;
}
-
- public InvalidComObjectException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT);
+
+ public InvalidComObjectException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INVALIDCOMOBJECT;
}
-
- public InvalidComObjectException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_INVALIDCOMOBJECT);
+
+ public InvalidComObjectException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_INVALIDCOMOBJECT;
}
- protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ 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 4ca3da5619..5154a028ad 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
@@ -10,29 +10,35 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
- public class InvalidOleVariantTypeException : SystemException {
- public InvalidOleVariantTypeException()
- : base(Environment.GetResourceString("Arg_InvalidOleVariantTypeException")) {
- SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE);
+ public class InvalidOleVariantTypeException : SystemException
+ {
+ public InvalidOleVariantTypeException()
+ : base(SR.Arg_InvalidOleVariantTypeException)
+ {
+ HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE;
}
-
- public InvalidOleVariantTypeException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE);
+
+ public InvalidOleVariantTypeException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE;
}
-
- public InvalidOleVariantTypeException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_INVALIDOLEVARIANTTYPE);
+
+ public InvalidOleVariantTypeException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE;
}
- protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs b/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
deleted file mode 100644
index f7def3a8e9..0000000000
--- a/src/mscorlib/src/System/Runtime/InteropServices/LayoutKind.cs
+++ /dev/null
@@ -1,17 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-////////////////////////////////////////////////////////////////////////////////
-namespace System.Runtime.InteropServices {
- using System;
- // Used in the StructLayoutAttribute class
- [Serializable]
- public enum LayoutKind
- {
- Sequential = 0, // 0x00000008,
- Explicit = 2, // 0x00000010,
- Auto = 3, // 0x00000000,
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
index 9e9103b9c2..248e0d5778 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
@@ -13,7 +13,7 @@
=============================================================================*/
namespace System.Runtime.InteropServices
-{
+{
using System;
using System.Collections.Generic;
using System.Reflection;
@@ -35,7 +35,7 @@ namespace System.Runtime.InteropServices
[Serializable]
public enum CustomQueryInterfaceMode
{
- Ignore = 0,
+ Ignore = 0,
Allow = 1
}
@@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices
//========================================================================
public static partial class Marshal
- {
+ {
//====================================================================
// Defines used inside the Marshal class.
//====================================================================
@@ -101,10 +101,10 @@ namespace System.Runtime.InteropServices
// The name, title and description of the assembly that will contain
// the dynamically generated interop types.
//====================================================================
- private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes";
- private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types";
- private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's";
- private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes";
+ private const String s_strConvertedTypeInfoAssemblyName = "InteropDynamicTypes";
+ private const String s_strConvertedTypeInfoAssemblyTitle = "Interop Dynamic Types";
+ private const String s_strConvertedTypeInfoAssemblyDesc = "Type dynamically generated from ITypeInfo's";
+ private const String s_strConvertedTypeInfoNameSpace = "InteropDynamicTypes";
//====================================================================
@@ -112,22 +112,27 @@ namespace System.Runtime.InteropServices
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetSystemMaxDBCSCharSize();
-
+
unsafe public static String PtrToStringAnsi(IntPtr ptr)
{
- if (IntPtr.Zero == ptr) {
+ if (IntPtr.Zero == ptr)
+ {
return null;
}
- else if (IsWin32Atom(ptr)) {
+ else if (IsWin32Atom(ptr))
+ {
return null;
}
- else {
+ else
+ {
int nb = Win32Native.lstrlenA(ptr);
- if( nb == 0) {
+ if (nb == 0)
+ {
return string.Empty;
}
- else {
- return new String((sbyte *)ptr);
+ else
+ {
+ return new String((sbyte*)ptr);
}
}
}
@@ -139,7 +144,7 @@ namespace System.Runtime.InteropServices
if (len < 0)
throw new ArgumentException(null, nameof(len));
- return new String((sbyte *)ptr, 0, len);
+ return new String((sbyte*)ptr, 0, len);
}
unsafe public static String PtrToStringUni(IntPtr ptr, int len)
@@ -149,28 +154,31 @@ namespace System.Runtime.InteropServices
if (len < 0)
throw new ArgumentException(null, nameof(len));
- return new String((char *)ptr, 0, len);
+ return new String((char*)ptr, 0, len);
}
-
+
public static String PtrToStringAuto(IntPtr ptr, int len)
{
// Ansi platforms are no longer supported
return PtrToStringUni(ptr, len);
- }
-
+ }
+
unsafe public static String PtrToStringUni(IntPtr ptr)
{
- if (IntPtr.Zero == ptr) {
+ if (IntPtr.Zero == ptr)
+ {
return null;
}
- else if (IsWin32Atom(ptr)) {
+ else if (IsWin32Atom(ptr))
+ {
return null;
- }
- else {
- return new String((char *)ptr);
+ }
+ else
+ {
+ return new String((char*)ptr);
}
}
-
+
public static String PtrToStringAuto(IntPtr ptr)
{
// Ansi platforms are no longer supported
@@ -183,7 +191,7 @@ namespace System.Runtime.InteropServices
return PtrToStringUTF8(ptr, nbBytes);
}
- unsafe public static String PtrToStringUTF8(IntPtr ptr,int byteLen)
+ unsafe public static String PtrToStringUTF8(IntPtr ptr, int byteLen)
{
if (byteLen < 0)
{
@@ -232,9 +240,9 @@ namespace System.Runtime.InteropServices
if (t == null)
throw new ArgumentNullException(nameof(t));
if (!(t is RuntimeType))
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
if (t.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
Contract.EndContractBlock();
return SizeOfHelper(t, true);
@@ -285,13 +293,13 @@ namespace System.Runtime.InteropServices
if (t == null)
throw new ArgumentNullException(nameof(t));
Contract.EndContractBlock();
-
+
FieldInfo f = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (f == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_OffsetOfFieldNotFound", t.FullName), nameof(fieldName));
+ throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), nameof(fieldName));
RtFieldInfo rtField = f as RtFieldInfo;
if (rtField == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"), nameof(fieldName));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, nameof(fieldName));
return OffsetOfHelper(rtField);
}
@@ -322,27 +330,27 @@ namespace System.Runtime.InteropServices
//====================================================================
// Copy blocks from CLR arrays to native memory.
//====================================================================
- public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
+ public static void Copy(int[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
+ public static void Copy(char[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
+ public static void Copy(short[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
+ public static void Copy(long[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
+ public static void Copy(float[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
- public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
+ public static void Copy(double[] source, int startIndex, IntPtr destination, int length)
{
CopyToNative(source, startIndex, destination, length);
}
@@ -360,27 +368,27 @@ namespace System.Runtime.InteropServices
//====================================================================
// Copy blocks from native memory to CLR arrays
//====================================================================
- public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
+ public static void Copy(IntPtr source, int[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
+ public static void Copy(IntPtr source, char[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
+ public static void Copy(IntPtr source, short[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
+ public static void Copy(IntPtr source, long[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
+ public static void Copy(IntPtr source, float[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
- public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
+ public static void Copy(IntPtr source, double[] destination, int startIndex, int length)
{
CopyToManaged(source, destination, startIndex, length);
}
@@ -400,14 +408,14 @@ namespace System.Runtime.InteropServices
//====================================================================
public static byte ReadByte([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
public static unsafe byte ReadByte(IntPtr ptr, int ofs)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
return *addr;
}
catch (NullReferenceException)
@@ -419,29 +427,29 @@ namespace System.Runtime.InteropServices
public static byte ReadByte(IntPtr ptr)
{
- return ReadByte(ptr,0);
+ return ReadByte(ptr, 0);
}
- public static short ReadInt16([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
+ public static short ReadInt16([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
-
+
public static unsafe short ReadInt16(IntPtr ptr, int ofs)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned read
- return *((short *)addr);
+ return *((short*)addr);
}
else
{
// unaligned read
short val;
- byte *valPtr = (byte *)&val;
+ byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
return val;
@@ -459,26 +467,26 @@ namespace System.Runtime.InteropServices
return ReadInt16(ptr, 0);
}
- public static int ReadInt32([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
+ public static int ReadInt32([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
-
+
public static unsafe int ReadInt32(IntPtr ptr, int ofs)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned read
- return *((int *)addr);
+ return *((int*)addr);
}
else
{
// unaligned read
int val;
- byte *valPtr = (byte *)&val;
+ byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
@@ -492,59 +500,59 @@ namespace System.Runtime.InteropServices
throw new AccessViolationException();
}
}
-
+
public static int ReadInt32(IntPtr ptr)
{
- return ReadInt32(ptr,0);
+ return ReadInt32(ptr, 0);
}
-
- public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
+
+ public static IntPtr ReadIntPtr([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
- #if BIT64
- return (IntPtr) ReadInt64(ptr, ofs);
- #else // 32
+#if BIT64
+ return (IntPtr)ReadInt64(ptr, ofs);
+#else // 32
return (IntPtr) ReadInt32(ptr, ofs);
- #endif
+#endif
}
public static IntPtr ReadIntPtr(IntPtr ptr, int ofs)
{
- #if BIT64
- return (IntPtr) ReadInt64(ptr, ofs);
- #else // 32
+#if BIT64
+ return (IntPtr)ReadInt64(ptr, ofs);
+#else // 32
return (IntPtr) ReadInt32(ptr, ofs);
- #endif
+#endif
}
-
+
public static IntPtr ReadIntPtr(IntPtr ptr)
{
- #if BIT64
- return (IntPtr) ReadInt64(ptr, 0);
- #else // 32
+#if BIT64
+ return (IntPtr)ReadInt64(ptr, 0);
+#else // 32
return (IntPtr) ReadInt32(ptr, 0);
- #endif
+#endif
}
- public static long ReadInt64([MarshalAs(UnmanagedType.AsAny),In] Object ptr, int ofs)
+ public static long ReadInt64([MarshalAs(UnmanagedType.AsAny), In] Object ptr, int ofs)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
public static unsafe long ReadInt64(IntPtr ptr, int ofs)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned read
- return *((long *)addr);
+ return *((long*)addr);
}
else
{
// unaligned read
long val;
- byte *valPtr = (byte *)&val;
+ byte* valPtr = (byte*)&val;
valPtr[0] = addr[0];
valPtr[1] = addr[1];
valPtr[2] = addr[2];
@@ -562,13 +570,13 @@ namespace System.Runtime.InteropServices
throw new AccessViolationException();
}
}
-
+
public static long ReadInt64(IntPtr ptr)
{
- return ReadInt64(ptr,0);
+ return ReadInt64(ptr, 0);
}
-
-
+
+
//====================================================================
// Write to memory
//====================================================================
@@ -576,7 +584,7 @@ namespace System.Runtime.InteropServices
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
*addr = val;
}
catch (NullReferenceException)
@@ -586,30 +594,30 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteByte([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, byte val)
+ public static void WriteByte([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, byte val)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
public static void WriteByte(IntPtr ptr, byte val)
{
WriteByte(ptr, 0, val);
}
-
+
public static unsafe void WriteInt16(IntPtr ptr, int ofs, short val)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x1) == 0)
{
// aligned write
- *((short *)addr) = val;
+ *((short*)addr) = val;
}
else
{
// unaligned write
- byte *valPtr = (byte *)&val;
+ byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
}
@@ -621,45 +629,45 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteInt16([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, short val)
+ public static void WriteInt16([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, short val)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
public static void WriteInt16(IntPtr ptr, short val)
{
WriteInt16(ptr, 0, val);
- }
-
+ }
+
public static void WriteInt16(IntPtr ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
-
- public static void WriteInt16([In,Out]Object ptr, int ofs, char val)
+
+ public static void WriteInt16([In, Out]Object ptr, int ofs, char val)
{
WriteInt16(ptr, ofs, (short)val);
}
-
+
public static void WriteInt16(IntPtr ptr, char val)
{
WriteInt16(ptr, 0, (short)val);
}
-
+
public static unsafe void WriteInt32(IntPtr ptr, int ofs, int val)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x3) == 0)
{
// aligned write
- *((int *)addr) = val;
+ *((int*)addr) = val;
}
else
{
// unaligned write
- byte *valPtr = (byte *)&val;
+ byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
@@ -673,57 +681,57 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteInt32([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, int val)
+ public static void WriteInt32([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, int val)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
public static void WriteInt32(IntPtr ptr, int val)
{
- WriteInt32(ptr,0,val);
- }
-
+ WriteInt32(ptr, 0, val);
+ }
+
public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val)
{
- #if BIT64
- WriteInt64(ptr, ofs, (long)val);
- #else // 32
+#if BIT64
+ WriteInt64(ptr, ofs, (long)val);
+#else // 32
WriteInt32(ptr, ofs, (int)val);
- #endif
+#endif
}
-
- public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, IntPtr val)
+
+ public static void WriteIntPtr([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, IntPtr val)
{
- #if BIT64
- WriteInt64(ptr, ofs, (long)val);
- #else // 32
+#if BIT64
+ WriteInt64(ptr, ofs, (long)val);
+#else // 32
WriteInt32(ptr, ofs, (int)val);
- #endif
+#endif
}
-
+
public static void WriteIntPtr(IntPtr ptr, IntPtr val)
{
- #if BIT64
- WriteInt64(ptr, 0, (long)val);
- #else // 32
+#if BIT64
+ WriteInt64(ptr, 0, (long)val);
+#else // 32
WriteInt32(ptr, 0, (int)val);
- #endif
+#endif
}
public static unsafe void WriteInt64(IntPtr ptr, int ofs, long val)
{
try
{
- byte *addr = (byte *)ptr + ofs;
+ byte* addr = (byte*)ptr + ofs;
if ((unchecked((int)addr) & 0x7) == 0)
{
// aligned write
- *((long *)addr) = val;
+ *((long*)addr) = val;
}
else
{
// unaligned write
- byte *valPtr = (byte *)&val;
+ byte* valPtr = (byte*)&val;
addr[0] = valPtr[0];
addr[1] = valPtr[1];
addr[2] = valPtr[2];
@@ -741,30 +749,30 @@ namespace System.Runtime.InteropServices
}
}
- public static void WriteInt64([MarshalAs(UnmanagedType.AsAny),In,Out] Object ptr, int ofs, long val)
+ public static void WriteInt64([MarshalAs(UnmanagedType.AsAny), In, Out] Object ptr, int ofs, long val)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10442
}
public static void WriteInt64(IntPtr ptr, long val)
{
WriteInt64(ptr, 0, val);
}
-
-
+
+
//====================================================================
// GetLastWin32Error
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetLastWin32Error();
-
+
//====================================================================
// SetLastWin32Error
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetLastWin32Error(int error);
-
+
//====================================================================
// GetHRForLastWin32Error
@@ -784,18 +792,18 @@ namespace System.Runtime.InteropServices
//====================================================================
public static void Prelink(MethodInfo m)
{
- if (m == null)
+ if (m == null)
throw new ArgumentNullException(nameof(m));
Contract.EndContractBlock();
RuntimeMethodInfo rmi = m as RuntimeMethodInfo;
if (rmi == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo);
InternalPrelink(rmi);
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
private static extern void InternalPrelink(IRuntimeMethodInfo m);
@@ -806,15 +814,15 @@ namespace System.Runtime.InteropServices
Contract.EndContractBlock();
MethodInfo[] mi = c.GetMethods();
- if (mi != null)
+ if (mi != null)
{
- for (int i = 0; i < mi.Length; i++)
+ for (int i = 0; i < mi.Length; i++)
{
Prelink(mi[i]);
}
}
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern int GetExceptionCode();
@@ -844,12 +852,12 @@ namespace System.Runtime.InteropServices
{
PtrToStructure(ptr, (object)structure);
}
-
+
//====================================================================
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [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;
@@ -858,12 +866,12 @@ namespace System.Runtime.InteropServices
throw new ArgumentNullException(nameof(structureType));
if (structureType.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(structureType));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(structureType));
RuntimeType rt = structureType.UnderlyingSystemType as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), nameof(structureType));
+ throw new ArgumentException(SR.Arg_MustBeType, nameof(structureType));
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -917,10 +925,10 @@ namespace System.Runtime.InteropServices
}
if (rtModule == null)
- throw new ArgumentNullException(nameof(m),Environment.GetResourceString("Argument_MustBeRuntimeModule"));
+ throw new ArgumentNullException(nameof(m), SR.Argument_MustBeRuntimeModule);
return GetHINSTANCE(rtModule.GetNativeHandle());
- }
+ }
[SuppressUnmanagedCodeSecurity]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity]
@@ -952,14 +960,14 @@ namespace System.Runtime.InteropServices
{
if (errorCode < 0)
return GetExceptionForHRInternal(errorCode, IntPtr.Zero);
- else
+ else
return null;
}
public static Exception GetExceptionForHR(int errorCode, IntPtr errorInfo)
{
if (errorCode < 0)
return GetExceptionForHRInternal(errorCode, errorInfo);
- else
+ else
return null;
}
@@ -987,7 +995,8 @@ namespace System.Runtime.InteropServices
IntPtr pNewMem = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, unchecked(numBytes));
- if (pNewMem == IntPtr.Zero) {
+ if (pNewMem == IntPtr.Zero)
+ {
throw new OutOfMemoryException();
}
return pNewMem;
@@ -997,11 +1006,13 @@ namespace System.Runtime.InteropServices
{
return AllocHGlobal((IntPtr)cb);
}
-
+
public static void FreeHGlobal(IntPtr hglobal)
{
- if (IsNotWin32Atom(hglobal)) {
- if (IntPtr.Zero != Win32Native.LocalFree(hglobal)) {
+ if (IsNotWin32Atom(hglobal))
+ {
+ if (IntPtr.Zero != Win32Native.LocalFree(hglobal))
+ {
ThrowExceptionForHR(GetHRForLastWin32Error());
}
}
@@ -1010,7 +1021,8 @@ namespace System.Runtime.InteropServices
public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb)
{
IntPtr pNewMem = Win32Native.LocalReAlloc(pv, cb, LMEM_MOVEABLE);
- if (pNewMem == IntPtr.Zero) {
+ if (pNewMem == IntPtr.Zero)
+ {
throw new OutOfMemoryException();
}
return pNewMem;
@@ -1036,18 +1048,18 @@ namespace System.Runtime.InteropServices
UIntPtr len = new UIntPtr((uint)nb);
IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
-
+
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
else
{
- s.ConvertToAnsi((byte *)hglobal, nb, false, false);
+ s.ConvertToAnsi((byte*)hglobal, nb, false, false);
return hglobal;
}
}
- }
+ }
unsafe public static IntPtr StringToHGlobalUni(String s)
{
@@ -1065,7 +1077,7 @@ namespace System.Runtime.InteropServices
UIntPtr len = new UIntPtr((uint)nb);
IntPtr hglobal = Win32Native.LocalAlloc_NoSafeHandle(LMEM_FIXED, len);
-
+
if (hglobal == IntPtr.Zero)
{
throw new OutOfMemoryException();
@@ -1105,7 +1117,7 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetHRForException_WinRT(Exception e);
- internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}");
+ internal static readonly Guid ManagedNameGuid = new Guid("{0F21F359-AB84-41E8-9A78-36D110E6D2F9}");
//====================================================================
// Given a managed object that wraps an ITypeInfo, return its name
@@ -1115,7 +1127,7 @@ namespace System.Runtime.InteropServices
if (typeInfo == null)
throw new ArgumentNullException(nameof(typeInfo));
Contract.EndContractBlock();
-
+
String strTypeLibName = null;
String strDocString = null;
int dwHelpContext = 0;
@@ -1162,7 +1174,7 @@ namespace System.Runtime.InteropServices
{
throw new PlatformNotSupportedException();
}
-
+
#if FEATURE_COMINTEROP
//====================================================================
@@ -1263,7 +1275,7 @@ namespace System.Runtime.InteropServices
// Overflow checking
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
-
+
IntPtr hglobal = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb));
if (hglobal == IntPtr.Zero)
@@ -1274,7 +1286,7 @@ namespace System.Runtime.InteropServices
{
fixed (char* firstChar = s)
{
- String.wstrcpy((char *)hglobal, firstChar, s.Length + 1);
+ String.wstrcpy((char*)hglobal, firstChar, s.Length + 1);
}
return hglobal;
}
@@ -1296,7 +1308,7 @@ namespace System.Runtime.InteropServices
if (nb < s.Length)
throw new ArgumentOutOfRangeException(nameof(s));
- IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb +1));
+ IntPtr pMem = Win32Native.CoTaskMemAlloc(new UIntPtr((uint)nb + 1));
if (pMem == IntPtr.Zero)
{
@@ -1316,8 +1328,8 @@ namespace System.Runtime.InteropServices
{
// Ansi platforms are no longer supported
return StringToCoTaskMemUni(s);
- }
-
+ }
+
unsafe public static IntPtr StringToCoTaskMemAnsi(String s)
{
if (s == null)
@@ -1340,7 +1352,7 @@ namespace System.Runtime.InteropServices
}
else
{
- s.ConvertToAnsi((byte *)hglobal, nb, false, false);
+ s.ConvertToAnsi((byte*)hglobal, nb, false, false);
return hglobal;
}
}
@@ -1348,7 +1360,8 @@ namespace System.Runtime.InteropServices
public static void FreeCoTaskMem(IntPtr ptr)
{
- if (IsNotWin32Atom(ptr)) {
+ if (IsNotWin32Atom(ptr))
+ {
Win32Native.CoTaskMemFree(ptr);
}
}
@@ -1403,7 +1416,7 @@ namespace System.Runtime.InteropServices
public static int ReleaseComObject(Object o)
{
__ComObject co = null;
-
+
// Make sure the obj is an __ComObject.
try
{
@@ -1411,16 +1424,16 @@ namespace System.Runtime.InteropServices
}
catch (InvalidCastException)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
+ throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
-
+
return co.ReleaseSelf();
- }
+ }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int InternalReleaseComObject(Object o);
-
+
//====================================================================
// release the COM component and zombie this object
// further usage of this Object might throw an exception
@@ -1440,13 +1453,13 @@ namespace System.Runtime.InteropServices
}
catch (InvalidCastException)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
+ throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
}
-
+
co.FinalReleaseSelf();
return 0;
- }
+ }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalFinalReleaseComObject(Object o);
@@ -1457,7 +1470,7 @@ namespace System.Runtime.InteropServices
//====================================================================
public static Object GetComObjectData(Object obj, Object key)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported);
}
//====================================================================
@@ -1468,7 +1481,7 @@ namespace System.Runtime.InteropServices
//====================================================================
public static bool SetComObjectData(Object obj, Object key, Object data)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported);
}
#if FEATURE_COMINTEROP
@@ -1482,13 +1495,13 @@ namespace System.Runtime.InteropServices
if (t == null)
throw new ArgumentNullException(nameof(t));
if (!t.IsCOMObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotComObject"), nameof(t));
+ throw new ArgumentException(SR.Argument_TypeNotComObject, nameof(t));
if (t.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
Contract.EndContractBlock();
if (t.IsWindowsRuntimeObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeIsWinRTType"), nameof(t));
+ throw new ArgumentException(SR.Argument_TypeIsWinRTType, nameof(t));
// Check for the null case.
if (o == null)
@@ -1496,9 +1509,9 @@ namespace System.Runtime.InteropServices
// Make sure the object is a COM object.
if (!o.GetType().IsCOMObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjNotComObject"), nameof(o));
+ throw new ArgumentException(SR.Argument_ObjNotComObject, nameof(o));
if (o.GetType().IsWindowsRuntimeObject)
- throw new ArgumentException(Environment.GetResourceString("Argument_ObjIsWinRTObject"), nameof(o));
+ throw new ArgumentException(SR.Argument_ObjIsWinRTObject, nameof(o));
// Check to see if the type of the object is the requested type.
if (o.GetType() == t)
@@ -1537,12 +1550,12 @@ namespace System.Runtime.InteropServices
// IUnknown Helpers
//====================================================================
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);
+ public static extern int /* HRESULT */ QueryInterface(IntPtr /* IUnknown */ pUnk, ref Guid iid, out IntPtr ppv);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk );
+ public static extern int /* ULONG */ AddRef(IntPtr /* IUnknown */ pUnk);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk );
+ public static extern int /* ULONG */ Release(IntPtr /* IUnknown */ pUnk);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void GetNativeVariantForObject(Object obj, /* VARIANT * */ IntPtr pDstNativeVariant);
@@ -1553,7 +1566,7 @@ namespace System.Runtime.InteropServices
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant );
+ public static extern Object GetObjectForNativeVariant(/* VARIANT * */ IntPtr pSrcNativeVariant);
public static T GetObjectForNativeVariant<T>(IntPtr pSrcNativeVariant)
{
@@ -1561,13 +1574,13 @@ namespace System.Runtime.InteropServices
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars );
+ public static extern Object[] GetObjectsForNativeVariants(/* VARIANT * */ IntPtr aSrcNativeVariant, int cVars);
public static T[] GetObjectsForNativeVariants<T>(IntPtr aSrcNativeVariant, int cVars)
{
object[] objects = GetObjectsForNativeVariants(aSrcNativeVariant, cVars);
T[] result = null;
-
+
if (objects != null)
{
result = new T[objects.Length];
@@ -1608,28 +1621,28 @@ namespace System.Runtime.InteropServices
if (type == null)
throw new ArgumentNullException(nameof(type));
if (type.IsImport)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeMustNotBeComImport"), nameof(type));
+ throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, nameof(type));
if (type.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(type));
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(type));
Contract.EndContractBlock();
IList<CustomAttributeData> cas = CustomAttributeData.GetCustomAttributes(type);
- for (int i = 0; i < cas.Count; i ++)
+ for (int i = 0; i < cas.Count; i++)
{
if (cas[i].Constructor.DeclaringType == typeof(ProgIdAttribute))
{
// Retrieve the PROGID string from the ProgIdAttribute.
IList<CustomAttributeTypedArgument> caConstructorArgs = cas[i].ConstructorArguments;
Debug.Assert(caConstructorArgs.Count == 1, "caConstructorArgs.Count == 1");
-
- CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
+
+ CustomAttributeTypedArgument progIdConstructorArg = caConstructorArgs[0];
Debug.Assert(progIdConstructorArg.ArgumentType == typeof(String), "progIdConstructorArg.ArgumentType == typeof(String)");
-
+
String strProgId = (String)progIdConstructorArg.Value;
-
+
if (strProgId == null)
- strProgId = String.Empty;
-
+ strProgId = String.Empty;
+
return strProgId;
}
}
@@ -1673,10 +1686,10 @@ namespace System.Runtime.InteropServices
//========================================================================
private static IntPtr LoadLicenseManager()
{
- Assembly sys = Assembly.Load("System, Version="+ ThisAssembly.Version +
+ Assembly sys = Assembly.Load("System, Version=" + ThisAssembly.Version +
", Culture=neutral, PublicKeyToken=" + AssemblyRef.EcmaPublicKeyToken);
Type t = sys.GetType("System.ComponentModel.LicenseManager");
- if (t == null || !t.IsVisible)
+ if (t == null || !t.IsVisible)
return IntPtr.Zero;
return t.TypeHandle.Value;
}
@@ -1705,20 +1718,20 @@ namespace System.Runtime.InteropServices
// Validate the parameters
if (ptr == IntPtr.Zero)
throw new ArgumentNullException(nameof(ptr));
-
+
if (t == null)
throw new ArgumentNullException(nameof(t));
Contract.EndContractBlock();
-
+
if ((t as RuntimeType) == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), nameof(t));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(t));
if (t.IsGenericType)
- throw new ArgumentException(Environment.GetResourceString("Argument_NeedNonGenericType"), nameof(t));
-
+ throw new ArgumentException(SR.Argument_NeedNonGenericType, nameof(t));
+
Type c = t.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"), nameof(t));
+ throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(t));
return GetDelegateForFunctionPointerInternal(ptr, t);
}
@@ -1748,21 +1761,25 @@ namespace System.Runtime.InteropServices
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d);
- public static IntPtr SecureStringToBSTR(SecureString s) {
- if( s == null) {
+ public static IntPtr SecureStringToBSTR(SecureString s)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
-
+
#if FEATURE_COMINTEROP
return s.MarshalToBSTR();
#else
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(); // https://github.com/dotnet/coreclr/issues/10443
#endif
}
- public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) {
- if( s == null) {
+ public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
@@ -1772,12 +1789,13 @@ namespace System.Runtime.InteropServices
public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s)
{
- if( s == null) {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.MarshalToString(globalAlloc: false, unicode: true);
+ return s.MarshalToString(globalAlloc: false, unicode: true);
}
#if FEATURE_COMINTEROP
@@ -1806,8 +1824,10 @@ namespace System.Runtime.InteropServices
FreeCoTaskMem(s);
}
- public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) {
- if( s == null) {
+ public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
@@ -1815,21 +1835,25 @@ namespace System.Runtime.InteropServices
return s.MarshalToString(globalAlloc: true, unicode: false);
}
- public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) {
- if( s == null) {
+ public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s)
+ {
+ if (s == null)
+ {
throw new ArgumentNullException(nameof(s));
}
Contract.EndContractBlock();
- return s.MarshalToString(globalAlloc: true, unicode: true);;
+ return s.MarshalToString(globalAlloc: true, unicode: true); ;
}
- public static void ZeroFreeGlobalAllocAnsi(IntPtr s) {
+ public static void ZeroFreeGlobalAllocAnsi(IntPtr s)
+ {
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenA(s)));
FreeHGlobal(s);
}
- public static void ZeroFreeGlobalAllocUnicode(IntPtr s) {
+ public static void ZeroFreeGlobalAllocUnicode(IntPtr s)
+ {
Win32Native.ZeroMemory(s, (UIntPtr)(Win32Native.lstrlenW(s) * 2));
FreeHGlobal(s);
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
index ec1014ecf8..6fe7574e26 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
@@ -11,29 +11,35 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+namespace System.Runtime.InteropServices
+{
[Serializable]
- public class MarshalDirectiveException : SystemException {
- public MarshalDirectiveException()
- : base(Environment.GetResourceString("Arg_MarshalDirectiveException")) {
- SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE);
+ public class MarshalDirectiveException : SystemException
+ {
+ public MarshalDirectiveException()
+ : base(SR.Arg_MarshalDirectiveException)
+ {
+ HResult = __HResults.COR_E_MARSHALDIRECTIVE;
}
-
- public MarshalDirectiveException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE);
+
+ public MarshalDirectiveException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_MARSHALDIRECTIVE;
}
-
- public MarshalDirectiveException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_MARSHALDIRECTIVE);
+
+ public MarshalDirectiveException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_MARSHALDIRECTIVE;
}
- protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs
index 706ef80019..d0ab0d9460 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeCallableAttribute.cs
@@ -13,7 +13,6 @@ using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices
{
-
[AttributeUsage(AttributeTargets.Method)]
public sealed class NativeCallableAttribute : Attribute
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
index 818034ee34..ddd15c2b95 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NativeMethods.cs
@@ -12,17 +12,18 @@
**/
#if FEATURE_COMINTEROP
-namespace System.Runtime.InteropServices {
-
- internal static class NativeMethods {
-
+namespace System.Runtime.InteropServices
+{
+ internal static class NativeMethods
+ {
[
System.Security.SuppressUnmanagedCodeSecurity,
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("00020400-0000-0000-C000-000000000046")
]
- internal interface IDispatch {
+ internal interface IDispatch
+ {
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
index ae974460f7..7b7c5efb90 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/NonPortable.cs
@@ -15,7 +15,7 @@ namespace System.Runtime.InteropServices
public static int AddRef(System.IntPtr pUnk)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool AreComObjectsAvailableForCleanup()
@@ -25,12 +25,12 @@ namespace System.Runtime.InteropServices
public static System.IntPtr CreateAggregatedObject(System.IntPtr pOuter, object o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object BindToMoniker(String monikerName)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void CleanupUnusedObjectsInCurrentContext()
@@ -40,42 +40,42 @@ namespace System.Runtime.InteropServices
public static System.IntPtr CreateAggregatedObject<T>(System.IntPtr pOuter, T o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object CreateWrapperOfType(object o, System.Type t)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static TWrapper CreateWrapperOfType<T, TWrapper>(T o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int FinalReleaseComObject(object o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetComInterfaceForObject(object o, System.Type T)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetComInterfaceForObject(object o, System.Type T, System.Runtime.InteropServices.CustomQueryInterfaceMode mode)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetComInterfaceForObject<T, TInterface>(T o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.IntPtr GetHINSTANCE(System.Reflection.Module m)
@@ -89,67 +89,67 @@ namespace System.Runtime.InteropServices
public static System.IntPtr GetIUnknownForObject(object o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject(object obj, System.IntPtr pDstNativeVariant)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void GetNativeVariantForObject<T>(T obj, System.IntPtr pDstNativeVariant)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static Object GetTypedObjectForIUnknown(System.IntPtr pUnk, System.Type t)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForIUnknown(System.IntPtr pUnk)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetObjectForNativeVariant(System.IntPtr pSrcNativeVariant)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T GetObjectForNativeVariant<T>(System.IntPtr pSrcNativeVariant)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object[] GetObjectsForNativeVariants(System.IntPtr aSrcNativeVariant, int cVars)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static T[] GetObjectsForNativeVariants<T>(System.IntPtr aSrcNativeVariant, int cVars)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int GetStartComSlot(System.Type t)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.Type GetTypeFromCLSID(System.Guid clsid)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static string GetTypeInfoName(System.Runtime.InteropServices.ComTypes.ITypeInfo typeInfo)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static object GetUniqueObjectForIUnknown(System.IntPtr unknown)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static bool IsComObject(object o)
@@ -159,22 +159,22 @@ namespace System.Runtime.InteropServices
public static int QueryInterface(System.IntPtr pUnk, ref System.Guid iid, out System.IntPtr ppv)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int Release(System.IntPtr pUnk)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static int ReleaseComObject(object o)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static void ZeroFreeBSTR(System.IntPtr s)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
@@ -182,14 +182,14 @@ namespace System.Runtime.InteropServices
{
public DispatchWrapper(object obj)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public object WrappedObject
{
get
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
@@ -198,12 +198,12 @@ namespace System.Runtime.InteropServices
{
public static void Combine(object rcw, System.Guid iid, int dispid, System.Delegate d)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
public static System.Delegate Remove(object rcw, System.Guid iid, int dispid, System.Delegate d)
{
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_ComInterop);
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs
index f47165544a..ed289fd14b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/PInvokeMap.cs
@@ -9,40 +9,42 @@
// values are defined in CorHdr.h.
//
//
-namespace System.Runtime.InteropServices {
- using System.Runtime.InteropServices;
- using System;
-
+
+using System.Runtime.InteropServices;
+using System;
+
+namespace System.Runtime.InteropServices
+{
// This Enum matchs the CorPinvokeMap defined in CorHdr.h
[Serializable]
internal enum PInvokeMap
{
- NoMangle = 0x0001, // Pinvoke is to use the member name as specified.
- CharSetMask = 0x0006, // Heuristic used in data type & name mapping.
- CharSetNotSpec = 0x0000,
- CharSetAnsi = 0x0002,
- CharSetUnicode = 0x0004,
- CharSetAuto = 0x0006,
-
- PinvokeOLE = 0x0020, // Heuristic: pinvoke will return hresult, with return value becoming the retval param. Not relevant for fields.
- SupportsLastError = 0x0040, // Information about target function. Not relevant for fields.
+ NoMangle = 0x0001, // Pinvoke is to use the member name as specified.
+ CharSetMask = 0x0006, // Heuristic used in data type & name mapping.
+ CharSetNotSpec = 0x0000,
+ CharSetAnsi = 0x0002,
+ CharSetUnicode = 0x0004,
+ CharSetAuto = 0x0006,
+
+ PinvokeOLE = 0x0020, // Heuristic: pinvoke will return hresult, with return value becoming the retval param. Not relevant for fields.
+ SupportsLastError = 0x0040, // Information about target function. Not relevant for fields.
+
+ BestFitMask = 0x0030,
+ BestFitEnabled = 0x0010,
+ BestFitDisabled = 0x0020,
+ BestFitUseAsm = 0x0030,
+
+ ThrowOnUnmappableCharMask = 0x3000,
+ ThrowOnUnmappableCharEnabled = 0x1000,
+ ThrowOnUnmappableCharDisabled = 0x2000,
+ ThrowOnUnmappableCharUseAsm = 0x3000,
- BestFitMask = 0x0030,
- BestFitEnabled = 0x0010,
- BestFitDisabled = 0x0020,
- BestFitUseAsm = 0x0030,
-
- ThrowOnUnmappableCharMask = 0x3000,
- ThrowOnUnmappableCharEnabled = 0x1000,
- ThrowOnUnmappableCharDisabled = 0x2000,
- ThrowOnUnmappableCharUseAsm = 0x3000,
-
// None of the calling convention flags is relevant for fields.
- CallConvMask = 0x0700,
- CallConvWinapi = 0x0100, // Pinvoke will use native callconv appropriate to target windows platform.
- CallConvCdecl = 0x0200,
- CallConvStdcall = 0x0300,
- CallConvThiscall = 0x0400, // In M9, pinvoke will raise exception.
- CallConvFastcall = 0x0500,
+ CallConvMask = 0x0700,
+ CallConvWinapi = 0x0100, // Pinvoke will use native callconv appropriate to target windows platform.
+ CallConvCdecl = 0x0200,
+ CallConvStdcall = 0x0300,
+ CallConvThiscall = 0x0400, // In M9, pinvoke will raise exception.
+ CallConvFastcall = 0x0500,
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
index 28abe0cb3b..e11e3a437d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/RuntimeEnvironment.cs
@@ -24,18 +24,14 @@ using StackCrawlMark = System.Threading.StackCrawlMark;
namespace System.Runtime.InteropServices
{
- static internal class RuntimeEnvironment {
-
+ static internal class RuntimeEnvironment
+ {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern String GetModuleFileName();
- [MethodImpl (MethodImplOptions.NoInlining)]
public static String GetSystemVersion()
{
return Assembly.GetExecutingAssembly().ImageRuntimeVersion;
}
-
-#if FEATURE_COMINTEROP
-#endif // FEATURE_COMINTEROP
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
index 72b98738ae..5595fadc43 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
@@ -11,30 +11,37 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System.Runtime.InteropServices;
- using System;
- using System.Runtime.Serialization;
+using System.Runtime.InteropServices;
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Runtime.InteropServices
+{
// Exception for Structured Exception Handler exceptions.
//
[Serializable]
- public class SEHException : ExternalException {
- public SEHException()
- : base() {
- SetErrorCode(__HResults.E_FAIL);
+ public class SEHException : ExternalException
+ {
+ public SEHException()
+ : base()
+ {
+ HResult = __HResults.E_FAIL;
}
-
- public SEHException(String message)
- : base(message) {
- SetErrorCode(__HResults.E_FAIL);
+
+ public SEHException(String message)
+ : base(message)
+ {
+ HResult = __HResults.E_FAIL;
}
-
- public SEHException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.E_FAIL);
+
+ public SEHException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.E_FAIL;
}
-
- protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context) {
+
+ protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
}
// Exceptions can be resumable, meaning a filtered exception
@@ -48,6 +55,6 @@ namespace System.Runtime.InteropServices {
public virtual bool CanResume()
{
return false;
- }
+ }
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
index 12bf7e7e47..f39f1f3a41 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
@@ -10,31 +10,35 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+namespace System.Runtime.InteropServices
+{
[Serializable]
- public class SafeArrayRankMismatchException : SystemException {
- public SafeArrayRankMismatchException()
- : base(Environment.GetResourceString("Arg_SafeArrayRankMismatchException")) {
- SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH);
+ public class SafeArrayRankMismatchException : SystemException
+ {
+ public SafeArrayRankMismatchException()
+ : base(SR.Arg_SafeArrayRankMismatchException)
+ {
+ HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH;
}
-
- public SafeArrayRankMismatchException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH);
- }
-
- public SafeArrayRankMismatchException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_SAFEARRAYRANKMISMATCH);
+
+ public SafeArrayRankMismatchException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH;
}
- protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public SafeArrayRankMismatchException(String message, Exception inner)
+ : base(message, inner)
+ {
+ 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 050772af2c..2283263422 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
@@ -11,31 +11,35 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
- using System;
- using System.Runtime.Serialization;
+using System;
+using System.Runtime.Serialization;
+namespace System.Runtime.InteropServices
+{
[Serializable]
- public class SafeArrayTypeMismatchException : SystemException {
- public SafeArrayTypeMismatchException()
- : base(Environment.GetResourceString("Arg_SafeArrayTypeMismatchException")) {
- SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH);
+ public class SafeArrayTypeMismatchException : SystemException
+ {
+ public SafeArrayTypeMismatchException()
+ : base(SR.Arg_SafeArrayTypeMismatchException)
+ {
+ HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH;
}
-
- public SafeArrayTypeMismatchException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH);
- }
-
- public SafeArrayTypeMismatchException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_SAFEARRAYTYPEMISMATCH);
+
+ public SafeArrayTypeMismatchException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH;
}
- protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ public SafeArrayTypeMismatchException(String message, Exception inner)
+ : base(message, inner)
+ {
+ 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 ee5c3d8e87..aba25e94a3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
@@ -66,8 +66,6 @@
// assignments in a static class constructor are under a lock implicitly.
-namespace System.Runtime.InteropServices
-{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -77,12 +75,13 @@ using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-
+namespace System.Runtime.InteropServices
+{
public abstract unsafe class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid
{
// Steal UIntPtr.MaxValue as our uninitialized value.
- private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
- ((UIntPtr) UInt32.MaxValue) : ((UIntPtr) UInt64.MaxValue);
+ private static readonly UIntPtr Uninitialized = (UIntPtr.Size == 4) ?
+ ((UIntPtr)UInt32.MaxValue) : ((UIntPtr)UInt64.MaxValue);
private UIntPtr _numBytes;
@@ -100,15 +99,15 @@ using System.Diagnostics.Contracts;
public void Initialize(ulong numBytes)
{
if (numBytes < 0)
- throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum);
if (IntPtr.Size == 4 && numBytes > UInt32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_AddressSpace);
Contract.EndContractBlock();
if (numBytes >= (ulong)Uninitialized)
- throw new ArgumentOutOfRangeException(nameof(numBytes), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
+ throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_UIntPtrMax);
- _numBytes = (UIntPtr) numBytes;
+ _numBytes = (UIntPtr)numBytes;
}
/// <summary>
@@ -119,18 +118,18 @@ using System.Diagnostics.Contracts;
public void Initialize(uint numElements, uint sizeOfEachElement)
{
if (numElements < 0)
- throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_NeedNonNegNum);
if (sizeOfEachElement < 0)
- throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(sizeOfEachElement), SR.ArgumentOutOfRange_NeedNonNegNum);
if (IntPtr.Size == 4 && numElements * sizeOfEachElement > UInt32.MaxValue)
- throw new ArgumentOutOfRangeException("numBytes", Environment.GetResourceString("ArgumentOutOfRange_AddressSpace"));
+ throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace);
Contract.EndContractBlock();
if (numElements * sizeOfEachElement >= (ulong)Uninitialized)
- throw new ArgumentOutOfRangeException(nameof(numElements), Environment.GetResourceString("ArgumentOutOfRange_UIntPtrMax-1"));
+ throw new ArgumentOutOfRangeException(nameof(numElements), SR.ArgumentOutOfRange_UIntPtrMax);
- _numBytes = checked((UIntPtr) (numElements * sizeOfEachElement));
+ _numBytes = checked((UIntPtr)(numElements * sizeOfEachElement));
}
/// <summary>
@@ -209,7 +208,8 @@ using System.Diagnostics.Contracts;
/// may have to consider alignment.</param>
/// <returns>An instance of T read from memory.</returns>
[CLSCompliant(false)]
- public T Read<T>(ulong byteOffset) where T : struct {
+ public T Read<T>(ulong byteOffset) where T : struct
+ {
if (_numBytes == Uninitialized)
throw NotInitialized();
@@ -240,13 +240,13 @@ using System.Diagnostics.Contracts;
where T : struct
{
if (array == null)
- throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (_numBytes == Uninitialized)
@@ -282,7 +282,8 @@ using System.Diagnostics.Contracts;
/// may have to consider alignment.</param>
/// <param name="value">The value type to write to memory.</param>
[CLSCompliant(false)]
- public void Write<T>(ulong byteOffset, T value) where T : struct {
+ public void Write<T>(ulong byteOffset, T value) where T : struct
+ {
if (_numBytes == Uninitialized)
throw NotInitialized();
@@ -310,13 +311,13 @@ using System.Diagnostics.Contracts;
where T : struct
{
if (array == null)
- throw new ArgumentNullException(nameof(array), Environment.GetResourceString("ArgumentNull_Buffer"));
+ throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer);
if (index < 0)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Length - index < count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
+ throw new ArgumentException(SR.Argument_InvalidOffLen);
Contract.EndContractBlock();
if (_numBytes == Uninitialized)
@@ -326,7 +327,7 @@ using System.Diagnostics.Contracts;
uint alignedSizeofT = Marshal.AlignedSizeOf<T>();
byte* ptr = (byte*)handle + byteOffset;
SpaceCheck(ptr, checked((ulong)(alignedSizeofT * count)));
-
+
bool mustCallRelease = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
@@ -347,35 +348,37 @@ using System.Diagnostics.Contracts;
/// Returns the number of bytes in the memory region.
/// </summary>
[CLSCompliant(false)]
- public ulong ByteLength {
- get {
+ public ulong ByteLength
+ {
+ get
+ {
if (_numBytes == Uninitialized)
throw NotInitialized();
- return (ulong) _numBytes;
+ return (ulong)_numBytes;
}
}
/* No indexer. The perf would be misleadingly bad. People should use
* AcquirePointer and ReleasePointer instead. */
-
+
private void SpaceCheck(byte* ptr, ulong sizeInBytes)
{
if ((ulong)_numBytes < sizeInBytes)
NotEnoughRoom();
- if ((ulong)(ptr - (byte*) handle) > ((ulong)_numBytes) - sizeInBytes)
+ if ((ulong)(ptr - (byte*)handle) > ((ulong)_numBytes) - sizeInBytes)
NotEnoughRoom();
}
private static void NotEnoughRoom()
{
- throw new ArgumentException(Environment.GetResourceString("Arg_BufferTooSmall"));
+ throw new ArgumentException(SR.Arg_BufferTooSmall);
}
private static InvalidOperationException NotInitialized()
{
Debug.Assert(false, "Uninitialized SafeBuffer! Someone needs to call Initialize before using this instance!");
- return new InvalidOperationException(Environment.GetResourceString("InvalidOperation_MustCallInitialize"));
+ return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize);
}
// FCALL limitations mean we can't have generic FCALL methods. However, we can pass
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
index 591caa2877..6654ec9b00 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeHandle.cs
@@ -14,276 +14,281 @@
**
===========================================================*/
-namespace System.Runtime.InteropServices {
-
-using System;
-using System.Reflection;
-using System.Threading;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.IO;
-using System.Runtime.ConstrainedExecution;
-using System.Runtime.Versioning;
-
-/*
- Problems addressed by the SafeHandle class:
- 1) Critical finalization - ensure we never leak OS resources in SQL. Done
- without running truly arbitrary & unbounded amounts of managed code.
- 2) Reduced graph promotion - during finalization, keep object graph small
- 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race conditions (HandleRef)
- 4) Elimination of security race conditions w/ explicit calls to Close (HandleProtector)
- 5) Enforcement of the above via the type system - Don't use IntPtr anymore.
- 6) Allows the handle lifetime to be controlled externally via a boolean.
-
- Subclasses of SafeHandle will implement the ReleaseHandle abstract method
- used to execute any code required to free the handle. This method will be
- prepared as a constrained execution region at instance construction time
- (along with all the methods in its statically determinable call graph). This
- implies that we won't get any inconvenient jit allocation errors or rude
- thread abort interrupts while releasing the handle but the user must still
- write careful code to avoid injecting fault paths of their own (see the CER
- spec for more details). In particular, any sub-methods you call should be
- decorated with a reliability contract of the appropriate level. In most cases
- this should be:
- ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)
- Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity
- attribute to avoid a runtime security check that can also inject failures
- (even if the check is guaranteed to pass).
-
- The GC will run ReleaseHandle methods after any normal finalizers have been
- run for objects that were collected at the same time. This ensures classes
- like FileStream can run a normal finalizer to flush out existing buffered
- data. This is key - it means adding this class to a class like FileStream does
- not alter our current semantics w.r.t. finalization today.
-
- Subclasses must also implement the IsInvalid property so that the
- infrastructure can tell when critical finalization is actually required.
- Again, this method is prepared ahead of time. It's envisioned that direct
- subclasses of SafeHandle will provide an IsInvalid implementation that suits
- the general type of handle they support (null is invalid, -1 is invalid etc.)
- and then these classes will be further derived for specific safe handle types.
-
- Most classes using SafeHandle should not provide a finalizer. If they do
- need to do so (ie, for flushing out file buffers, needing to write some data
- back into memory, etc), then they can provide a finalizer that will be
- guaranteed to run before the SafeHandle's critical finalizer.
-
- Note that SafeHandle's ReleaseHandle is called from a constrained execution
- region, and is eagerly prepared before we create your class. This means you
- should only call methods with an appropriate reliability contract from your
- ReleaseHandle method.
-
- Subclasses are expected to be written as follows (note that
- SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods
- invoked as part of ReleaseHandle, in order to switch the security check from
- runtime to jit time and thus remove a possible failure path from the
- invocation of the method):
-
- internal sealed MySafeHandleSubclass : SafeHandle {
- // Called by P/Invoke when returning SafeHandles
- private MySafeHandleSubclass() : base(IntPtr.Zero, true)
- {
+namespace System.Runtime.InteropServices
+{
+ using System;
+ using System.Reflection;
+ using System.Threading;
+ using System.Runtime;
+ using System.Runtime.CompilerServices;
+ using System.IO;
+ using System.Runtime.ConstrainedExecution;
+ using System.Runtime.Versioning;
+
+ /*
+ Problems addressed by the SafeHandle class:
+ 1) Critical finalization - ensure we never leak OS resources in SQL. Done
+ without running truly arbitrary & unbounded amounts of managed code.
+ 2) Reduced graph promotion - during finalization, keep object graph small
+ 3) GC.KeepAlive behavior - P/Invoke vs. finalizer thread race conditions (HandleRef)
+ 4) Elimination of security race conditions w/ explicit calls to Close (HandleProtector)
+ 5) Enforcement of the above via the type system - Don't use IntPtr anymore.
+ 6) Allows the handle lifetime to be controlled externally via a boolean.
+
+ Subclasses of SafeHandle will implement the ReleaseHandle abstract method
+ used to execute any code required to free the handle. This method will be
+ prepared as a constrained execution region at instance construction time
+ (along with all the methods in its statically determinable call graph). This
+ implies that we won't get any inconvenient jit allocation errors or rude
+ thread abort interrupts while releasing the handle but the user must still
+ write careful code to avoid injecting fault paths of their own (see the CER
+ spec for more details). In particular, any sub-methods you call should be
+ decorated with a reliability contract of the appropriate level. In most cases
+ this should be:
+ ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)
+ Also, any P/Invoke methods should use the SuppressUnmanagedCodeSecurity
+ attribute to avoid a runtime security check that can also inject failures
+ (even if the check is guaranteed to pass).
+
+ The GC will run ReleaseHandle methods after any normal finalizers have been
+ run for objects that were collected at the same time. This ensures classes
+ like FileStream can run a normal finalizer to flush out existing buffered
+ data. This is key - it means adding this class to a class like FileStream does
+ not alter our current semantics w.r.t. finalization today.
+
+ Subclasses must also implement the IsInvalid property so that the
+ infrastructure can tell when critical finalization is actually required.
+ Again, this method is prepared ahead of time. It's envisioned that direct
+ subclasses of SafeHandle will provide an IsInvalid implementation that suits
+ the general type of handle they support (null is invalid, -1 is invalid etc.)
+ and then these classes will be further derived for specific safe handle types.
+
+ Most classes using SafeHandle should not provide a finalizer. If they do
+ need to do so (ie, for flushing out file buffers, needing to write some data
+ back into memory, etc), then they can provide a finalizer that will be
+ guaranteed to run before the SafeHandle's critical finalizer.
+
+ Note that SafeHandle's ReleaseHandle is called from a constrained execution
+ region, and is eagerly prepared before we create your class. This means you
+ should only call methods with an appropriate reliability contract from your
+ ReleaseHandle method.
+
+ Subclasses are expected to be written as follows (note that
+ SuppressUnmanagedCodeSecurity should always be used on any P/Invoke methods
+ invoked as part of ReleaseHandle, in order to switch the security check from
+ runtime to jit time and thus remove a possible failure path from the
+ invocation of the method):
+
+ internal sealed MySafeHandleSubclass : SafeHandle {
+ // Called by P/Invoke when returning SafeHandles
+ private MySafeHandleSubclass() : base(IntPtr.Zero, true)
+ {
+ }
+
+ // If & only if you need to support user-supplied handles
+ internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
+ {
+ SetHandle(preexistingHandle);
+ }
+
+ // Do not provide a finalizer - SafeHandle's critical finalizer will
+ // call ReleaseHandle for you.
+
+ public override bool IsInvalid {
+ get { return handle == IntPtr.Zero; }
+ }
+
+ override protected bool ReleaseHandle()
+ {
+ return MyNativeMethods.CloseHandle(handle);
+ }
}
- // If & only if you need to support user-supplied handles
- internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
- {
- SetHandle(preexistingHandle);
- }
+ Then elsewhere to create one of these SafeHandles, define a method
+ with the following type of signature (CreateFile follows this model).
+ Note that when returning a SafeHandle like this, P/Invoke will call your
+ class's default constructor. Also, you probably want to define CloseHandle
+ somewhere, and remember to apply a reliability contract to it.
- // Do not provide a finalizer - SafeHandle's critical finalizer will
- // call ReleaseHandle for you.
+ [SuppressUnmanagedCodeSecurity]
+ internal static class MyNativeMethods {
+ [DllImport("kernel32")]
+ private static extern MySafeHandleSubclass CreateHandle(int someState);
- public override bool IsInvalid {
- get { return handle == IntPtr.Zero; }
+ [DllImport("kernel32", SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ private static extern bool CloseHandle(IntPtr handle);
}
- override protected bool ReleaseHandle()
- {
- return MyNativeMethods.CloseHandle(handle);
- }
- }
-
- Then elsewhere to create one of these SafeHandles, define a method
- with the following type of signature (CreateFile follows this model).
- Note that when returning a SafeHandle like this, P/Invoke will call your
- class's default constructor. Also, you probably want to define CloseHandle
- somewhere, and remember to apply a reliability contract to it.
-
- [SuppressUnmanagedCodeSecurity]
- internal static class MyNativeMethods {
- [DllImport("kernel32")]
- private static extern MySafeHandleSubclass CreateHandle(int someState);
-
- [DllImport("kernel32", SetLastError=true), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
- private static extern bool CloseHandle(IntPtr handle);
- }
-
- Drawbacks with this implementation:
- 1) Requires some magic to run the critical finalizer.
- 2) Requires more memory than just an IntPtr.
- 3) If you use DangerousAddRef and forget to call DangerousRelease, you can leak a SafeHandle. Use CER's & don't do that.
- */
-
-
-// This class should not be serializable - it's a handle. We require unmanaged
-// code permission to subclass SafeHandle 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.
-public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
-{
- // ! Do not add or rearrange fields as the EE depends on this layout.
- //------------------------------------------------------------------
+ Drawbacks with this implementation:
+ 1) Requires some magic to run the critical finalizer.
+ 2) Requires more memory than just an IntPtr.
+ 3) If you use DangerousAddRef and forget to call DangerousRelease, you can leak a SafeHandle. Use CER's & don't do that.
+ */
+
+
+ // This class should not be serializable - it's a handle. We require unmanaged
+ // code permission to subclass SafeHandle 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.
+ public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
+ {
+ // ! Do not add or rearrange fields as the EE depends on this layout.
+ //------------------------------------------------------------------
#if DEBUG
- // FxCop thinks this field is marshaled and so it raises a CA2101 error unless
- // we specify this. In practice this is never presented to Win32.
- [MarshalAs(UnmanagedType.LPWStr)]
- private String _stackTrace; // Where we allocated this SafeHandle.
+ // FxCop thinks this field is marshaled and so it raises a CA2101 error unless
+ // we specify this. In practice this is never presented to Win32.
+ [MarshalAs(UnmanagedType.LPWStr)]
+ private String _stackTrace; // Where we allocated this SafeHandle.
#endif
- protected IntPtr handle; // this must be protected so derived classes can use out params.
- private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them).
- private bool _ownsHandle; // Whether we can release this handle.
+ protected IntPtr handle; // this must be protected so derived classes can use out params.
+ private int _state; // Combined ref count and closed/disposed flags (so we can atomically modify them).
+ private bool _ownsHandle; // Whether we can release this handle.
#pragma warning disable 414
- private bool _fullyInitialized; // Whether constructor completed.
+ private bool _fullyInitialized; // Whether constructor completed.
#pragma warning restore 414
- // Creates a SafeHandle class. Users must then set the Handle property.
- // To prevent the SafeHandle from being freed, write a subclass that
- // doesn't define a finalizer.
- protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
- {
- handle = invalidHandleValue;
- _state = 4; // Ref count 1 and not closed or disposed.
- _ownsHandle = ownsHandle;
+ // Creates a SafeHandle class. Users must then set the Handle property.
+ // To prevent the SafeHandle from being freed, write a subclass that
+ // doesn't define a finalizer.
+ protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle)
+ {
+ handle = invalidHandleValue;
+ _state = 4; // Ref count 1 and not closed or disposed.
+ _ownsHandle = ownsHandle;
- if (!ownsHandle)
- GC.SuppressFinalize(this);
+ if (!ownsHandle)
+ GC.SuppressFinalize(this);
#if DEBUG
- if (BCLDebug.SafeHandleStackTracesEnabled)
- _stackTrace = Environment.GetStackTrace(null, false);
- else
- _stackTrace = "For a stack trace showing who allocated this SafeHandle, set SafeHandleStackTraces to 1 and rerun your app.";
+ if (BCLDebug.SafeHandleStackTracesEnabled)
+ _stackTrace = Environment.GetStackTrace(null, false);
+ else
+ _stackTrace = "For a stack trace showing who allocated this SafeHandle, set SafeHandleStackTraces to 1 and rerun your app.";
#endif
- // Set this last to prevent SafeHandle's finalizer from freeing an
- // invalid handle. This means we don't have to worry about
- // ThreadAbortExceptions interrupting this constructor or the managed
- // constructors on subclasses that call this constructor.
- _fullyInitialized = true;
- }
-
- // Migrating InheritanceDemands requires this default ctor, so we can mark it critical
- protected SafeHandle()
- {
- BCLDebug.Assert(false, "SafeHandle's protected default ctor should never be used!");
- throw new NotImplementedException();
- }
-
- ~SafeHandle()
- {
- Dispose(false);
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- extern void InternalFinalize();
-
- protected void SetHandle(IntPtr handle) {
- this.handle = handle;
+ // Set this last to prevent SafeHandle's finalizer from freeing an
+ // invalid handle. This means we don't have to worry about
+ // ThreadAbortExceptions interrupting this constructor or the managed
+ // constructors on subclasses that call this constructor.
+ _fullyInitialized = true;
+ }
+
+ // Migrating InheritanceDemands requires this default ctor, so we can mark it critical
+ protected SafeHandle()
+ {
+ BCLDebug.Assert(false, "SafeHandle's protected default ctor should never be used!");
+ throw new NotImplementedException();
+ }
+
+ ~SafeHandle()
+ {
+ Dispose(false);
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern void InternalFinalize();
+
+ protected void SetHandle(IntPtr handle)
+ {
+ this.handle = handle;
+ }
+
+ // This method is necessary for getting an IntPtr out of a SafeHandle.
+ // Used to tell whether a call to create the handle succeeded by comparing
+ // the handle against a known invalid value, and for backwards
+ // compatibility to support the handle properties returning IntPtrs on
+ // many of our Framework classes.
+ // Note that this method is dangerous for two reasons:
+ // 1) If the handle has been marked invalid with SetHandleasInvalid,
+ // DangerousGetHandle will still return the original handle value.
+ // 2) The handle returned may be recycled at any point. At best this means
+ // the handle might stop working suddenly. At worst, if the handle or
+ // the resource the handle represents is exposed to untrusted code in
+ // any way, this can lead to a handle recycling security attack (i.e. an
+ // untrusted caller can query data on the handle you've just returned
+ // and get back information for an entirely unrelated resource).
+ public IntPtr DangerousGetHandle()
+ {
+ return handle;
+ }
+
+ public bool IsClosed
+ {
+ get { return (_state & 1) == 1; }
+ }
+
+ public abstract bool IsInvalid
+ {
+ get;
+ }
+
+ public void Close()
+ {
+ Dispose(true);
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ }
+
+ protected virtual void Dispose(bool disposing)
+ {
+ if (disposing)
+ InternalDispose();
+ else
+ InternalFinalize();
+ }
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern void InternalDispose();
+
+ // This should only be called for cases when you know for a fact that
+ // your handle is invalid and you want to record that information.
+ // An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
+ // This method will normally leak handles!
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public extern void SetHandleAsInvalid();
+
+ // Implement this abstract method in your derived class to specify how to
+ // free the handle. Be careful not write any code that's subject to faults
+ // in this method (the runtime will prepare the infrastructure for you so
+ // that no jit allocations etc. will occur, but don't allocate memory unless
+ // you can deal with the failure and still free the handle).
+ // The boolean returned should be true for success and false if the runtime
+ // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that
+ // MDA is enabled.
+ protected abstract bool ReleaseHandle();
+
+ // Add a reason why this handle should not be relinquished (i.e. have
+ // ReleaseHandle called on it). This method has dangerous in the name since
+ // it must always be used carefully (e.g. called within a CER) to avoid
+ // leakage of the handle. It returns a boolean indicating whether the
+ // increment was actually performed to make it easy for program logic to
+ // back out in failure cases (i.e. is a call to DangerousRelease needed).
+ // It is passed back via a ref parameter rather than as a direct return so
+ // that callers need not worry about the atomicity of calling the routine
+ // and assigning the return value to a variable (the variable should be
+ // explicitly set to false prior to the call). The only failure cases are
+ // when the method is interrupted prior to processing by a thread abort or
+ // when the handle has already been (or is in the process of being)
+ // released.
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public extern void DangerousAddRef(ref bool success);
+
+ // Partner to DangerousAddRef. This should always be successful when used in
+ // a correct manner (i.e. matching a successful DangerousAddRef and called
+ // from a region such as a CER where a thread abort cannot interrupt
+ // processing). In the same way that unbalanced DangerousAddRef calls can
+ // cause resource leakage, unbalanced DangerousRelease calls may cause
+ // invalid handle states to become visible to other threads. This
+ // constitutes a potential security hole (via handle recycling) as well as a
+ // correctness problem -- so don't ever expose Dangerous* calls out to
+ // untrusted code.
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public extern void DangerousRelease();
}
-
- // This method is necessary for getting an IntPtr out of a SafeHandle.
- // Used to tell whether a call to create the handle succeeded by comparing
- // the handle against a known invalid value, and for backwards
- // compatibility to support the handle properties returning IntPtrs on
- // many of our Framework classes.
- // Note that this method is dangerous for two reasons:
- // 1) If the handle has been marked invalid with SetHandleasInvalid,
- // DangerousGetHandle will still return the original handle value.
- // 2) The handle returned may be recycled at any point. At best this means
- // the handle might stop working suddenly. At worst, if the handle or
- // the resource the handle represents is exposed to untrusted code in
- // any way, this can lead to a handle recycling security attack (i.e. an
- // untrusted caller can query data on the handle you've just returned
- // and get back information for an entirely unrelated resource).
- public IntPtr DangerousGetHandle()
- {
- return handle;
- }
-
- public bool IsClosed {
- get { return (_state & 1) == 1; }
- }
-
- public abstract bool IsInvalid {
- get;
- }
-
- public void Close() {
- Dispose(true);
- }
-
- public void Dispose() {
- Dispose(true);
- }
-
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- InternalDispose();
- else
- InternalFinalize();
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern void InternalDispose();
-
- // This should only be called for cases when you know for a fact that
- // your handle is invalid and you want to record that information.
- // An example is calling a syscall and getting back ERROR_INVALID_HANDLE.
- // This method will normally leak handles!
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern void SetHandleAsInvalid();
-
- // Implement this abstract method in your derived class to specify how to
- // free the handle. Be careful not write any code that's subject to faults
- // in this method (the runtime will prepare the infrastructure for you so
- // that no jit allocations etc. will occur, but don't allocate memory unless
- // you can deal with the failure and still free the handle).
- // The boolean returned should be true for success and false if the runtime
- // should fire a SafeHandleCriticalFailure MDA (CustomerDebugProbe) if that
- // MDA is enabled.
- protected abstract bool ReleaseHandle();
-
- // Add a reason why this handle should not be relinquished (i.e. have
- // ReleaseHandle called on it). This method has dangerous in the name since
- // it must always be used carefully (e.g. called within a CER) to avoid
- // leakage of the handle. It returns a boolean indicating whether the
- // increment was actually performed to make it easy for program logic to
- // back out in failure cases (i.e. is a call to DangerousRelease needed).
- // It is passed back via a ref parameter rather than as a direct return so
- // that callers need not worry about the atomicity of calling the routine
- // and assigning the return value to a variable (the variable should be
- // explicitly set to false prior to the call). The only failure cases are
- // when the method is interrupted prior to processing by a thread abort or
- // when the handle has already been (or is in the process of being)
- // released.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern void DangerousAddRef(ref bool success);
-
- // Partner to DangerousAddRef. This should always be successful when used in
- // a correct manner (i.e. matching a successful DangerousAddRef and called
- // from a region such as a CER where a thread abort cannot interrupt
- // processing). In the same way that unbalanced DangerousAddRef calls can
- // cause resource leakage, unbalanced DangerousRelease calls may cause
- // invalid handle states to become visible to other threads. This
- // constitutes a potential security hole (via handle recycling) as well as a
- // correctness problem -- so don't ever expose Dangerous* calls out to
- // untrusted code.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern void DangerousRelease();
-}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
index 1f70108a02..c758ae1b4f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/UnknownWrapper.cs
@@ -11,10 +11,11 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
+using System;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
public sealed class UnknownWrapper
{
@@ -23,9 +24,9 @@ namespace System.Runtime.InteropServices {
m_WrappedObject = obj;
}
- public Object WrappedObject
+ public Object WrappedObject
{
- get
+ get
{
return m_WrappedObject;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs
index 3f5120af39..50689e08f8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/VariantWrapper.cs
@@ -11,10 +11,11 @@
**
=============================================================================*/
-namespace System.Runtime.InteropServices {
-
- using System;
+using System;
+
+namespace System.Runtime.InteropServices
+{
[Serializable]
public sealed class VariantWrapper
@@ -24,9 +25,9 @@ namespace System.Runtime.InteropServices {
m_WrappedObject = obj;
}
- public Object WrappedObject
+ public Object WrappedObject
{
- get
+ get
{
return m_WrappedObject;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
index 7fa2420530..d78aae216b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/Attributes.cs
@@ -90,14 +90,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)]
public sealed class ReadOnlyArrayAttribute : Attribute
{
- public ReadOnlyArrayAttribute() {}
+ public ReadOnlyArrayAttribute() { }
}
// Applies to write-only array parameters
[AttributeUsage(AttributeTargets.Parameter, Inherited = false, AllowMultiple = false)]
public sealed class WriteOnlyArrayAttribute : Attribute
{
- public WriteOnlyArrayAttribute() {}
+ public WriteOnlyArrayAttribute() { }
}
@@ -119,5 +119,4 @@ namespace System.Runtime.InteropServices.WindowsRuntime
get { return m_Name; }
}
}
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
index e3c6a926d3..350920564a 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToCollectionAdapter.cs
@@ -39,7 +39,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
uint size = _this.Size;
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)size;
@@ -68,7 +68,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// ICollection expects the destination array to be single-dimensional.
if (array.Rank != 1)
- throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"));
+ throw new ArgumentException(SR.Arg_RankMultiDimNotSupported);
int destLB = array.GetLowerBound(0);
@@ -87,11 +87,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { -1 });
// list.CopyTo(items, 0);
- if(srcLen > (destLen - (arrayIndex - destLB)))
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ if (srcLen > (destLen - (arrayIndex - destLB)))
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
- if(arrayIndex - destLB > destLen)
- throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
+ if (arrayIndex - destLB > destLen)
+ throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds);
// We need to verify the index as we;
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
index d6e50f5164..539b8020b8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
@@ -60,7 +60,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
uint size = _this.Size;
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)(size - 1);
@@ -109,7 +109,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < index)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)index;
@@ -137,7 +137,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
if (((uint)Int32.MaxValue) < index)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
RemoveAtHelper(_this, index);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs
index 3a52d12234..86321e6191 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIKeyValuePairImpl.cs
@@ -47,7 +47,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal static object UnboxHelper(object wrapper)
{
Contract.Requires(wrapper != null);
-
+
CLRIKeyValuePairImpl<K, V> reference = (CLRIKeyValuePairImpl<K, V>)wrapper;
return reference._pair;
}
@@ -61,6 +61,5 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return _pair;
}
-
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
index b7dad17a6b..aa0f3ba056 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
@@ -25,9 +25,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
_data = data;
}
- private static Tuple<Type, PropertyType>[] NumericScalarTypes {
- get {
- if (s_numericScalarTypes == null) {
+ private static Tuple<Type, PropertyType>[] NumericScalarTypes
+ {
+ get
+ {
+ if (s_numericScalarTypes == null)
+ {
Tuple<Type, PropertyType>[] numericScalarTypes = new Tuple<Type, PropertyType>[] {
new Tuple<Type, PropertyType>(typeof(Byte), PropertyType.UInt8),
new Tuple<Type, PropertyType>(typeof(Int16), PropertyType.Int16),
@@ -47,14 +50,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
}
- public PropertyType Type {
+ public PropertyType Type
+ {
[Pure]
get { return _type; }
}
- public bool IsNumericScalar {
+ public bool IsNumericScalar
+ {
[Pure]
- get {
+ get
+ {
return IsNumericScalarImpl(_type, _data);
}
}
@@ -128,7 +134,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public char GetChar16()
{
if (this.Type != PropertyType.Char16)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -137,7 +143,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Boolean GetBoolean()
{
if (this.Type != PropertyType.Boolean)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -160,7 +166,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public DateTimeOffset GetDateTime()
{
if (this.Type != PropertyType.DateTime)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -169,7 +175,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public TimeSpan GetTimeSpan()
{
if (this.Type != PropertyType.TimeSpan)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -178,7 +184,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Point GetPoint()
{
if (this.Type != PropertyType.Point)
- throw new InvalidCastException(Environment.GetResourceString("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);
@@ -188,9 +194,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Size GetSize()
{
if (this.Type != PropertyType.Size)
- throw new InvalidCastException(Environment.GetResourceString("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);
}
@@ -198,9 +204,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Rect GetRect()
{
if (this.Type != PropertyType.Rect)
- throw new InvalidCastException(Environment.GetResourceString("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);
}
@@ -262,7 +268,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public char[] GetChar16Array()
{
if (this.Type != PropertyType.Char16Array)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -271,7 +277,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Boolean[] GetBooleanArray()
{
if (this.Type != PropertyType.BooleanArray)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -286,7 +292,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Object[] GetInspectableArray()
{
if (this.Type != PropertyType.InspectableArray)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -301,7 +307,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public DateTimeOffset[] GetDateTimeArray()
{
if (this.Type != PropertyType.DateTimeArray)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -310,7 +316,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public TimeSpan[] GetTimeSpanArray()
{
if (this.Type != PropertyType.TimeSpanArray)
- throw new InvalidCastException(Environment.GetResourceString("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;
}
@@ -319,9 +325,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Point[] GetPointArray()
{
if (this.Type != PropertyType.PointArray)
- throw new InvalidCastException(Environment.GetResourceString("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);
}
@@ -329,7 +335,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Size[] GetSizeArray()
{
if (this.Type != PropertyType.SizeArray)
- throw new InvalidCastException(Environment.GetResourceString("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();
@@ -340,22 +346,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Rect[] GetRectArray()
{
if (this.Type != PropertyType.RectArray)
- throw new InvalidCastException(Environment.GetResourceString("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);
}
- private T[] CoerceArrayValue<T>(PropertyType unboxType) {
+ private T[] CoerceArrayValue<T>(PropertyType unboxType)
+ {
// If we contain the type being looked for directly, then take the fast-path
- if (Type == unboxType) {
+ if (Type == unboxType)
+ {
return (T[])_data;
}
// Make sure we have an array to begin with
Array dataArray = _data as Array;
- if (dataArray == null) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, typeof(T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
+ if (dataArray == null)
+ {
+ 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
@@ -365,11 +374,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// If we do not have the correct array type, then we need to convert the array element-by-element
// to a new array of the requested type
T[] coercedArray = new T[dataArray.Length];
- for (int i = 0; i < dataArray.Length; ++i) {
- try {
+ for (int i = 0; i < dataArray.Length; ++i)
+ {
+ try
+ {
coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i));
- } catch (InvalidCastException elementCastException) {
- Exception e = new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueArrayCoersion", this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException);
+ }
+ catch (InvalidCastException elementCastException)
+ {
+ Exception e = new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueArrayCoersion, this.Type, typeof (T).MakeArrayType().Name, i, elementCastException.Message), elementCastException);
e.SetErrorCode(elementCastException._HResult);
throw e;
}
@@ -381,92 +394,117 @@ namespace System.Runtime.InteropServices.WindowsRuntime
private T CoerceScalarValue<T>(PropertyType unboxType)
{
// If we are just a boxed version of the requested type, then take the fast path out
- if (Type == unboxType) {
+ if (Type == unboxType)
+ {
return (T)_data;
}
return CoerceScalarValue<T>(Type, _data);
}
- private static T CoerceScalarValue<T>(PropertyType type, object value) {
+ private static T CoerceScalarValue<T>(PropertyType type, object value)
+ {
// If the property type is neither one of the coercable numeric types nor IInspectable, we
// should not attempt coersion, even if the underlying value is technically convertable
- if (!IsCoercable(type, value) && type != PropertyType.Inspectable) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
+ if (!IsCoercable(type, value) && type != PropertyType.Inspectable)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
- try {
+ try
+ {
// Try to coerce:
// * String <--> Guid
// * Numeric scalars
- if (type == PropertyType.String && typeof(T) == typeof(Guid)) {
+ if (type == PropertyType.String && typeof(T) == typeof(Guid))
+ {
return (T)(object)Guid.Parse((string)value);
}
- else if (type == PropertyType.Guid && typeof(T) == typeof(String)) {
- return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture);
+ else if (type == PropertyType.Guid && typeof(T) == typeof(String))
+ {
+ return (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture);
}
- else {
+ else
+ {
// Iterate over the numeric scalars, to see if we have a match for one of the known conversions
- foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
- if (numericScalar.Item1 == typeof(T)) {
+ foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes)
+ {
+ if (numericScalar.Item1 == typeof(T))
+ {
return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
}
}
}
- catch (FormatException) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
+ catch (FormatException)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH);
}
- catch (InvalidCastException) {
- throw new InvalidCastException(Environment.GetResourceString("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);
}
- catch (OverflowException) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueCoersion", type, value, typeof(T).Name), __HResults.DISP_E_OVERFLOW);
+ catch (OverflowException)
+ {
+ 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
// to pass along the request to coerce the value.
IPropertyValue ipv = value as IPropertyValue;
- if (type == PropertyType.Inspectable && ipv != null) {
- if (typeof(T) == typeof(Byte)) {
+ if (type == PropertyType.Inspectable && ipv != null)
+ {
+ if (typeof(T) == typeof(Byte))
+ {
return (T)(object)ipv.GetUInt8();
}
- else if (typeof(T) == typeof(Int16)) {
+ else if (typeof(T) == typeof(Int16))
+ {
return (T)(object)ipv.GetInt16();
}
- else if (typeof(T) == typeof(UInt16)) {
+ else if (typeof(T) == typeof(UInt16))
+ {
return (T)(object)ipv.GetUInt16();
}
- else if (typeof(T) == typeof(Int32)) {
+ else if (typeof(T) == typeof(Int32))
+ {
return (T)(object)ipv.GetUInt32();
}
- else if (typeof(T) == typeof(UInt32)) {
+ else if (typeof(T) == typeof(UInt32))
+ {
return (T)(object)ipv.GetUInt32();
}
- else if (typeof(T) == typeof(Int64)) {
+ else if (typeof(T) == typeof(Int64))
+ {
return (T)(object)ipv.GetInt64();
}
- else if (typeof(T) == typeof(UInt64)) {
+ else if (typeof(T) == typeof(UInt64))
+ {
return (T)(object)ipv.GetUInt64();
}
- else if (typeof(T) == typeof(Single)) {
+ else if (typeof(T) == typeof(Single))
+ {
return (T)(object)ipv.GetSingle();
}
- else if (typeof(T) == typeof(Double)) {
+ else if (typeof(T) == typeof(Double))
+ {
return (T)(object)ipv.GetDouble();
}
- else {
+ else
+ {
BCLDebug.Assert(false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync");
}
}
// Otherwise, this is an invalid coersion
- throw new InvalidCastException(Environment.GetResourceString("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) {
+ private static bool IsCoercable(PropertyType type, object data)
+ {
// String <--> Guid is allowed
- if (type == PropertyType.Guid || type == PropertyType.String) {
+ if (type == PropertyType.Guid || type == PropertyType.String)
+ {
return true;
}
@@ -474,13 +512,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return IsNumericScalarImpl(type, data);
}
- private static bool IsNumericScalarImpl(PropertyType type, object data) {
- if (data.GetType().IsEnum) {
+ private static bool IsNumericScalarImpl(PropertyType type, object data)
+ {
+ if (data.GetType().IsEnum)
+ {
return true;
}
- foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
- if (numericScalar.Item2 == type) {
+ foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes)
+ {
+ if (numericScalar.Item2 == type)
+ {
return true;
}
}
@@ -490,42 +532,50 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Unbox the data stored in the property value to a structurally equivilent type
[Pure]
- private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct {
+ private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct
+ {
Contract.Requires(expectedBoxedType != null);
Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T)));
- if (_data.GetType() != expectedBoxedType) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH);
+ if (_data.GetType() != expectedBoxedType)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH);
}
T unboxed = new T();
- fixed (byte *pData = &JitHelpers.GetPinningHelper(_data).m_data) {
+ fixed (byte* pData = &JitHelpers.GetPinningHelper(_data).m_data)
+ {
byte* pUnboxed = (byte*)JitHelpers.UnsafeCastToStackPointer(ref unboxed);
Buffer.Memcpy(pUnboxed, pData, Marshal.SizeOf(unboxed));
}
-
+
return unboxed;
}
// Convert the array stored in the property value to a structurally equivilent array type
[Pure]
- private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct {
+ private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct
+ {
Contract.Requires(expectedArrayElementType != null);
Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T)));
Array dataArray = _data as Array;
- if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
+ if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
}
T[] converted = new T[dataArray.Length];
- if (converted.Length > 0) {
- fixed (byte * dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data) {
- fixed (byte * convertedPin = &JitHelpers.GetPinningHelper(converted).m_data) {
- byte *pData = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0);
- byte *pConverted = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0);
+ if (converted.Length > 0)
+ {
+ fixed (byte* dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data)
+ {
+ fixed (byte* convertedPin = &JitHelpers.GetPinningHelper(converted).m_data)
+ {
+ byte* pData = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0);
+ byte* pConverted = (byte*)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0);
Buffer.Memcpy(pConverted, pData, checked(Marshal.SizeOf(typeof(T)) * converted.Length));
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
index 9705b61148..3afd87ab12 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIReferenceImpl.cs
@@ -13,7 +13,7 @@ using System.Security;
namespace System.Runtime.InteropServices.WindowsRuntime
{
- internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget
+ internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget
{
private T _value;
@@ -24,7 +24,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
_value = obj;
}
- public T Value {
+ public T Value
+ {
get { return _value; }
}
@@ -55,16 +56,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal static Object UnboxHelper(Object wrapper)
{
Contract.Requires(wrapper != null);
- IReference<T> reference = (IReference<T>) wrapper;
- Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<"+typeof(T)+">, but that failed.");
+ IReference<T> reference = (IReference<T>)wrapper;
+ Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed.");
return reference.Value;
}
}
// T can be any WinRT-compatible type
internal sealed class CLRIReferenceArrayImpl<T> : CLRIPropertyValueImpl,
- IGetProxyTarget,
- IReferenceArray<T>,
+ IGetProxyTarget,
+ IReferenceArray<T>,
IList // Jupiter data binding needs IList/IEnumerable
{
private T[] _value;
@@ -77,10 +78,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
_value = obj;
- _list = (IList) _value;
+ _list = (IList)_value;
}
- public T[] Value {
+ public T[] Value
+ {
get { return _value; }
}
@@ -109,7 +111,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// IList & ICollection methods.
// This enables two-way data binding and index access in Jupiter
//
- Object IList.this[int index] {
+ Object IList.this[int index]
+ {
get
{
return _list[index];
@@ -120,30 +123,30 @@ namespace System.Runtime.InteropServices.WindowsRuntime
_list[index] = value;
}
}
-
+
int IList.Add(Object value)
{
return _list.Add(value);
}
-
+
bool IList.Contains(Object value)
{
return _list.Contains(value);
}
-
+
void IList.Clear()
{
_list.Clear();
}
- bool IList.IsReadOnly
- {
+ bool IList.IsReadOnly
+ {
get
{
return _list.IsReadOnly;
}
}
-
+
bool IList.IsFixedSize
{
get
@@ -156,17 +159,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return _list.IndexOf(value);
}
-
+
void IList.Insert(int index, Object value)
{
_list.Insert(index, value);
}
-
+
void IList.Remove(Object value)
{
_list.Remove(value);
}
-
+
void IList.RemoveAt(int index)
{
_list.RemoveAt(index);
@@ -176,9 +179,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
_list.CopyTo(array, index);
}
-
+
int ICollection.Count
- {
+ {
get
{
return _list.Count;
@@ -186,15 +189,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
Object ICollection.SyncRoot
- {
+ {
get
{
return _list.SyncRoot;
}
}
-
+
bool ICollection.IsSynchronized
- {
+ {
get
{
return _list.IsSynchronized;
@@ -205,7 +208,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return (object)_value;
}
-
+
// We have T in an IReferenceArray<T>. Need to QI for IReferenceArray<T> with the appropriate GUID, call
// the get_Value property, allocate an appropriately-sized managed object, marshal the native object
// to the managed object, and free the native method.
@@ -238,7 +241,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Type type = obj.GetType();
if (type.IsArray)
- return CreateIReferenceArray((Array) obj);
+ return CreateIReferenceArray((Array)obj);
if (type == typeof(int))
return new CLRIReferenceImpl<int>(PropertyType.Int32, (int)obj);
@@ -313,7 +316,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Contract.Ensures(Contract.Result<Object>() != null);
Type type = obj.GetType().GetElementType();
-
+
Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray);
if (type == typeof(int))
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
index 3a896ecbe3..4549a407e0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
@@ -48,9 +48,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentNullException(nameof(data));
Contract.EndContractBlock();
- this.firstItemIndex = 0;
- this.lastItemIndex = data.Count - 1;
- this.items = CreateKeyValueArray(data.Count, data.GetEnumerator());
+ firstItemIndex = 0;
+ lastItemIndex = data.Count - 1;
+ items = CreateKeyValueArray(data.Count, data.GetEnumerator());
}
@@ -61,7 +61,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
this.lastItemIndex = lastItemIndex;
}
-
+
private KeyValuePair<TKey, TValue>[] CreateKeyValueArray(Int32 count, IEnumerator<KeyValuePair<TKey, TValue>> data)
{
KeyValuePair<TKey, TValue>[] kvArray = new KeyValuePair<TKey, TValue>[count];
@@ -76,16 +76,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
- public int Count {
- get {
+ public int Count
+ {
+ get
+ {
return lastItemIndex - firstItemIndex + 1;
}
}
// [CLSCompliant(false)]
- public UInt32 Size {
- get {
+ public UInt32 Size
+ {
+ get
+ {
return (UInt32)(lastItemIndex - firstItemIndex + 1);
}
}
@@ -98,7 +102,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!found)
{
- Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
+ Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
@@ -118,17 +122,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return ((IEnumerable<IKeyValuePair<TKey, TValue>>)this).GetEnumerator();
}
-
+
public IIterator<IKeyValuePair<TKey, TValue>> First()
{
return new EnumeratorToIteratorAdapter<IKeyValuePair<TKey, TValue>>(GetEnumerator());
}
-
+
public IEnumerator<IKeyValuePair<TKey, TValue>> GetEnumerator()
{
return new IKeyValuePairEnumerator(items, firstItemIndex, lastItemIndex);
}
-
+
public void Split(out IMapView<TKey, TValue> firstPartition, out IMapView<TKey, TValue> secondPartition)
{
if (Count < 2)
@@ -144,7 +148,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
secondPartition = new ConstantSplittableMap<TKey, TValue>(items, pivot + 1, lastItemIndex);
}
-#region IReadOnlyDictionary members
+ #region IReadOnlyDictionary members
public bool TryGetValue(TKey key, out TValue value)
{
@@ -197,16 +201,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return false;
}
- public IKeyValuePair<TKey, TValue> Current {
- get {
- if (_current < _start) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
- if (_current > _end) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded));
+ public IKeyValuePair<TKey, TValue> Current
+ {
+ get
+ {
+ if (_current < _start) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumNotStarted));
+ if (_current > _end) throw new InvalidOperationException(SR.GetResourceString(ResId.InvalidOperation_EnumEnded));
return new CLRIKeyValuePairImpl<TKey, TValue>(ref _array[_current]);
}
}
- Object IEnumerator.Current {
- get {
+ Object IEnumerator.Current
+ {
+ get
+ {
return Current;
}
}
@@ -222,7 +230,5 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
#endregion IKeyValuePair Enumerator
-
} // internal ConstantSplittableMap<TKey, TValue>
-
} // namespace System.Runtime.InteropServices.WindowsRuntime
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
index 9f822d5ced..63565a39b8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CustomPropertyImpl.cs
@@ -21,8 +21,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// ICustomProperty implementation - basically a wrapper of PropertyInfo
//
internal sealed class CustomPropertyImpl : ICustomProperty
- {
- private PropertyInfo m_property;
+ {
+ private PropertyInfo m_property;
//
// Constructor
@@ -46,11 +46,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return m_property.Name;
}
}
-
+
public bool CanRead
{
- get
- {
+ get
+ {
// Return false if the getter is not public
return m_property.GetGetMethod() != null;
}
@@ -58,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public bool CanWrite
{
- get
+ get
{
// Return false if the setter is not public
return m_property.GetSetMethod() != null;
@@ -105,21 +105,21 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// We get non-public accessors just so that we can throw the correct exception.
MethodInfo accessor = getValue ? m_property.GetGetMethod(true) : m_property.GetSetMethod(true);
-
+
if (accessor == null)
- throw new ArgumentException(System.Environment.GetResourceString(getValue ? "Arg_GetMethNotFnd" : "Arg_SetMethNotFnd"));
+ throw new ArgumentException(getValue ? SR.Arg_GetMethNotFnd : SR.Arg_SetMethNotFnd);
if (!accessor.IsPublic)
throw new MethodAccessException(
String.Format(
CultureInfo.CurrentCulture,
- Environment.GetResourceString("Arg_MethodAccessException_WithMethodName"),
+ SR.Arg_MethodAccessException_WithMethodName,
accessor.ToString(),
accessor.DeclaringType.FullName));
RuntimeMethodInfo rtMethod = accessor as RuntimeMethodInfo;
if (rtMethod == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeMethodInfo"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo);
// We can safely skip access check because this is only used in full trust scenarios.
// And we have already verified that the property accessor is public.
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
index c33e002e0e..2a34aba717 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryKeyCollection.cs
@@ -30,9 +30,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
+ throw new ArgumentException(SR.Arg_IndexOutOfRangeException);
if (array.Length - index < dictionary.Count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
int i = index;
foreach (KeyValuePair<TKey, TValue> mapping in dictionary)
@@ -41,22 +41,24 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
}
- public int Count {
+ public int Count
+ {
get { return dictionary.Count; }
}
- bool ICollection<TKey>.IsReadOnly {
+ bool ICollection<TKey>.IsReadOnly
+ {
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
+ throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
+ throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
public bool Contains(TKey item)
@@ -66,7 +68,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
bool ICollection<TKey>.Remove(TKey item)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_KeyCollectionSet"));
+ throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
IEnumerator IEnumerable.GetEnumerator()
@@ -93,7 +95,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
- this.enumeration = dictionary.GetEnumerator();
+ enumeration = dictionary.GetEnumerator();
}
void IDisposable.Dispose()
@@ -106,11 +108,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return enumeration.MoveNext();
}
- Object IEnumerator.Current {
+ Object IEnumerator.Current
+ {
get { return ((IEnumerator<TKey>)this).Current; }
}
- public TKey Current {
+ public TKey Current
+ {
get { return enumeration.Current.Key; }
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
index 24e5777768..bb54d49b60 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
@@ -41,7 +41,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!keyFound)
{
- Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
+ Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
@@ -55,7 +55,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
return (uint)_this.Count;
}
-
+
// bool HasKey(K key)
internal bool HasKey<K, V>(K key)
{
@@ -96,7 +96,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!removed)
{
- Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
+ Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
index fcc7755d67..083b0ffcb1 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryValueCollection.cs
@@ -11,7 +11,8 @@ using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
-namespace System.Runtime.InteropServices.WindowsRuntime {
+namespace System.Runtime.InteropServices.WindowsRuntime
+{
[Serializable]
[DebuggerDisplay("Count = {Count}")]
internal sealed class DictionaryValueCollection<TKey, TValue> : ICollection<TValue>
@@ -33,9 +34,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
+ throw new ArgumentException(SR.Arg_IndexOutOfRangeException);
if (array.Length - index < dictionary.Count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
int i = index;
foreach (KeyValuePair<TKey, TValue> mapping in dictionary)
@@ -44,22 +45,24 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
}
}
- public int Count {
+ public int Count
+ {
get { return dictionary.Count; }
}
- bool ICollection<TValue>.IsReadOnly {
+ bool ICollection<TValue>.IsReadOnly
+ {
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ValueCollectionSet"));
+ throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
void ICollection<TValue>.Clear()
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ValueCollectionSet"));
+ throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
public bool Contains(TValue item)
@@ -73,7 +76,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
bool ICollection<TValue>.Remove(TValue item)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ValueCollectionSet"));
+ throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
IEnumerator IEnumerable.GetEnumerator()
@@ -100,7 +103,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
- this.enumeration = dictionary.GetEnumerator();
+ enumeration = dictionary.GetEnumerator();
}
void IDisposable.Dispose()
@@ -113,11 +116,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
return enumeration.MoveNext();
}
- Object IEnumerator.Current {
+ Object IEnumerator.Current
+ {
get { return ((IEnumerator<TValue>)this).Current; }
}
- public TValue Current {
+ public TValue Current
+ {
get { return enumeration.Current.Value; }
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
index 3f9d516162..75b8480eeb 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
@@ -51,20 +51,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public NonGenericToGenericEnumerator(IEnumerator enumerator)
{ this.enumerator = enumerator; }
- public object Current { get { return enumerator.Current; } }
+ public object Current { get { return enumerator.Current; } }
public bool MoveNext() { return enumerator.MoveNext(); }
- public void Reset() { enumerator.Reset(); }
- public void Dispose() { }
+ public void Reset() { enumerator.Reset(); }
+ public void Dispose() { }
}
// This method is invoked when First is called on a managed implementation of IBindableIterable.
internal IBindableIterator First_Stub()
{
IEnumerable _this = JitHelpers.UnsafeCast<IEnumerable>(this);
- return new EnumeratorToIteratorAdapter<object>(new NonGenericToGenericEnumerator(_this.GetEnumerator()) );
+ return new EnumeratorToIteratorAdapter<object>(new NonGenericToGenericEnumerator(_this.GetEnumerator()));
}
}
-
+
// Adapter class which holds a managed IEnumerator<T>, exposing it as a Windows Runtime IIterator<T>
internal sealed class EnumeratorToIteratorAdapter<T> : IIterator<T>, IBindableIterator
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs
index 03b17d9261..974da48a42 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EventRegistrationTokenTable.cs
@@ -28,7 +28,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// static check at construction time
if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EventTokenTableRequiresDelegate", typeof(T)));
+ throw new InvalidOperationException(SR.Format(SR.InvalidOperation_EventTokenTableRequiresDelegate, typeof (T)));
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
index 4c6169a4e8..d62649e7a7 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IClosable.cs
@@ -13,7 +13,6 @@ using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
-
// Local definition of Windows.Foundation.IClosable
[ComImport]
[Guid("30d5a829-7fa4-4026-83bb-d75bae4ea99e")]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs
index 88472a46b8..3ff4ffd098 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomProperty.cs
@@ -19,34 +19,34 @@ namespace System.Runtime.InteropServices.WindowsRuntime
[Pure]
get;
}
-
- string Name
- {
+
+ string Name
+ {
[Pure]
- get;
+ get;
}
[Pure]
object GetValue(object target);
void SetValue(object target, object value);
-
+
[Pure]
object GetValue(object target, object indexValue);
-
+
void SetValue(object target, object value, object indexValue);
-
- bool CanWrite
- {
+
+ bool CanWrite
+ {
[Pure]
- get;
+ get;
}
- bool CanRead
- {
+ bool CanRead
+ {
[Pure]
- get;
- }
+ get;
+ }
}
}
-
+
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
index 3bbde35a3c..f461327712 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ICustomPropertyProvider.cs
@@ -16,7 +16,6 @@ using System.Security;
namespace System.Runtime.InteropServices.WindowsRuntime
{
-
//
// ICustomProperty Implementation helpers
//
@@ -32,7 +31,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Contract.Requires(propertyName != null);
IGetProxyTarget proxy = target as IGetProxyTarget;
- if (proxy != null)
+ if (proxy != null)
target = proxy.GetTarget();
// Only return public instance/static properties
@@ -50,7 +49,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Creates a ICustomProperty implementation for Jupiter
// Called from ICustomPropertyProvider_GetIndexedProperty from within runtime
//
- static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative *pIndexedParamType)
+ static internal unsafe ICustomProperty CreateIndexedProperty(object target, string propertyName, TypeNameNative* pIndexedParamType)
{
Contract.Requires(target != null);
Contract.Requires(propertyName != null);
@@ -58,7 +57,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Type indexedParamType = null;
SystemTypeMarshaler.ConvertToManaged(pIndexedParamType, ref indexedParamType);
- return CreateIndexedProperty(target, propertyName, indexedParamType);
+ return CreateIndexedProperty(target, propertyName, indexedParamType);
}
static internal ICustomProperty CreateIndexedProperty(object target, string propertyName, Type indexedParamType)
@@ -67,7 +66,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Contract.Requires(propertyName != null);
IGetProxyTarget proxy = target as IGetProxyTarget;
- if (proxy != null)
+ if (proxy != null)
target = proxy.GetTarget();
// Only return public instance/static properties
@@ -86,25 +85,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return new CustomPropertyImpl(propertyInfo);
}
- static internal unsafe void GetType(object target, TypeNameNative *pIndexedParamType)
- {
+ static internal unsafe void GetType(object target, TypeNameNative* pIndexedParamType)
+ {
IGetProxyTarget proxy = target as IGetProxyTarget;
- if (proxy != null)
+ if (proxy != null)
target = proxy.GetTarget();
SystemTypeMarshaler.ConvertToNative(target.GetType(), pIndexedParamType);
- }
+ }
}
[Flags]
- enum InterfaceForwardingSupport
+ internal enum InterfaceForwardingSupport
{
- None = 0,
- IBindableVector = 0x1, // IBindableVector -> IBindableVector
- IVector = 0x2, // IBindableVector -> IVector<T>
- IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView
- IVectorView = 0x8, // IBindableVectorView -> IVectorView<T>
- IBindableIterableOrIIterable= 0x10 // IBindableIterable -> IBindableIterable/IIterable<T>
+ None = 0,
+ IBindableVector = 0x1, // IBindableVector -> IBindableVector
+ IVector = 0x2, // IBindableVector -> IVector<T>
+ IBindableVectorView = 0x4, // IBindableVectorView -> IBindableVectorView
+ IVectorView = 0x8, // IBindableVectorView -> IVectorView<T>
+ IBindableIterableOrIIterable = 0x10 // IBindableIterable -> IBindableIterable/IIterable<T>
}
//
@@ -113,9 +112,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
//
internal interface IGetProxyTarget
{
- object GetTarget();
+ object GetTarget();
}
-
+
//
// Proxy that supports data binding on another object
//
@@ -164,7 +163,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// doesn't recognize, and therefore IEnumerable cast won't be able to take advantage of this QI
if (target as IList<T1> != null)
supportFlags |= InterfaceForwardingSupport.IVector;
-
+
if (target as IBindableVectorView != null)
supportFlags |= InterfaceForwardingSupport.IBindableVectorView;
@@ -181,8 +180,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// succeeded, IEnumerable needs to know that
if (target as IEnumerable != null)
supportFlags |= InterfaceForwardingSupport.IBindableIterableOrIIterable;
-
- return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags);
+
+ return new ICustomPropertyProviderProxy<T1, T2>(target, supportFlags);
}
@@ -213,26 +212,26 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// Reject the QI if target doesn't implement IEnumerable
if ((_flags & (InterfaceForwardingSupport.IBindableIterableOrIIterable)) == 0)
- return CustomQueryInterfaceResult.Failed;
+ return CustomQueryInterfaceResult.Failed;
}
if (iid == typeof(IBindableVector).GUID)
{
// Reject the QI if target doesn't implement IBindableVector/IVector
if ((_flags & (InterfaceForwardingSupport.IBindableVector | InterfaceForwardingSupport.IVector)) == 0)
- return CustomQueryInterfaceResult.Failed;
+ return CustomQueryInterfaceResult.Failed;
}
if (iid == typeof(IBindableVectorView).GUID)
{
// Reject the QI if target doesn't implement IBindableVectorView/IVectorView
if ((_flags & (InterfaceForwardingSupport.IBindableVectorView | InterfaceForwardingSupport.IVectorView)) == 0)
- return CustomQueryInterfaceResult.Failed;
+ return CustomQueryInterfaceResult.Failed;
}
-
+
return CustomQueryInterfaceResult.NotHandled;
}
-
+
//
// IEnumerable methods
//
@@ -257,14 +256,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
return GetVectorOfT().GetAt(index);
- }
+ }
}
-
+
[Pure]
- uint IBindableVector.Size
- {
+ uint IBindableVector.Size
+ {
get
- {
+ {
IBindableVector bindableVector = GetIBindableVectorNoThrow();
if (bindableVector != null)
{
@@ -275,10 +274,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
return GetVectorOfT().Size;
- }
+ }
}
}
-
+
[Pure]
IBindableVectorView IBindableVector.GetView()
{
@@ -292,7 +291,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
return new IVectorViewToIBindableVectorViewAdapter<T1>(GetVectorOfT().GetView());
- }
+ }
}
private sealed class IVectorViewToIBindableVectorViewAdapter<T> : IBindableVectorView
@@ -300,8 +299,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
private IVectorView<T> _vectorView;
public IVectorViewToIBindableVectorViewAdapter(IVectorView<T> vectorView)
- {
- this._vectorView = vectorView;
+ {
+ _vectorView = vectorView;
}
[Pure]
@@ -309,16 +308,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return _vectorView.GetAt(index);
}
-
+
[Pure]
uint IBindableVectorView.Size
- {
+ {
get
{
return _vectorView.Size;
}
}
-
+
[Pure]
bool IBindableVectorView.IndexOf(object value, out uint index)
{
@@ -329,9 +328,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return new IteratorOfTToIteratorAdapter<T>(_vectorView.First());
}
+ }
- }
-
[Pure]
bool IBindableVector.IndexOf(object value, out uint index)
{
@@ -345,9 +343,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
return GetVectorOfT().IndexOf(ConvertTo<T1>(value), out index);
- }
+ }
}
-
+
void IBindableVector.SetAt(uint index, object value)
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
@@ -360,9 +358,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
GetVectorOfT().SetAt(index, ConvertTo<T1>(value));
- }
+ }
}
-
+
void IBindableVector.InsertAt(uint index, object value)
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
@@ -375,9 +373,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
GetVectorOfT().InsertAt(index, ConvertTo<T1>(value));
- }
+ }
}
-
+
void IBindableVector.RemoveAt(uint index)
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
@@ -390,9 +388,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
GetVectorOfT().RemoveAt(index);
- }
+ }
}
-
+
void IBindableVector.Append(object value)
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
@@ -405,9 +403,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
GetVectorOfT().Append(ConvertTo<T1>(value));
- }
- }
-
+ }
+ }
+
void IBindableVector.RemoveAtEnd()
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
@@ -420,9 +418,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
GetVectorOfT().RemoveAtEnd();
- }
+ }
}
-
+
void IBindableVector.Clear()
{
IBindableVector bindableVector = GetIBindableVectorNoThrow();
@@ -435,7 +433,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// IBindableVector -> IVector<T>
GetVectorOfT().Clear();
- }
+ }
}
private IBindableVector GetIBindableVectorNoThrow()
@@ -454,7 +452,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new InvalidOperationException(); // We should not go down this path, unless Jupiter pass this out to managed code
// and managed code use reflection to do the cast
}
-
+
//
// IBindableVectorView implementation (forwarding to IBindableVectorView or IVectorView<T>)
//
@@ -467,10 +465,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
else
return GetVectorViewOfT().GetAt(index);
}
-
+
[Pure]
uint IBindableVectorView.Size
- {
+ {
get
{
IBindableVectorView bindableVectorView = GetIBindableVectorViewNoThrow();
@@ -480,7 +478,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return GetVectorViewOfT().Size;
}
}
-
+
[Pure]
bool IBindableVectorView.IndexOf(object value, out uint index)
{
@@ -505,12 +503,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
private IIterator<T> _iterator;
public IteratorOfTToIteratorAdapter(IIterator<T> iterator)
- { this._iterator = iterator; }
+ { _iterator = iterator; }
public bool HasCurrent { get { return _iterator.HasCurrent; } }
- public object Current { get { return (object)_iterator.Current; } }
+ public object Current { get { return (object)_iterator.Current; } }
public bool MoveNext() { return _iterator.MoveNext(); }
- }
+ }
private IBindableVectorView GetIBindableVectorViewNoThrow()
{
@@ -537,9 +535,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Throw ArgumentNullException if value is null (otherwise we'll throw NullReferenceException
// when casting value to T)
ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value);
-
+
// No coersion support needed. If we need coersion later, this is the place
- return (T) value;
+ return (T)value;
}
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs
index dbf4771cf6..30ce895423 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IIterable.cs
@@ -10,6 +10,7 @@ using System.Diagnostics.Contracts;
// Windows.Foundation.Collections.IIterable`1 cannot be referenced from managed code because it's hidden
// by the metadata adapter. We redeclare the interface manually to be able to talk to native WinRT objects.
+
namespace System.Runtime.InteropServices.WindowsRuntime
{
[ComImport]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs
index 8160e6afc9..1f954a66b0 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMap.cs
@@ -11,6 +11,7 @@ using System.Diagnostics.Contracts;
// Windows.Foundation.Collections.IMap`2, IMapView`2, and IKeyValuePair`2 cannot be referenced from
// managed code because they're hidden by the metadata adapter. We redeclare the interfaces manually
// to be able to talk to native WinRT objects.
+
namespace System.Runtime.InteropServices.WindowsRuntime
{
[ComImport]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
index a7424da3fb..e06364dcae 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
@@ -114,7 +114,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
- throw new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
+ throw new KeyNotFoundException(SR.Arg_KeyNotFound);
throw;
}
}
@@ -145,9 +145,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
+ throw new ArgumentException(SR.Arg_IndexOutOfRangeException);
if (array.Length - index < dictionary.Count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
int i = index;
foreach (KeyValuePair<TKey, TValue> mapping in dictionary)
@@ -190,7 +190,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
- this.enumeration = dictionary.GetEnumerator();
+ enumeration = dictionary.GetEnumerator();
}
void IDisposable.Dispose()
@@ -203,11 +203,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return enumeration.MoveNext();
}
- Object IEnumerator.Current {
+ Object IEnumerator.Current
+ {
get { return ((IEnumerator<TKey>)this).Current; }
}
- public TKey Current {
+ public TKey Current
+ {
get { return enumeration.Current.Key; }
}
@@ -240,9 +242,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
if (array.Length <= index && this.Count > 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_IndexOutOfRangeException"));
+ throw new ArgumentException(SR.Arg_IndexOutOfRangeException);
if (array.Length - index < dictionary.Count)
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
int i = index;
foreach (KeyValuePair<TKey, TValue> mapping in dictionary)
@@ -289,7 +291,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentNullException(nameof(dictionary));
this.dictionary = dictionary;
- this.enumeration = dictionary.GetEnumerator();
+ enumeration = dictionary.GetEnumerator();
}
void IDisposable.Dispose()
@@ -302,11 +304,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return enumeration.MoveNext();
}
- Object IEnumerator.Current {
+ Object IEnumerator.Current
+ {
get { return ((IEnumerator<TValue>)this).Current; }
}
- public TValue Current {
+ public TValue Current
+ {
get { return enumeration.Current.Value; }
}
@@ -315,5 +319,4 @@ namespace System.Runtime.InteropServices.WindowsRuntime
enumeration = dictionary.GetEnumerator();
}
} // class ReadOnlyDictionaryValueEnumerator<TKey, TValue>
-
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs
index 4065406dfa..a2b07b2ea7 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IPropertyValue.cs
@@ -139,27 +139,25 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// Specify size directly instead of fields to avoid warnings
- [StructLayoutAttribute(LayoutKind.Sequential, Size=8)]
+ [StructLayoutAttribute(LayoutKind.Sequential, Size = 8)]
[WindowsRuntimeImport]
internal struct Point
{
-
// float X;
// float Y;
}
// Specify size directly instead of fields to avoid warnings
- [StructLayoutAttribute(LayoutKind.Sequential, Size=8)]
+ [StructLayoutAttribute(LayoutKind.Sequential, Size = 8)]
[WindowsRuntimeImport]
internal struct Size
{
-
// float Width;
// float Height;
}
// Specify size directly instead of fields to avoid warnings
- [StructLayoutAttribute(LayoutKind.Sequential, Size=16)]
+ [StructLayoutAttribute(LayoutKind.Sequential, Size = 16)]
[WindowsRuntimeImport]
internal struct Rect
{
@@ -167,5 +165,5 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// float Y;
// float Width;
// float Height;
- }
+ }
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
index b185b41be0..73daf876cd 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
@@ -40,7 +40,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!keyFound)
{
- Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
+ Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
@@ -54,7 +54,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
return (uint)_this.Count;
}
-
+
// bool HasKey(K key)
internal bool HasKey<K, V>(K key)
{
@@ -67,7 +67,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
IReadOnlyDictionary<K, V> _this = JitHelpers.UnsafeCast<IReadOnlyDictionary<K, V>>(this);
- if (_this.Count < 2) {
+ if (_this.Count < 2)
+ {
first = null;
second = null;
return;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
index 431d16256e..5dce7dfc8d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
@@ -35,11 +35,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal T GetAt<T>(uint index)
{
IReadOnlyList<T> _this = JitHelpers.UnsafeCast<IReadOnlyList<T>>(this);
- EnsureIndexInt32(index, _this.Count);
+ EnsureIndexInt32(index, _this.Count);
try
{
- return _this[(int) index];
+ return _this[(int)index];
}
catch (ArgumentOutOfRangeException ex)
{
@@ -126,7 +126,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
index 6982911a13..e88f4f3b9f 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVector.cs
@@ -11,6 +11,7 @@ using System.Diagnostics.Contracts;
// Windows.Foundation.Collections.IVector`1 and IVectorView`1 cannot be referenced from managed
// code because they're hidden by the metadata adapter. We redeclare the interfaces manually
// to be able to talk to native WinRT objects.
+
namespace System.Runtime.InteropServices.WindowsRuntime
{
[ComImport]
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
index 37f21307dc..76b0fff00d 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
@@ -43,7 +43,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
try
{
- return _this.GetAt((uint) index);
+ return _this.GetAt((uint)index);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
@@ -62,15 +62,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
bool fUseString;
Delegate target = System.StubHelpers.StubHelpers.GetTargetForAmbiguousVariantCall(
- this,
- typeof(IReadOnlyList<T>).TypeHandle.Value,
+ this,
+ typeof(IReadOnlyList<T>).TypeHandle.Value,
out fUseString);
if (target != null)
{
return (JitHelpers.UnsafeCast<Indexer_Get_Delegate<T>>(target))(index);
}
-
+
if (fUseString)
{
return JitHelpers.UnsafeCast<T>(Indexer_Get<string>(index));
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
index e219a86769..417476dbbe 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
@@ -31,7 +31,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
Debug.Assert(false, "This class is never instantiated");
}
-
+
// This method is invoked when GetEnumerator is called on a WinRT-backed implementation of IEnumerable<T>.
internal IEnumerator<T> GetEnumerator_Stub<T>()
{
@@ -55,7 +55,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
return (JitHelpers.UnsafeCast<GetEnumerator_Delegate<T>>(target))();
}
-
+
if (fUseString)
{
return JitHelpers.UnsafeCast<IEnumerator<T>>(GetEnumerator_Stub<string>());
@@ -79,7 +79,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public NonGenericToGenericIterator(IBindableIterator iterator)
{ this.iterator = iterator; }
- public object Current { get { return iterator.Current; } }
+ public object Current { get { return iterator.Current; } }
public bool HasCurrent { get { return iterator.HasCurrent; } }
public bool MoveNext() { return iterator.MoveNext(); }
public int GetMany(object[] items) { throw new NotSupportedException(); }
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
index b9fe11557d..5f12322ea8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
@@ -36,7 +36,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal object GetAt(uint index)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
- EnsureIndexInt32(index, _this.Count);
+ EnsureIndexInt32(index, _this.Count);
try
{
@@ -119,7 +119,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal void RemoveAt(uint index)
{
IList _this = JitHelpers.UnsafeCast<IList>(this);
- EnsureIndexInt32(index, _this.Count);
+ EnsureIndexInt32(index, _this.Count);
try
{
@@ -146,7 +146,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
IList _this = JitHelpers.UnsafeCast<IList>(this);
if (_this.Count == 0)
{
- Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRemoveLastFromEmptyCollection"));
+ Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
@@ -170,7 +170,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
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 2e2ea9b876..fc02bedfa6 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
@@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
@@ -61,7 +61,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
try
{
return list[(int)index];
-
}
catch (ArgumentOutOfRangeException ex)
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
index b73f4d7a99..87330e2559 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
@@ -36,7 +36,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal T GetAt<T>(uint index)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
- EnsureIndexInt32(index, _this.Count);
+ EnsureIndexInt32(index, _this.Count);
try
{
@@ -128,7 +128,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal void RemoveAt<T>(uint index)
{
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
- EnsureIndexInt32(index, _this.Count);
+ EnsureIndexInt32(index, _this.Count);
try
{
@@ -155,7 +155,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this);
if (_this.Count == 0)
{
- Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRemoveLastFromEmptyCollection"));
+ Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
@@ -201,7 +201,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// that Size > Int32.MaxValue:
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
- Exception e = new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue"));
+ Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
e.SetErrorCode(__HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
index 2d08cab0ee..12b13ac79b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ManagedActivationFactory.cs
@@ -41,8 +41,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Check whether the type is "exported to WinRT", i.e. it is declared in a managed .winmd and is decorated
// with at least one ActivatableAttribute or StaticAttribute.
if (!(type is RuntimeType) || !type.IsExportedToWindowsRuntime)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypeNotActivatableViaWindowsRuntime", type), nameof(type));
-
+ throw new ArgumentException(SR.Format(SR.Argument_TypeNotActivatableViaWindowsRuntime, type), nameof(type));
+
m_type = type;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
index f11260eb4a..6b6c1719c3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToCollectionAdapter.cs
@@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingDictionaryTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingDictionaryTooLarge);
}
return (int)size;
@@ -58,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)size;
@@ -140,10 +140,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length <= arrayIndex && Count<K, V>() > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
+ throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds);
if (array.Length - arrayIndex < Count<K, V>())
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
Contract.EndContractBlock();
@@ -175,7 +175,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < index)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
VectorToListAdapter.RemoveAtHelper<KeyValuePair<K, V>>(_this_vector, index);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
index 981972ca9f..224a266b07 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
@@ -88,7 +88,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentNullException(nameof(key));
if (ContainsKey<K, V>(key))
- throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate"));
+ throw new ArgumentException(SR.Argument_AddingDuplicate);
Contract.EndContractBlock();
@@ -110,7 +110,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
_this.Remove(key);
return true;
-
}
catch (Exception ex)
{
@@ -158,9 +157,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
-
if (__HResults.E_BOUNDS == ex._HResult)
- throw new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
+ throw new KeyNotFoundException(SR.Arg_KeyNotFound);
throw;
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
index a3715da0b0..5d509549d3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapViewToReadOnlyCollectionAdapter.cs
@@ -46,7 +46,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingDictionaryTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingDictionaryTooLarge);
}
return (int)size;
@@ -58,7 +58,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)size;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
index 627de8d400..ccae412987 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/NativeMethods.cs
@@ -38,14 +38,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
[SuppressUnmanagedCodeSecurity]
internal static unsafe extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)] string sourceString,
int length,
- [Out] IntPtr *hstring);
+ [Out] IntPtr* hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
[SuppressUnmanagedCodeSecurity]
- internal static unsafe extern int WindowsCreateStringReference(char *sourceString,
+ internal static unsafe extern int WindowsCreateStringReference(char* sourceString,
int length,
- [Out] HSTRING_HEADER *hstringHeader,
- [Out] IntPtr *hstring);
+ [Out] HSTRING_HEADER* hstringHeader,
+ [Out] IntPtr* hstring);
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
[SuppressUnmanagedCodeSecurity]
@@ -53,6 +53,6 @@ namespace System.Runtime.InteropServices.WindowsRuntime
[DllImport("api-ms-win-core-winrt-string-l1-1-0.dll", CallingConvention = CallingConvention.StdCall)]
[SuppressUnmanagedCodeSecurity]
- internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint *length);
+ internal static unsafe extern char* WindowsGetStringRawBuffer(IntPtr hstring, [Out] uint* length);
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs
index ad64c9917f..8a3e2066cf 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/PropertyValue.cs
@@ -17,20 +17,20 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal enum PropertyType
{
// WARNING: These values have to match enum Windows.Foundation.PropertyType !!!
- Empty = 0,
- UInt8 = 1,
+ Empty = 0,
+ UInt8 = 1,
Int16 = 2,
UInt16 = 3,
- Int32 = 4,
- UInt32 = 5,
- Int64 = 6,
- UInt64 = 7,
- Single = 8,
- Double = 9,
- Char16 = 10,
- Boolean = 11,
- String = 12,
- Inspectable = 13,
+ Int32 = 4,
+ UInt32 = 5,
+ Int64 = 6,
+ UInt64 = 7,
+ Single = 8,
+ Double = 9,
+ Char16 = 10,
+ Boolean = 11,
+ String = 12,
+ Inspectable = 13,
DateTime = 14,
TimeSpan = 15,
Guid = 16,
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
index cd3c53ab4e..fdc0d22632 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/RuntimeClass.cs
@@ -10,15 +10,15 @@
**
**
===========================================================*/
-namespace System.Runtime.InteropServices.WindowsRuntime {
-
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Runtime.CompilerServices;
- using System.Security;
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Runtime.CompilerServices;
+using System.Security;
+namespace System.Runtime.InteropServices.WindowsRuntime
+{
// Local definition of Windows.Foundation.IStringable
[ComImport]
[Guid("96369f54-8eb6-48f0-abce-c1b211e627c3")]
@@ -33,7 +33,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
internal static string ToString(object obj)
{
IGetProxyTarget proxy = obj as IGetProxyTarget;
- if (proxy != null)
+ if (proxy != null)
obj = proxy.GetTarget();
// Check whether the type implements IStringable.
@@ -41,12 +41,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
if (stringableType != null)
{
return stringableType.ToString();
- }
-
+ }
+
return obj.ToString();
- }
+ }
}
-
+
//
// Base class for every WinRT class
// We'll make it a ComImport and WindowsRuntimeImport in the type loader
@@ -57,11 +57,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
//
// Support for ToString/GetHashCode/Equals override
//
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal extern IntPtr GetRedirectedGetHashCodeMD();
-
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal extern int RedirectGetHashCode(IntPtr pMD);
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern IntPtr GetRedirectedGetHashCodeMD();
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern int RedirectGetHashCode(IntPtr pMD);
public override int GetHashCode()
{
@@ -71,10 +71,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
return RedirectGetHashCode(pMD);
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal extern IntPtr GetRedirectedToStringMD();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern IntPtr GetRedirectedToStringMD();
- [MethodImpl(MethodImplOptions.InternalCall)]
+ [MethodImpl(MethodImplOptions.InternalCall)]
internal extern string RedirectToString(IntPtr pMD);
public override string ToString()
@@ -96,11 +96,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime {
}
}
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal extern IntPtr GetRedirectedEqualsMD();
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern IntPtr GetRedirectedEqualsMD();
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal extern bool RedirectEquals(object obj, IntPtr pMD);
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern bool RedirectEquals(object obj, IntPtr pMD);
public override bool Equals(object obj)
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
index 898f1a68a0..3065b83c30 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToCollectionAdapter.cs
@@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
uint size = _this.Size;
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)size;
@@ -83,10 +83,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
throw new ArgumentOutOfRangeException(nameof(arrayIndex));
if (array.Length <= arrayIndex && Count<T>() > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_IndexOutOfArrayBounds"));
+ throw new ArgumentException(SR.Argument_IndexOutOfArrayBounds);
if (array.Length - arrayIndex < Count<T>())
- throw new ArgumentException(Environment.GetResourceString("Argument_InsufficientSpaceToCopyCollection"));
+ throw new ArgumentException(SR.Argument_InsufficientSpaceToCopyCollection);
Contract.EndContractBlock();
@@ -111,7 +111,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < index)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
VectorToListAdapter.RemoveAtHelper<T>(_this, index);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
index 3e3324864d..56e62a25e7 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
@@ -63,7 +63,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) < index)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)index;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
index 6b7785d2dc..84c12f8a5c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorViewToReadOnlyCollectionAdapter.cs
@@ -38,7 +38,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
uint size = _this.Size;
if (((uint)Int32.MaxValue) < size)
{
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
+ throw new InvalidOperationException(SR.InvalidOperation_CollectionBackingListTooLarge);
}
return (int)size;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
index 551ee65153..55c356de93 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeBufferHelper.cs
@@ -9,29 +9,26 @@ using System.Security;
using System.Threading;
-namespace System.Runtime.InteropServices.WindowsRuntime {
-
-/// <summary>
-/// Exposes a helper method that allows <code>WindowsRuntimeBuffer : IBuffer, IBufferInternal</code> which is implemented in
-/// <code>System.Runtime.WindowsRuntime.dll</code> to call into the VM.
-/// </summary>
-[FriendAccessAllowed]
-internal static class WindowsRuntimeBufferHelper {
-
-
- [DllImport(JitHelpers.QCall)]
- [SuppressUnmanagedCodeSecurity]
- private unsafe extern static void StoreOverlappedPtrInCCW(ObjectHandleOnStack windowsRuntimeBuffer, NativeOverlapped* overlapped);
-
-
+namespace System.Runtime.InteropServices.WindowsRuntime
+{
+ /// <summary>
+ /// Exposes a helper method that allows <code>WindowsRuntimeBuffer : IBuffer, IBufferInternal</code> which is implemented in
+ /// <code>System.Runtime.WindowsRuntime.dll</code> to call into the VM.
+ /// </summary>
[FriendAccessAllowed]
- internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped) {
-
- StoreOverlappedPtrInCCW(JitHelpers.GetObjectHandleOnStack(ref windowsRuntimeBuffer), overlapped);
- }
-
-} // class WindowsRuntimeBufferHelper
-
+ internal static class WindowsRuntimeBufferHelper
+ {
+ [DllImport(JitHelpers.QCall)]
+ [SuppressUnmanagedCodeSecurity]
+ private unsafe extern static void StoreOverlappedPtrInCCW(ObjectHandleOnStack windowsRuntimeBuffer, NativeOverlapped* overlapped);
+
+
+ [FriendAccessAllowed]
+ internal unsafe static void StoreOverlappedInCCW(Object windowsRuntimeBuffer, NativeOverlapped* overlapped)
+ {
+ StoreOverlappedPtrInCCW(JitHelpers.GetObjectHandleOnStack(ref windowsRuntimeBuffer), overlapped);
+ }
+ } // class WindowsRuntimeBufferHelper
} // namespace
// WindowsRuntimeBufferHelper.cs
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
index 57655ec861..0b7ba10d62 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
@@ -75,9 +75,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (target == null || Marshal.IsComObject(target))
NativeOrStaticEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler);
else
- ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler);
+ ManagedEventRegistrationImpl.RemoveEventHandler<T>(removeMethod, handler);
}
-
+
public static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
if (removeMethod == null)
@@ -108,7 +108,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
count += ManagedEventRegistrationImpl.s_eventRegistrations.Keys.Count;
}
}
-
+
if (NativeOrStaticEventRegistrationImpl.s_eventRegistrations != null)
{
lock (NativeOrStaticEventRegistrationImpl.s_eventRegistrations)
@@ -116,7 +116,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
count += NativeOrStaticEventRegistrationImpl.s_eventRegistrations.Count;
}
}
-
+
return count;
}
@@ -124,11 +124,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Optimized version of List of EventRegistrationToken
// It is made a struct to reduce overhead
//
- internal struct EventRegistrationTokenList
+ internal struct EventRegistrationTokenList
{
- private EventRegistrationToken firstToken; // Optimization for common case where there is only one token
- private List<EventRegistrationToken> restTokens; // Rest of the tokens
-
+ private EventRegistrationToken firstToken; // Optimization for common case where there is only one token
+ private List<EventRegistrationToken> restTokens; // Rest of the tokens
+
internal EventRegistrationTokenList(EventRegistrationToken token)
{
firstToken = token;
@@ -141,18 +141,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public bool Push(EventRegistrationToken token)
{
bool needCopy = false;
-
+
if (restTokens == null)
{
restTokens = new List<EventRegistrationToken>();
needCopy = true;
}
-
+
restTokens.Add(token);
return needCopy;
}
-
+
// Pops the last token
// Returns false if no more tokens left, true otherwise
public bool Pop(out EventRegistrationToken token)
@@ -163,14 +163,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
token = firstToken;
return false;
}
-
+
int last = restTokens.Count - 1;
token = restTokens[last];
restTokens.RemoveAt(last);
-
+
return true;
}
-
+
public void CopyTo(List<EventRegistrationToken> tokens)
{
tokens.Add(firstToken);
@@ -183,7 +183,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Event registration support for managed objects events & static events
//
internal static class ManagedEventRegistrationImpl
- {
+ {
// Mappings of delegates registered for events -> their registration tokens.
// These mappings are stored indexed by the remove method which can be used to undo the registrations.
//
@@ -208,10 +208,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// If the delegates aren't alive, it means either they have been unsubscribed, or the object itself is gone,
// and in either case, they've been already taken care of.
//
- internal volatile static
- ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations =
+ internal volatile static
+ ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>> s_eventRegistrations =
new ConditionalWeakTable<object, Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>>();
-
+
internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
Action<EventRegistrationToken> removeMethod,
T handler)
@@ -239,18 +239,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (needCopy)
registrationTokens[handler] = tokens;
}
-
+
BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for managed instance = " + instance + ", handler = " + handler + "\n");
}
}
-
+
// Get the event registration token table for an event. These are indexed by the remove method of the event.
private static Dictionary<object, EventRegistrationTokenList> GetEventRegistrationTokenTable(object instance, Action<EventRegistrationToken> removeMethod)
{
Contract.Requires(instance != null);
Contract.Requires(removeMethod != null);
- Contract.Requires(s_eventRegistrations != null);
-
+ Contract.Requires(s_eventRegistrations != null);
+
lock (s_eventRegistrations)
{
Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>> instanceMap = null;
@@ -259,14 +259,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
instanceMap = new Dictionary<MethodInfo, Dictionary<object, EventRegistrationTokenList>>();
s_eventRegistrations.Add(instance, instanceMap);
}
-
+
Dictionary<object, EventRegistrationTokenList> tokens = null;
if (!instanceMap.TryGetValue(removeMethod.Method, out tokens))
{
tokens = new Dictionary<object, EventRegistrationTokenList>();
instanceMap.Add(removeMethod.Method, tokens);
}
-
+
return tokens;
}
}
@@ -278,19 +278,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime
object instance = removeMethod.Target;
Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod);
EventRegistrationToken token;
-
+
lock (registrationTokens)
{
EventRegistrationTokenList tokens;
-
+
// Failure to find a registration for a token is not an error - it's simply a no-op.
if (!registrationTokens.TryGetValue(handler, out tokens))
{
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instance + ", handler= " + handler + "\n");
-
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instance + ", handler= " + handler + "\n");
+
return;
}
-
+
// Select a registration token to unregister
// We don't care which one but I'm returning the last registered token to be consistent
// with native event registration implementation
@@ -306,23 +306,23 @@ namespace System.Runtime.InteropServices.WindowsRuntime
registrationTokens.Remove(handler);
}
}
-
+
removeMethod(token);
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instance + ", handler = " + handler + ", token = " + token.m_value + "\n");
}
internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
{
- Contract.Requires(removeMethod != null);
+ Contract.Requires(removeMethod != null);
object instance = removeMethod.Target;
Dictionary<object, EventRegistrationTokenList> registrationTokens = GetEventRegistrationTokenTable(instance, removeMethod);
List<EventRegistrationToken> tokensToRemove = new List<EventRegistrationToken>();
-
+
lock (registrationTokens)
- {
+ {
// Copy all tokens to tokensToRemove array which later we'll call removeMethod on
// outside this lock
foreach (EventRegistrationTokenList tokens in registrationTokens.Values)
@@ -339,9 +339,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
//
// Remove all handlers outside the lock
//
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instance + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instance + "\n");
CallRemoveMethods(removeMethod, tokensToRemove);
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instance + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instance + "\n");
}
}
@@ -349,15 +349,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// WinRT event registration implementation code
//
internal static class NativeOrStaticEventRegistrationImpl
- {
+ {
//
// Key = (target object, event)
// We use a key of object+event to save an extra dictionary
//
internal struct EventCacheKey
{
- internal object target;
- internal MethodInfo method;
+ internal object target;
+ internal MethodInfo method;
public override string ToString()
{
@@ -377,7 +377,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return key.target.GetHashCode() ^ key.method.GetHashCode();
}
}
-
+
//
// EventRegistrationTokenListWithCount
//
@@ -390,9 +390,9 @@ namespace System.Runtime.InteropServices.WindowsRuntime
//
internal class EventRegistrationTokenListWithCount
{
- private TokenListCount _tokenListCount;
- EventRegistrationTokenList _tokenList;
-
+ private TokenListCount _tokenListCount;
+ private EventRegistrationTokenList _tokenList;
+
internal EventRegistrationTokenListWithCount(TokenListCount tokenListCount, EventRegistrationToken token)
{
_tokenListCount = tokenListCount;
@@ -400,30 +400,30 @@ namespace System.Runtime.InteropServices.WindowsRuntime
_tokenList = new EventRegistrationTokenList(token);
}
-
+
~EventRegistrationTokenListWithCount()
- {
+ {
// Decrement token list count
// This is need to correctly keep trace of number of tokens for EventCacheKey
// and remove it from cache when the token count drop to 0
// we don't need to take locks for decrement the count - we only need to take a global
// lock when we decide to destroy cache for the IUnknown */type instance
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finalizing EventRegistrationTokenList for " + _tokenListCount.Key + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finalizing EventRegistrationTokenList for " + _tokenListCount.Key + "\n");
_tokenListCount.Dec();
}
-
+
public void Push(EventRegistrationToken token)
{
// Since EventRegistrationTokenListWithCount is a reference type, there is no need
// to copy back. Ignore the return value
_tokenList.Push(token);
}
-
+
public bool Pop(out EventRegistrationToken token)
{
return _tokenList.Pop(out token);
}
-
+
public void CopyTo(List<EventRegistrationToken> tokens)
{
_tokenList.CopyTo(tokens);
@@ -438,8 +438,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
//
internal class TokenListCount
{
- private int _count;
- private EventCacheKey _key;
+ private int _count;
+ private EventCacheKey _key;
internal TokenListCount(EventCacheKey key)
{
@@ -448,14 +448,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal EventCacheKey Key
{
-
get { return _key; }
}
-
+
internal void Inc()
{
int newCount = Interlocked.Increment(ref _count);
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Incremented TokenListCount for " + _key + ", Value = " + newCount + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Incremented TokenListCount for " + _key + ", Value = " + newCount + "\n");
}
internal void Dec()
@@ -466,7 +465,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
try
{
int newCount = Interlocked.Decrement(ref _count);
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Decremented TokenListCount for " + _key + ", Value = " + newCount + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Decremented TokenListCount for " + _key + ", Value = " + newCount + "\n");
if (newCount == 0)
CleanupCache();
}
@@ -482,7 +481,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// because the total token list count has dropped to 0 and we don't have any events subscribed
Contract.Requires(s_eventRegistrations != null);
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Removing " + _key + " from cache" + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Removing " + _key + " from cache" + "\n");
s_eventRegistrations.Remove(_key);
BCLDebug.Log("INTEROP", "[WinRT_Eventing] s_eventRegistrations size = " + s_eventRegistrations.Count + "\n");
}
@@ -520,7 +519,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// b. The same delegate is subscribed then unsubscribed. We need to make sure give
// them the latest token in this case. This is guaranteed by always giving the last token and always use equality to
// add/remove event handlers
- internal volatile static Dictionary<EventCacheKey, EventCacheEntry> s_eventRegistrations =
+ internal volatile static Dictionary<EventCacheKey, EventCacheEntry> s_eventRegistrations =
new Dictionary<EventCacheKey, EventCacheEntry>(new EventCacheKeyEqualityComparer());
// Prevent add/remove handler code to run at the same with with cache cleanup code
@@ -533,11 +532,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Debug.Assert(target == null || Marshal.IsComObject(target), "Must be null or a RCW");
if (target == null)
return removeMethod.Method.DeclaringType;
-
+
// Need the "Raw" IUnknown pointer for the RCW that is not bound to the current context
- return (object) Marshal.GetRawIUnknownForComObjectNoAddRef(target);
+ return (object)Marshal.GetRawIUnknownForComObjectNoAddRef(target);
}
-
+
internal static void AddEventHandler<T>(Func<T, EventRegistrationToken> addMethod,
Action<EventRegistrationToken> removeMethod,
T handler)
@@ -552,11 +551,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
EventRegistrationToken token = addMethod(handler);
bool tokenAdded = false;
-
+
try
{
EventRegistrationTokenListWithCount tokens;
-
+
//
// The whole add/remove code has to be protected by a reader/writer lock
// Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time
@@ -592,8 +591,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
tokens.Push(token);
}
-
- tokenAdded = true;
+
+ tokenAdded = true;
}
}
finally
@@ -601,10 +600,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
s_eventCacheRWLock.ReleaseReaderLock();
}
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for instance = " + instanceKey + ", handler = " + handler + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event subscribed for instance = " + instanceKey + ", handler = " + handler + "\n");
}
- catch(Exception)
- {
+ catch (Exception)
+ {
// If we've already added the token and go there, we don't need to "UNDO" anything
if (!tokenAdded)
{
@@ -613,8 +612,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
removeMethod(token);
}
-
- throw;
+
+ throw;
}
}
@@ -633,18 +632,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime
return GetEventRegistrationTokenTableInternal(instance, removeMethod, out tokenListCount, /* createIfNotFound = */ true);
}
-
+
// Get the event registration token table for an event. These are indexed by the remove method of the event.
private static ConditionalWeakTable<object, EventRegistrationTokenListWithCount> GetEventRegistrationTokenTableInternal(object instance, Action<EventRegistrationToken> removeMethod, out TokenListCount tokenListCount, bool createIfNotFound)
{
Contract.Requires(instance != null);
Contract.Requires(removeMethod != null);
- Contract.Requires(s_eventRegistrations != null);
+ Contract.Requires(s_eventRegistrations != null);
EventCacheKey eventCacheKey;
eventCacheKey.target = instance;
eventCacheKey.method = removeMethod.Method;
-
+
lock (s_eventRegistrations)
{
EventCacheEntry eventCacheEntry;
@@ -656,18 +655,18 @@ namespace System.Runtime.InteropServices.WindowsRuntime
tokenListCount = null;
return null;
}
-
+
BCLDebug.Log("INTEROP", "[WinRT_Eventing] Adding (" + instance + "," + removeMethod.Method + ") into cache" + "\n");
-
+
eventCacheEntry = new EventCacheEntry();
eventCacheEntry.registrationTable = new ConditionalWeakTable<object, EventRegistrationTokenListWithCount>();
eventCacheEntry.tokenListCount = new TokenListCount(eventCacheKey);
-
+
s_eventRegistrations.Add(eventCacheKey, eventCacheEntry);
}
-
+
tokenListCount = eventCacheEntry.tokenListCount;
-
+
return eventCacheEntry.registrationTable;
}
}
@@ -677,7 +676,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
object instanceKey = GetInstanceKey(removeMethod);
EventRegistrationToken token;
-
+
//
// The whole add/remove code has to be protected by a reader/writer lock
// Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time
@@ -691,10 +690,10 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
// We have no information regarding this particular instance (IUnknown*/type) - just return
// This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instanceKey + ", handler= " + handler + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] no registrationTokens found for instance=" + instanceKey + ", handler= " + handler + "\n");
return;
}
-
+
lock (registrationTokens)
{
EventRegistrationTokenListWithCount tokens;
@@ -707,12 +706,12 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Note that inside TryGetValueWithValueEquality we assumes that any delegate
// with the same value equality would have the same hash code
object key = registrationTokens.FindEquivalentKeyUnsafe(handler, out tokens);
- Debug.Assert((key != null && tokens != null) || (key == null && tokens == null),
+ Debug.Assert((key != null && tokens != null) || (key == null && tokens == null),
"key and tokens must be both null or non-null");
if (tokens == null)
{
// Failure to find a registration for a token is not an error - it's simply a no-op.
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] no token list found for instance=" + instanceKey + ", handler= " + handler + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] no token list found for instance=" + instanceKey + ", handler= " + handler + "\n");
return;
}
@@ -721,7 +720,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// is created at the same address before the entry for the old one goes away.
// See comments above s_eventRegistrations for more details
bool moreItems = tokens.Pop(out token);
-
+
// If the last token is removed from token list, we need to remove it from the cache
// otherwise FindEquivalentKeyUnsafe may found this empty token list even though there could be other
// equivalent keys in there with non-0 token list
@@ -733,8 +732,8 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// EventRegistrationTokenList
registrationTokens.Remove(key);
}
-
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.m_value + "\n");
+
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for managed instance = " + instanceKey + ", handler = " + handler + ", token = " + token.m_value + "\n");
}
}
finally
@@ -745,7 +744,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Call removeMethod outside of RW lock
// At this point we don't need to worry about race conditions and we can avoid deadlocks
// if removeMethod waits on finalizer thread
- removeMethod(token);
+ removeMethod(token);
}
internal static void RemoveAllEventHandlers(Action<EventRegistrationToken> removeMethod)
@@ -753,7 +752,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
object instanceKey = GetInstanceKey(removeMethod);
List<EventRegistrationToken> tokensToRemove = new List<EventRegistrationToken>();
-
+
//
// The whole add/remove code has to be protected by a reader/writer lock
// Add/Remove cannot run at the same time with cache cleanup but Add/Remove can run at the same time
@@ -769,7 +768,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// This is necessary to avoid leaking empty dictionary/conditionalWeakTables for this instance
return;
}
-
+
lock (registrationTokens)
{
// Copy all tokens to tokensToRemove array which later we'll call removeMethod on
@@ -782,7 +781,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Clear the table - at this point all event handlers are no longer in the cache
// but they are not removed yet
registrationTokens.Clear();
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Cache cleared for managed instance = " + instanceKey + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Cache cleared for managed instance = " + instanceKey + "\n");
}
}
finally
@@ -793,18 +792,17 @@ namespace System.Runtime.InteropServices.WindowsRuntime
//
// Remove all handlers outside the lock
//
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instanceKey + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Start removing all events for instance = " + instanceKey + "\n");
CallRemoveMethods(removeMethod, tokensToRemove);
- BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instanceKey + "\n");
+ BCLDebug.Log("INTEROP", "[WinRT_Eventing] Finished removing all events for instance = " + instanceKey + "\n");
}
-
+
internal class ReaderWriterLockTimedOutException : ApplicationException
{
}
- /// I borrowed Vance's reader writer lock implementation from his blog as ReaderWriterLockSlim is
- /// available in System.Core.dll!
+ /// Discussed @ https://blogs.msdn.microsoft.com/vancem/2006/03/29/analysis-of-reader-writer-lock/
///
/// <summary>
/// A reader-writer lock implementation that is intended to be simple, yet very
@@ -821,19 +819,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Lock specifiation for myLock: This lock protects exactly the local fields associted
// instance of MyReaderWriterLock. It does NOT protect the memory associted with the
// the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
- int myLock;
+ private int myLock;
// Who owns the lock owners > 0 => readers
// owners = -1 means there is one writer. Owners must be >= -1.
- int owners;
+ private int owners;
// These variables allow use to avoid Setting events (which is expensive) if we don't have to.
- uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
- uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
+ private uint numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
+ private uint numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
// conditions we wait on.
- EventWaitHandle writeEvent; // threads waiting to aquire a write lock go here.
- EventWaitHandle readEvent; // threads waiting to aquire a read lock go here (will be released in bulk)
+ private EventWaitHandle writeEvent; // threads waiting to aquire a write lock go here.
+ private EventWaitHandle readEvent; // threads waiting to aquire a read lock go here (will be released in bulk)
internal MyReaderWriterLock()
{
@@ -843,7 +841,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal void AcquireReaderLock(int millisecondsTimeout)
{
EnterMyLock();
- for (; ; )
+ for (;;)
{
// We can enter a read lock if there are only read-locks have been given out
// and a writer is not trying to get in.
@@ -869,7 +867,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
internal void AcquireWriterLock(int millisecondsTimeout)
{
EnterMyLock();
- for (; ; )
+ for (;;)
{
if (owners == 0)
{
@@ -912,15 +910,16 @@ namespace System.Runtime.InteropServices.WindowsRuntime
/// while holding a spin lock). If all goes well, reenter the lock and
/// set 'waitEvent'
/// </summary>
- private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) {
+ private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
+ {
Debug.Assert(myLock != 0, "Lock must be held");
Debug.Assert(waitEvent == null, "Wait event must be null");
ExitMyLock();
EventWaitHandle newEvent;
- if (makeAutoResetEvent)
+ if (makeAutoResetEvent)
newEvent = new AutoResetEvent(false);
- else
+ else
newEvent = new ManualResetEvent(false);
EnterMyLock();
if (waitEvent == null) // maybe someone snuck in.
@@ -944,7 +943,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
if (!waitEvent.WaitOne(millisecondsTimeout, false))
throw new ReaderWriterLockTimedOutException();
-
+
waitSuccessful = true;
}
finally
@@ -977,18 +976,19 @@ namespace System.Runtime.InteropServices.WindowsRuntime
ExitMyLock();
}
- private void EnterMyLock() {
+ private void EnterMyLock()
+ {
if (Interlocked.CompareExchange(ref myLock, 1, 0) != 0)
EnterMyLockSpin();
}
private void EnterMyLockSpin()
{
- for (int i = 0; ;i++)
+ for (int i = 0; ; i++)
{
if (i < 3 && Environment.ProcessorCount > 1)
Thread.SpinWait(20); // Wait a few dozen instructions to let another processor release lock.
- else
+ else
Thread.Sleep(0); // Give up my quantum.
if (Interlocked.CompareExchange(ref myLock, 1, 0) == 0)
@@ -1000,7 +1000,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Debug.Assert(myLock != 0, "Exiting spin lock that is not held");
myLock = 0;
}
- };
+ };
}
//
@@ -1008,27 +1008,26 @@ namespace System.Runtime.InteropServices.WindowsRuntime
//
internal static void CallRemoveMethods(Action<EventRegistrationToken> removeMethod, List<EventRegistrationToken> tokensToRemove)
{
-
List<Exception> exceptions = new List<Exception>();
-
+
foreach (EventRegistrationToken token in tokensToRemove)
{
try
{
removeMethod(token);
}
- catch(Exception ex)
+ catch (Exception ex)
{
exceptions.Add(ex);
}
-
+
BCLDebug.Log("INTEROP", "[WinRT_Eventing] Event unsubscribed for token = " + token.m_value + "\n");
- }
+ }
if (exceptions.Count > 0)
throw new AggregateException(exceptions.ToArray());
}
-
+
internal static unsafe string HStringToString(IntPtr hstring)
{
Contract.Requires(Environment.IsWinRTSupported);
@@ -1055,13 +1054,13 @@ namespace System.Runtime.InteropServices.WindowsRuntime
string message = innerException.Message;
if (message == null && messageResource != null)
{
- message = Environment.GetResourceString(messageResource);
+ message = SR.GetResourceString(messageResource);
}
e = new Exception(message, innerException);
}
else
{
- string message = (messageResource != null ? Environment.GetResourceString(messageResource) : null);
+ string message = (messageResource != null ? SR.GetResourceString(messageResource): null);
e = new Exception(message);
}
@@ -1109,7 +1108,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
private static Guid s_iidIErrorInfo = new Guid(0x1CF2B120, 0x547D, 0x101B, 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19);
-
+
/// <summary>
/// Report that an exception has occurred which went user unhandled. This allows the global error handler
/// for the application to be invoked to process the error.
@@ -1183,14 +1182,14 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// Get an IActivationFactory * for a managed type
internal static IntPtr GetActivationFactoryForType(Type type)
{
- ManagedActivationFactory activationFactory = GetManagedActivationFactory(type);
+ ManagedActivationFactory activationFactory = GetManagedActivationFactory(type);
return Marshal.GetComInterfaceForObject(activationFactory, typeof(IActivationFactory));
- }
+ }
internal static ManagedActivationFactory GetManagedActivationFactory(Type type)
{
ManagedActivationFactory activationFactory = new ManagedActivationFactory(type);
-
+
// If the type has any associated factory interfaces (i.e. supports non-default activation
// or has statics), the CCW for this instance of ManagedActivationFactory must support them.
Marshal.InitializeManagedWinRTFactoryObject(activationFactory, (RuntimeType)type);
@@ -1235,7 +1234,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public static IntPtr StringToHString(String s)
{
if (!Environment.IsWinRTSupported)
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (s == null)
throw new ArgumentNullException(nameof(s));
@@ -1253,7 +1252,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
if (!Environment.IsWinRTSupported)
{
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
return HStringToString(ptr);
@@ -1262,7 +1261,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public static void FreeHString(IntPtr ptr)
{
if (!Environment.IsWinRTSupported)
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (ptr != IntPtr.Zero)
{
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
index f097c6a0db..0f28d3b080 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMetadata.cs
@@ -4,22 +4,22 @@
//
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics.Contracts;
+using System.Reflection;
+using System.Reflection.Emit;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.Runtime.InteropServices.WindowsRuntime
{
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Diagnostics.Contracts;
- using System.Reflection;
- using System.Reflection.Emit;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Security;
-
internal static class WindowsRuntimeMetadata
{
private static EventHandler<DesignerNamespaceResolveEventArgs> DesignerNamespaceResolve;
-
+
internal static string[] OnDesignerNamespaceResolveEvent(AppDomain appDomain, string namespaceName)
{
EventHandler<DesignerNamespaceResolveEventArgs> eventHandler = DesignerNamespaceResolve;
@@ -42,7 +42,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
{
if (String.IsNullOrEmpty(assemblyFile))
{ // DesignerNamespaceResolve event returned null or empty file name - that is not allowed
- throw new ArgumentException(Environment.GetResourceString("Arg_EmptyOrNullString"), "DesignerNamespaceResolveEventArgs.ResolvedAssemblyFiles");
+ throw new ArgumentException(SR.Arg_EmptyOrNullString, "DesignerNamespaceResolveEventArgs.ResolvedAssemblyFiles");
}
retAssemblyFiles[retIndex] = assemblyFile;
retIndex++;
@@ -52,50 +52,11 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
}
}
-
+
return null;
}
}
-
-#if FEATURE_REFLECTION_ONLY_LOAD
- public class NamespaceResolveEventArgs : EventArgs
- {
- private string _NamespaceName;
- private Assembly _RequestingAssembly;
- private Collection<Assembly> _ResolvedAssemblies;
-
- public string NamespaceName
- {
- get
- {
- return _NamespaceName;
- }
- }
-
- public Assembly RequestingAssembly
- {
- get
- {
- return _RequestingAssembly;
- }
- }
- public Collection<Assembly> ResolvedAssemblies
- {
- get
- {
- return _ResolvedAssemblies;
- }
- }
-
- public NamespaceResolveEventArgs(string namespaceName, Assembly requestingAssembly)
- {
- _NamespaceName = namespaceName;
- _RequestingAssembly = requestingAssembly;
- _ResolvedAssemblies = new Collection<Assembly>();
- }
- }
-#endif //FEATURE_REFLECTION_ONLY
internal class DesignerNamespaceResolveEventArgs : EventArgs
{
diff --git a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
index 2be8b13274..de8137f1ec 100644
--- a/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
+++ b/src/mscorlib/src/System/Runtime/Loader/AssemblyLoadContext.cs
@@ -18,19 +18,18 @@ namespace System.Runtime.Loader
{
public abstract class AssemblyLoadContext
{
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
@@ -50,8 +49,8 @@ namespace System.Runtime.Loader
// Initialize the ALC representing TPA LoadContext
InitializeLoadContext(fRepresentsTPALoadContext);
}
-
- void InitializeLoadContext(bool fRepresentsTPALoadContext)
+
+ private void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
@@ -75,14 +74,14 @@ namespace System.Runtime.Loader
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies);
-
+
public static Assembly[] GetLoadedAssemblies()
{
Assembly[] assemblies = null;
GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies));
return assemblies;
}
-
+
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
public Assembly LoadFromAssemblyPath(string assemblyPath)
@@ -94,14 +93,14 @@ namespace System.Runtime.Loader
if (PathInternal.IsPartiallyQualified(assemblyPath))
{
- throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
-
+
public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
@@ -111,12 +110,12 @@ namespace System.Runtime.Loader
if (PathInternal.IsPartiallyQualified(nativeImagePath))
{
- throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(nativeImagePath));
}
if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(assemblyPath));
}
// Basic validation has succeeded - lets try to load the NI image.
@@ -125,74 +124,79 @@ namespace System.Runtime.Loader
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
-
+
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
-
+
public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
-
+
+ if (assembly.Length <= 0)
+ {
+ throw new BadImageFormatException(SR.BadImageFormat_BadILFormat);
+ }
+
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
-
+
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
-
+
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
-
+
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
-
+
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
-
+
RuntimeAssembly loadedAssembly = null;
- unsafe
+ unsafe
{
- fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
+ fixed (byte* ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
-
+
return loadedAssembly;
}
-
+
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
-
+
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
-
+
return context.ResolveUsingLoad(assemblyName);
}
-
+
// This method is invoked by the VM to resolve an assembly reference using the Resolving event
// after trying assembly resolution via Load override and TPA load context without success.
private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
-
+
// Invoke the AssemblyResolve event callbacks if wired up
return context.ResolveUsingEvent(assemblyName);
}
-
+
private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName)
{
Assembly resolvedAssembly = null;
@@ -202,8 +206,8 @@ namespace System.Runtime.Loader
if (assemblyResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
- Delegate [] arrSubscribers = assemblyResolveHandler.GetInvocationList();
- for(int i = 0; i < arrSubscribers.Length; i++)
+ Delegate[] arrSubscribers = assemblyResolveHandler.GetInvocationList();
+ for (int i = 0; i < arrSubscribers.Length; i++)
{
resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName);
if (resolvedAssembly != null)
@@ -212,7 +216,7 @@ namespace System.Runtime.Loader
}
}
}
-
+
return resolvedAssembly;
}
@@ -220,7 +224,7 @@ namespace System.Runtime.Loader
{
// Get the name of the loaded assembly
string loadedSimpleName = null;
-
+
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
@@ -229,49 +233,48 @@ namespace System.Runtime.Loader
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
-
+
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
- throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch"));
-
+ throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch);
+
return assembly;
-
}
-
+
private Assembly ResolveUsingLoad(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
-
+
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
-
+
return assembly;
}
-
+
private Assembly ResolveUsingEvent(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
-
+
// Invoke the AssemblyResolve event callbacks if wired up
Assembly assembly = GetFirstResolvedAssembly(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
-
+
// Since attempt to resolve the assembly via Resolving event is the last option,
// throw an exception if we do not find any assembly.
if (assembly == null)
{
- throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), simpleName);
+ throw new FileNotFoundException(SR.IO_FileLoad, simpleName);
}
-
+
return assembly;
}
-
+
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
@@ -294,23 +297,23 @@ namespace System.Runtime.Loader
}
if (unmanagedDllPath.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(unmanagedDllPath));
+ throw new ArgumentException(SR.Argument_EmptyPath, nameof(unmanagedDllPath));
}
if (PathInternal.IsPartiallyQualified(unmanagedDllPath))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(unmanagedDllPath));
+ throw new ArgumentException(SR.Argument_AbsolutePathRequired, nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
-
+
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
- return IntPtr.Zero;
+ return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
@@ -331,7 +334,7 @@ namespace System.Runtime.Loader
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
// Synchronize access to initializing Default ALC
- lock(s_initLock)
+ lock (s_initLock)
{
if (s_DefaultAssemblyLoadContext == null)
{
@@ -340,16 +343,11 @@ namespace System.Runtime.Loader
}
}
}
-
+
return s_DefaultAssemblyLoadContext;
}
}
-
- // This call opens and closes the file, but does not add the
- // assembly to the domain.
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static internal extern AssemblyName nGetFileInformation(String s);
-
+
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
@@ -358,14 +356,13 @@ namespace System.Runtime.Loader
throw new ArgumentNullException(nameof(assemblyPath));
}
- string fullPath = Path.GetFullPath(assemblyPath);
- return nGetFileInformation(fullPath);
+ return AssemblyName.GetAssemblyName(assemblyPath);
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
-
+
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
@@ -373,11 +370,11 @@ namespace System.Runtime.Loader
{
throw new ArgumentNullException(nameof(assembly));
}
-
+
AssemblyLoadContext loadContextForAssembly = null;
RuntimeAssembly rtAsm = assembly as RuntimeAssembly;
-
+
// We only support looking up load context for runtime assemblies.
if (rtAsm != null)
{
@@ -397,7 +394,7 @@ namespace System.Runtime.Loader
return loadContextForAssembly;
}
-
+
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
@@ -424,7 +421,7 @@ namespace System.Runtime.Loader
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
-
+
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
@@ -434,36 +431,36 @@ namespace System.Runtime.Loader
private static readonly object s_initLock = new Object();
// Occurs when an Assembly is loaded
- public static event AssemblyLoadEventHandler AssemblyLoad
- {
- add { AppDomain.CurrentDomain.AssemblyLoad += value; }
- remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
+ public static event AssemblyLoadEventHandler AssemblyLoad
+ {
+ add { AppDomain.CurrentDomain.AssemblyLoad += value; }
+ remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
}
// Occurs when resolution of type fails
- public static event ResolveEventHandler TypeResolve
- {
- add { AppDomain.CurrentDomain.TypeResolve += value; }
- remove { AppDomain.CurrentDomain.TypeResolve -= value; }
+ public static event ResolveEventHandler TypeResolve
+ {
+ add { AppDomain.CurrentDomain.TypeResolve += value; }
+ remove { AppDomain.CurrentDomain.TypeResolve -= value; }
}
// Occurs when resolution of resource fails
- public static event ResolveEventHandler ResourceResolve
- {
- add { AppDomain.CurrentDomain.ResourceResolve += value; }
- remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
- }
+ public static event ResolveEventHandler ResourceResolve
+ {
+ add { AppDomain.CurrentDomain.ResourceResolve += value; }
+ remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
+ }
// Occurs when resolution of assembly fails
// This event is fired after resolve events of AssemblyLoadContext fails
public static event ResolveEventHandler AssemblyResolve
{
- add { AppDomain.CurrentDomain.AssemblyResolve += value; }
- remove { AppDomain.CurrentDomain.AssemblyResolve -= value; }
+ add { AppDomain.CurrentDomain.AssemblyResolve += value; }
+ remove { AppDomain.CurrentDomain.AssemblyResolve -= value; }
}
}
- class AppPathAssemblyLoadContext : AssemblyLoadContext
+ internal class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
index 84b8ba9e1e..f9f87bc928 100644
--- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
+++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
@@ -139,7 +139,7 @@ namespace System.Runtime
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
-
+
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
@@ -155,7 +155,7 @@ namespace System.Runtime
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
- throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(sizeInMegabytes), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
#if !FEATURE_PAL // Remove this when CheckForAvailableMemory is able to provide legitimate estimates
@@ -168,9 +168,9 @@ namespace System.Runtime
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
- ulong segmentSize = (ulong) (Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
+ ulong segmentSize = (ulong)(Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
if (segmentSize >= TopOfMemory)
- throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_TooBig"));
+ throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig);
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
@@ -191,7 +191,8 @@ namespace System.Runtime
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
- for(int stage = 0; stage < 3; stage++) {
+ for (int stage = 0; stage < 3; stage++)
+ {
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
@@ -206,99 +207,109 @@ namespace System.Runtime
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
- LastKnownFreeAddressSpace < (long) segmentSize) {
+ LastKnownFreeAddressSpace < (long)segmentSize)
+ {
CheckForFreeAddressSpace(segmentSize, false);
}
- bool needContiguousVASpace = (ulong) LastKnownFreeAddressSpace < segmentSize;
+ bool needContiguousVASpace = (ulong)LastKnownFreeAddressSpace < segmentSize;
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB",
- segmentSize >> 20, sizeInMegabytes, needPageFile,
- needAddressSpace, needContiguousVASpace,
- availPageFile >> 20, totalAddressSpaceFree >> 20,
+ segmentSize >> 20, sizeInMegabytes, needPageFile,
+ needAddressSpace, needContiguousVASpace,
+ availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved, stage);
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
- switch(stage) {
- case 0:
- // The GC will release empty segments to the OS. This will
- // relieve us from having to guess whether there's
- // enough memory in either GC heap, and whether
- // internal fragmentation will prevent those
- // allocations from succeeding.
- GC.Collect();
- continue;
-
- case 1:
- // Do this step if and only if the page file is too small.
- if (!needPageFile)
+ switch (stage)
+ {
+ case 0:
+ // The GC will release empty segments to the OS. This will
+ // relieve us from having to guess whether there's
+ // enough memory in either GC heap, and whether
+ // internal fragmentation will prevent those
+ // allocations from succeeding.
+ GC.Collect();
continue;
- // 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 {
- 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();
+ case 1:
+ // Do this step if and only if the page file is too small.
+ if (!needPageFile)
+ continue;
+
+ // 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
+ {
+ 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();
+ }
}
}
- }
- continue;
-
- case 2:
- // The call to CheckForAvailableMemory above updated our
- // state.
- if (needPageFile || needAddressSpace) {
- InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint"));
+ continue;
+
+ case 2:
+ // The call to CheckForAvailableMemory above updated our
+ // state.
+ if (needPageFile || needAddressSpace)
+ {
+ InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint);
#if _DEBUG
- e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
- needPageFile, needAddressSpace, needContiguousVASpace,
- availPageFile >> 20, totalAddressSpaceFree >> 20,
- LastKnownFreeAddressSpace >> 20, reserved);
+ e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
+ needPageFile, needAddressSpace, needContiguousVASpace,
+ availPageFile >> 20, totalAddressSpaceFree >> 20,
+ LastKnownFreeAddressSpace >> 20, reserved);
#endif
- throw e;
- }
+ throw e;
+ }
- if (needContiguousVASpace) {
- InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"));
+ if (needContiguousVASpace)
+ {
+ InsufficientMemoryException e = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
#if _DEBUG
- e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
- needPageFile, needAddressSpace, needContiguousVASpace,
- availPageFile >> 20, totalAddressSpaceFree >> 20,
- LastKnownFreeAddressSpace >> 20, reserved);
+ e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
+ needPageFile, needAddressSpace, needContiguousVASpace,
+ availPageFile >> 20, totalAddressSpaceFree >> 20,
+ LastKnownFreeAddressSpace >> 20, reserved);
#endif
- throw e;
- }
+ throw e;
+ }
- break;
+ break;
- default:
- Debug.Assert(false, "Fell through switch statement!");
- break;
+ default:
+ Debug.Assert(false, "Fell through switch statement!");
+ break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
- AddToLastKnownFreeAddressSpace(-((long) size));
+ AddToLastKnownFreeAddressSpace(-((long)size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
-
+
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
}
- finally {
- SharedStatics.AddMemoryFailPointReservation((long) size);
+ finally
+ {
+ SharedStatics.AddMemoryFailPointReservation((long)size);
_mustSubtractReservation = true;
}
#endif
@@ -334,11 +345,11 @@ namespace System.Runtime
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
- LastKnownFreeAddressSpace = (long) freeSpaceAfterGCHeap;
+ LastKnownFreeAddressSpace = (long)freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
- throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"));
+ throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag);
return freeSpaceAfterGCHeap >= size;
}
@@ -346,28 +357,30 @@ namespace System.Runtime
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
- private static unsafe ulong MemFreeAfterAddress(void * address, ulong size)
+ private static unsafe ulong MemFreeAfterAddress(void* address, ulong size)
{
if (size >= TopOfMemory)
return 0;
ulong largestFreeRegion = 0;
Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
- UIntPtr sizeOfMemInfo = (UIntPtr) Marshal.SizeOf(memInfo);
-
- while (((ulong)address) + size < TopOfMemory) {
+ UIntPtr sizeOfMemInfo = (UIntPtr)Marshal.SizeOf(memInfo);
+
+ while (((ulong)address) + size < TopOfMemory)
+ {
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
__Error.WinIOError();
ulong regionSize = memInfo.RegionSize.ToUInt64();
- if (memInfo.State == Win32Native.MEM_FREE) {
+ if (memInfo.State == Win32Native.MEM_FREE)
+ {
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
- address = (void *) ((ulong) address + regionSize);
+ address = (void*)((ulong)address + regionSize);
}
return largestFreeRegion;
}
@@ -398,11 +411,14 @@ namespace System.Runtime
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
- if (_mustSubtractReservation) {
+ if (_mustSubtractReservation)
+ {
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
}
- finally {
+ finally
+ {
SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
@@ -465,9 +481,9 @@ namespace System.Runtime
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
- _segmentSize >> 20, _allocationSizeInMB, _needPageFile,
- _needAddressSpace, _needContiguousVASpace,
- _availPageFile >> 20, _totalFreeAddressSpace >> 20,
+ _segmentSize >> 20, _allocationSizeInMB, _needPageFile,
+ _needAddressSpace, _needContiguousVASpace,
+ _availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
}
diff --git a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
index 67c934d034..6594562b97 100644
--- a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
+++ b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
@@ -16,11 +16,12 @@
**
**
===========================================================*/
+
+using System;
+using System.Runtime.InteropServices;
+
namespace System.Runtime.ConstrainedExecution
{
- using System;
- using System.Runtime.InteropServices;
-
[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
internal sealed class PrePrepareMethodAttribute : Attribute
diff --git a/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs b/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs
deleted file mode 100644
index 4a14e5733c..0000000000
--- a/src/mscorlib/src/System/Runtime/Reliability/ReliabilityContractAttribute.cs
+++ /dev/null
@@ -1,67 +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: Defines a publically documentable contract for
-** reliability between a method and its callers, expressing
-** what state will remain consistent in the presence of
-** failures (ie async exceptions like thread abort) and whether
-** the method needs to be called from within a CER.
-**
-**
-===========================================================*/
-
-namespace System.Runtime.ConstrainedExecution {
- using System.Runtime.InteropServices;
- using System;
-
- // **************************************************************************************************************************
- //
- // Note that if you change either of the enums below or the constructors, fields or properties of the custom attribute itself
- // you must also change the logic and definitions in vm\ConstrainedExecutionRegion.cpp to match.
- //
- // **************************************************************************************************************************
-
- [Serializable]
- public enum Consistency : int
- {
- MayCorruptProcess = 0,
- MayCorruptAppDomain = 1,
- MayCorruptInstance = 2,
- WillNotCorruptState = 3,
- }
-
- [Serializable]
- public enum Cer : int
- {
- None = 0,
- MayFail = 1, // Might fail, but the method will say it failed
- Success = 2,
- }
-
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Interface /* | AttributeTargets.Delegate*/, Inherited = false)]
- public sealed class ReliabilityContractAttribute : Attribute
- {
- private Consistency _consistency;
- private Cer _cer;
-
- public ReliabilityContractAttribute(Consistency consistencyGuarantee, Cer cer)
- {
- _consistency = consistencyGuarantee;
- _cer = cer;
- }
-
- public Consistency ConsistencyGuarantee {
- get { return _consistency; }
- }
-
- public Cer Cer {
- get { return _cer; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
index ed3444e15d..e76882d6df 100644
--- a/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
+++ b/src/mscorlib/src/System/Runtime/Remoting/ObjectHandle.cs
@@ -14,15 +14,15 @@
**
===========================================================*/
+using System;
+using System.Runtime.InteropServices;
+
namespace System.Runtime.Remoting
{
- using System;
- using System.Runtime.InteropServices;
-
- public class ObjectHandle
+ public class ObjectHandle
{
private Object WrappedObject;
-
+
private ObjectHandle()
{
}
diff --git a/src/mscorlib/src/System/Runtime/RuntimeImports.cs b/src/mscorlib/src/System/Runtime/RuntimeImports.cs
new file mode 100644
index 0000000000..16d41d3951
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/RuntimeImports.cs
@@ -0,0 +1,35 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+#if BIT64
+using nuint = System.UInt64;
+#else
+ using nuint = System.UInt32;
+#endif
+
+namespace System.Runtime
+{
+ public class RuntimeImports
+ {
+ // Non-inlinable wrapper around the QCall that avoids poluting the fast path
+ // with P/Invoke prolog/epilog.
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ internal unsafe static void RhZeroMemory(ref byte b, nuint byteLength)
+ {
+ fixed (byte* bytePointer = &b)
+ {
+ RhZeroMemory(bytePointer, byteLength);
+ }
+ }
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ extern private unsafe static void RhZeroMemory(byte* b, nuint byteLength);
+
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal extern unsafe static void RhBulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount);
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
index 27f7ecf9d2..52e748db89 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterConverter.cs
@@ -12,42 +12,53 @@
**
**
============================================================*/
-namespace System.Runtime.Serialization {
- using System;
- using System.Globalization;
- using System.Diagnostics.Contracts;
- internal class FormatterConverter : IFormatterConverter {
+using System;
+using System.Globalization;
+using System.Diagnostics.Contracts;
- public FormatterConverter() {
+namespace System.Runtime.Serialization
+{
+ internal class FormatterConverter : IFormatterConverter
+ {
+ public FormatterConverter()
+ {
}
- public Object Convert(Object value, Type type) {
- if (value==null) {
+ public Object Convert(Object value, Type type)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
- public Object Convert(Object value, TypeCode typeCode) {
- if (value==null) {
+ public Object Convert(Object value, TypeCode typeCode)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ChangeType(value, typeCode, CultureInfo.InvariantCulture);
}
- public bool ToBoolean(Object value) {
- if (value==null) {
+ public bool ToBoolean(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);
}
- public char ToChar(Object value) {
- if (value==null) {
+ public char ToChar(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -55,24 +66,30 @@ namespace System.Runtime.Serialization {
}
[CLSCompliant(false)]
- public sbyte ToSByte(Object value) {
- if (value==null) {
+ public sbyte ToSByte(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToSByte(value, CultureInfo.InvariantCulture);
}
- public byte ToByte(Object value) {
- if (value==null) {
+ public byte ToByte(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToByte(value, CultureInfo.InvariantCulture);
}
- public short ToInt16(Object value) {
- if (value==null) {
+ public short ToInt16(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -80,16 +97,20 @@ namespace System.Runtime.Serialization {
}
[CLSCompliant(false)]
- public ushort ToUInt16(Object value) {
- if (value==null) {
+ public ushort ToUInt16(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt16(value, CultureInfo.InvariantCulture);
}
- public int ToInt32(Object value) {
- if (value==null) {
+ public int ToInt32(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -97,16 +118,20 @@ namespace System.Runtime.Serialization {
}
[CLSCompliant(false)]
- public uint ToUInt32(Object value) {
- if (value==null) {
+ public uint ToUInt32(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt32(value, CultureInfo.InvariantCulture);
}
- public long ToInt64(Object value) {
- if (value==null) {
+ public long ToInt64(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -114,48 +139,60 @@ namespace System.Runtime.Serialization {
}
[CLSCompliant(false)]
- public ulong ToUInt64(Object value) {
- if (value==null) {
+ public ulong ToUInt64(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToUInt64(value, CultureInfo.InvariantCulture);
- }
+ }
- public float ToSingle(Object value) {
- if (value==null) {
+ public float ToSingle(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToSingle(value, CultureInfo.InvariantCulture);
}
- public double ToDouble(Object value) {
- if (value==null) {
+ public double ToDouble(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDouble(value, CultureInfo.InvariantCulture);
}
- public Decimal ToDecimal(Object value) {
- if (value==null) {
+ public Decimal ToDecimal(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDecimal(value, CultureInfo.InvariantCulture);
}
- public DateTime ToDateTime(Object value) {
- if (value==null) {
+ public DateTime ToDateTime(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
return System.Convert.ToDateTime(value, CultureInfo.InvariantCulture);
}
- public String ToString(Object value) {
- if (value==null) {
+ public String ToString(Object value)
+ {
+ if (value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -163,4 +200,4 @@ namespace System.Runtime.Serialization {
}
}
}
-
+
diff --git a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
index c3f9eb4452..18139324a3 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/FormatterServices.cs
@@ -11,25 +11,28 @@
**
**
============================================================*/
-namespace System.Runtime.Serialization {
-
- using System;
- using System.Reflection;
- using System.Collections;
- using System.Collections.Generic;
- using System.Security;
- using System.Runtime.Remoting;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Threading;
- using System.IO;
- using System.Text;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- public static class FormatterServices {
-
+using System;
+using System.Reflection;
+using System.Collections;
+using System.Collections.Generic;
+using System.Security;
+using System.Runtime.Remoting;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Threading;
+using System.IO;
+using System.Text;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Runtime.Serialization
+{
+ // This class duplicates a class on CoreFX. We are keeping it here -- just this one method --
+ // as it was widely invoked by reflection to workaround it being missing in .NET Core 1.0
+ internal static class FormatterServices
+ {
// Gets a new instance of the object. The entire object is initalized to 0 and no
// constructors have been run. **THIS MEANS THAT THE OBJECT MAY NOT BE IN A STATE
// CONSISTENT WITH ITS INTERNAL REQUIREMENTS** This method should only be used for
@@ -37,42 +40,24 @@ namespace System.Runtime.Serialization {
// will not create an unitialized string because it is non-sensical to create an empty
// instance of an immutable type.
//
- public static Object GetUninitializedObject(Type type) {
- if ((object)type == null) {
+ public static Object GetUninitializedObject(Type type)
+ {
+ if ((object)type == null)
+ {
throw new ArgumentNullException(nameof(type));
}
Contract.EndContractBlock();
-
- if (!(type is RuntimeType)) {
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidType", type.ToString()));
+
+ if (!(type is RuntimeType))
+ {
+ throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type.ToString()));
}
return nativeGetUninitializedObject((RuntimeType)type);
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object nativeGetUninitializedObject(RuntimeType type);
- private static Binder s_binder = Type.DefaultBinder;
-
- /*============================LoadAssemblyFromString============================
- **Action: Loads an assembly from a given string. The current assembly loading story
- ** is quite confusing. If the assembly is in the fusion cache, we can load it
- ** using the stringized-name which we transmitted over the wire. If that fails,
- ** we try for a lookup of the assembly using the simple name which is the first
- ** part of the assembly name. If we can't find it that way, we'll return null
- ** as our failure result.
- **Returns: The loaded assembly or null if it can't be found.
- **Arguments: assemblyName -- The stringized assembly name.
- **Exceptions: None
- ==============================================================================*/
- internal static Assembly LoadAssemblyFromString(String assemblyName) {
- //
- // Try using the stringized assembly name to load from the fusion cache.
- //
- BCLDebug.Trace("SER", "[LoadAssemblyFromString]Looking for assembly: ", assemblyName);
- Assembly found = Assembly.Load(assemblyName);
- return found;
- }
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs b/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
deleted file mode 100644
index 2911a4016e..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/IDeserializationCallback.cs
+++ /dev/null
@@ -1,22 +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.
-
-/*============================================================
-**
-** Interface: IDeserializationEventListener
-**
-**
-** Purpose: Implemented by any class that wants to indicate that
-** it wishes to receive deserialization events.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
- using System;
-
- // Interface does not need to be marked with the serializable attribute
- public interface IDeserializationCallback {
- void OnDeserialization(Object sender);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs b/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
deleted file mode 100644
index 0be0db9acd..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/IFormatterConverter.cs
+++ /dev/null
@@ -1,39 +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 interface provides the connection between an
-** instance of SerializationInfo and the formatter-provided
-** class which knows how to parse the data inside the
-** SerializationInfo.
-**
-**
-============================================================*/
-namespace System.Runtime.Serialization {
- using System;
-
- [CLSCompliant(false)]
- public interface IFormatterConverter {
- Object Convert(Object value, Type type);
- Object Convert(Object value, TypeCode typeCode);
- bool ToBoolean(Object value);
- char ToChar(Object value);
- sbyte ToSByte(Object value);
- byte ToByte(Object value);
- short ToInt16(Object value);
- ushort ToUInt16(Object value);
- int ToInt32(Object value);
- uint ToUInt32(Object value);
- long ToInt64(Object value);
- ulong ToUInt64(Object value);
- float ToSingle(Object value);
- double ToDouble(Object value);
- Decimal ToDecimal(Object value);
- DateTime ToDateTime(Object value);
- String ToString(Object value);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs b/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
deleted file mode 100644
index ef5ee6ade0..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/IObjectReference.cs
+++ /dev/null
@@ -1,27 +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.
-
-/*============================================================
-**
-** Interface: IObjectReference
-**
-**
-** Purpose: Implemented by objects that are actually references
-** to a different object which can't be discovered until
-** this one is completely restored. During the fixup stage,
-** any object implementing IObjectReference is asked for it's
-** "real" object and that object is inserted into the graph.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
-
- using System;
- // Interface does not need to be marked with the serializable attribute
- public interface IObjectReference {
- Object GetRealObject(StreamingContext context);
- }
-}
-
-
diff --git a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs b/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
deleted file mode 100644
index 816aa0484b..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/ISerializable.cs
+++ /dev/null
@@ -1,30 +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.
-
-/*============================================================
-**
-** Interface: ISerializable
-**
-**
-** Purpose: Implemented by any object that needs to control its
-** own serialization.
-**
-**
-===========================================================*/
-
-namespace System.Runtime.Serialization {
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System;
- using System.Reflection;
-
- public interface ISerializable {
- void GetObjectData(SerializationInfo info, StreamingContext context);
- }
-
-}
-
-
-
-
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs b/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
deleted file mode 100644
index 260e873bc7..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/SafeSerializationManager.cs
+++ /dev/null
@@ -1,240 +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.Collections;
-using System.Collections.Generic;
-using System.Diagnostics.Contracts;
-using System.Reflection;
-using System.Security;
-
-namespace System.Runtime.Serialization
-{
- //
- // #SafeSerialization
- //
- // Types which are serializable via the ISerializable interface have a problem when it comes to allowing
- // transparent subtypes which can allow themselves to serialize since the GetObjectData method is
- // SecurityCritical.
- //
- // For instance, System.Exception implements ISerializable, however it is also desirable to have
- // transparent exceptions with their own fields that need to be serialized. (For instance, in transparent
- // assemblies such as the DLR and F#, or even in partial trust application code). Since overriding
- // GetObjectData requires that the overriding method be security critical, this won't work directly.
- //
- // SafeSerializationManager solves this problem by allowing any partial trust code to contribute
- // individual chunks of serializable data to be included in the serialized version of the derived class.
- // These chunks are then deserialized back out of the serialized type and notified that they should
- // populate the fields of the deserialized object when serialization is complete. This allows partial
- // trust or transparent code to participate in serialization of an ISerializable type without having to
- // override GetObjectData or implement the ISerializable constructor.
- //
- // On the serialization side, SafeSerializationManager has an event SerializeObjectState which it will
- // fire in response to serialization in order to gather the units of serializable data that should be
- // stored with the rest of the object during serialization. Methods which respond to these events
- // create serializable objects which implement the ISafeSerializationData interface and add them to the
- // collection of other serialized data by calling AddSerializedState on the SafeSerializationEventArgs
- // passed into the event.
- //
- // By using an event rather than a virtual method on the base ISerializable object, we allow multiple
- // potentially untrusted subclasses to participate in serialization, without each one having to ensure
- // that it calls up to the base type in order for the whole system to work. (For instance Exception :
- // TrustedException : UntrustedException, in this scenario UntrustedException would be able to override
- // the virtual method an prevent TrustedException from ever seeing the method call, either accidentally
- // or maliciously).
- //
- // Further, by only allowing additions of new chunks of serialization state rather than exposing the
- // whole underlying list, we avoid exposing potentially sensitive serialized state to any of the
- // potentially untrusted subclasses.
- //
- // At deserialization time, SafeSerializationManager performs the reverse operation. It deserializes the
- // chunks of serialized state, and then notifies them that the object they belong to is deserialized by
- // calling their CompleteSerialization method. In repsonse to this call, the state objects populate the
- // fields of the object being deserialized with the state that they held.
- //
- // From a security perspective, the chunks of serialized state can only contain data that the specific
- // subclass itself had access to read (otherwise it wouldn't be able to populate the type with that
- // data), as opposed to having access to far more data in the SerializationInfo that GetObjectData uses.
- // Similarly, at deserialization time, the serialized state can only modify fields that the type itself
- // has access to (again, as opposed to the full SerializationInfo which could be modified).
- //
- // Individual types which wish to participate in safe serialization do so by containing an instance of a
- // SafeSerializationManager and exposing its serialization event. During GetObjectData, the
- // SafeSerializationManager is serialized just like any other field of the containing type. However, at
- // the end of serialization it is called back one last time to CompleteSerialization.
- //
- // In CompleteSerialization, if the SafeSerializationManager detects that it has extra chunks of
- // data to handle, it substitutes the root type being serialized (formerly the real type hosting the
- // SafeSerializationManager) with itself. This allows it to gain more control over the deserialization
- // process. It also saves away an extra bit of state in the serialization info indicating the real type
- // of object that should be recreated during deserialization.
- //
- // At this point the serialized state looks like this:
- // Data:
- // realSerializedData1
- // ...
- // realSerializedDataN
- // safeSerializationData -> this is the serialization data member of the parent type
- // m_serializedState -> list of saved serialized states from subclasses responding to the safe
- // serialization event
- // RealTypeSerializationName -> type which is using safe serialization
- // Type:
- // SafeSerializationManager
- //
- // That is, the serialized data claims to be of type SafeSerializationManager, however contains only the
- // data from the real object being serialized along with one bit of safe serialization metadata.
- //
- // At deserialization time, since the serialized data claims to be of type SafeSerializationManager, the
- // root object being created is an instance of the SafeSerializationManager class. However, it detects
- // that this isn't a real SafeSerializationManager (by looking for the real type field in the metadata),
- // and simply saves away the SerializationInfo and the real type being deserialized.
- //
- // Since SafeSerializationManager implements IObjectReference, the next step of deserialization is the
- // GetRealObject callback. This callback is the one responsible for getting the
- // SafeSerializationManager out of the way and instead creating an instance of the actual type which was
- // serialized.
- //
- // It does this by first creating an instance of the real type being deserialzed (saved away in the
- // deserialzation constructor), but not running any of its constructors. Instead, it walks the
- // inheritance hierarchy (moving toward the most derived type) looking for the last full trust type to
- // implement the standard ISerializable constructor before any type does not implement the constructor.
- // It is this last type's deserialization constructor which is then invoked, passing in the saved
- // SerializationInfo. Once the constructors are run, we return this object as the real deserialized
- // object.
- //
- // The reason that we do this walk is so that ISerializable types can protect themselves from malicious
- // input during deserialization by making their deserialization constructors unavailable to partial
- // trust code. By not requiring every type have a copy of this constructor, partial trust code can
- // participate in safe serialization and not be required to have access to the parent's constructor.
- //
- // It should be noted however, that this heuristic means that if a full trust type does derive from
- // a transparent or partial trust type using this safe serialization mechanism, that full trust type
- // will not have its constructor called. Further, the protection of not invoking partial trust
- // deserialization constructors only comes into play if SafeSerializationManager is in control of
- // deserialization, which means there must be at least one (even empty) safe serialization event
- // handler registered.
- //
- // Another interesting note is that at this point there are now two SafeSerializationManagers alive for
- // this deserialization. The first object is the one which is controlling the deserialization and was
- // created as the root object of the deserialization. The second one is the object which contains the
- // serialized data chunks and is a data member of the real object being deserialized. For this reason,
- // the data objects cannot be notified that the deserialization is complete during GetRealObject since
- // the ISafeSerializationData objects are not members of the active SafeSerializationManager instance.
- //
- // The next step is the OnDeserialized callback, which comes to SafeSerializableObject since it was
- // pretending to be the root object of the deserialization. It responds to this callback by calling
- // any existing OnDeserialized callback on the real type that was deserialized.
- //
- // The real type needs to call its data member SafeSerializationData object's CompleteDeserialization
- // method in response to the OnDeserialized call. This CompleteDeserialization call will then iterate
- // through the ISafeSerializationData objects calling each of their CompleteDeserialization methods so
- // that they can plug the nearly-complete object with their saved data.
- //
- // The reason for having a new ISafeSerializationData interface which is basically identical to
- // IDeserializationCallback is that IDeserializationCallback will be called on the stored data chunks
- // by the serialization code when they are deserialized, and that's not a desirable behavior.
- // Essentially, we need to change the meaning of the object parameter to mean "parent object which
- // participated in safe serialization", rather than "this object".
- //
- // Implementing safe serialization on an ISerialiable type is relatively straight forward. (For an
- // example, see System.Exception):
- //
- // 1. Include a data member of type SafeSerializationManager:
- //
- // private SafeSerializationManager m_safeSerializationManager;
- //
- // 2. Add a protected SerializeObjectState event, which passes through to the SafeSerializationManager:
- //
- // protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState
- // {
- // add { m_safeSerializationManager.SerializeObjectState += value; }
- // remove { m_safeSerializationManager.SerializeObjectState -= value; }
- // }
- //
- // 3. Serialize the safe serialization object in GetObjectData, and call its CompleteSerialization method:
- //
- // {
- // info.AddValue("m_safeSerializationManager", m_safeSerializationManager, typeof(SafeSerializationManager));
- // m_safeSerializationManager.CompleteSerialization(this, info, context);
- // }
- //
- // 4. Add an OnDeserialized handler if one doesn't already exist, and call CompleteDeserialization in it:
- //
- // [OnDeserialized]
- // private void OnDeserialized(StreamingContext context)
- // {
- // m_safeSerializationManager.CompleteDeserialization(this);
- // }
- //
- // On the client side, using safe serialization is also pretty easy. For example:
- //
- // [Serializable]
- // public class TransparentException : Exception
- // {
- // [Serializable]
- // private struct TransparentExceptionState : ISafeSerializationData
- // {
- // public string m_extraData;
- //
- // void ISafeSerializationData.CompleteDeserialization(object obj)
- // {
- // TransparentException exception = obj as TransparentException;
- // exception.m_state = this;
- // }
- // }
- //
- // [NonSerialized]
- // private TransparentExceptionState m_state = new TransparentExceptionState();
- //
- // public TransparentException()
- // {
- // SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs)
- // {
- // eventArgs.AddSerializedState(m_state);
- // };
- // }
- //
- // public string ExtraData
- // {
- // get { return m_state.m_extraData; }
- // set { m_state.m_extraData = value; }
- // }
- // }
- //
-
- // SafeSerializationEventArgs are provided to the delegates which do safe serialization. Each delegate
- // serializes its own state into an IDeserializationCallback instance which must, itself, be serializable.
- // These indivdiual states are then added to the SafeSerializationEventArgs in order to be saved away when
- // the original ISerializable type is serialized.
- public sealed class SafeSerializationEventArgs : EventArgs
- {
- private StreamingContext m_streamingContext;
- private List<object> m_serializedStates = new List<object>();
-
- internal SafeSerializationEventArgs() {}
-
- public void AddSerializedState(ISafeSerializationData serializedState)
- {
- if (serializedState == null)
- throw new ArgumentNullException(nameof(serializedState));
- if (!serializedState.GetType().IsSerializable)
- throw new ArgumentException(Environment.GetResourceString("Serialization_NonSerType", serializedState.GetType(), serializedState.GetType().Assembly.FullName));
-
- m_serializedStates.Add(serializedState);
- }
-
- public StreamingContext StreamingContext
- {
- get { return m_streamingContext; }
- }
- }
-
- // Interface to be supported by objects which are stored in safe serialization stores
- public interface ISafeSerializationData
- {
- // CompleteDeserialization is called when the object to which the extra serialized data was attached
- // has completed its deserialization, and now needs to be populated with the extra data stored in
- // this object.
- void CompleteDeserialization(object deserialized);
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
deleted file mode 100644
index 38abffa66e..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationAttributes.cs
+++ /dev/null
@@ -1,59 +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: Various Attributes for Serialization
-**
-**
-============================================================*/
-namespace System.Runtime.Serialization
-{
- using System;
- using System.Diagnostics.Contracts;
- using System.Reflection;
-
- [AttributeUsage(AttributeTargets.Field, Inherited=false)]
- public sealed class OptionalFieldAttribute : Attribute
- {
- int versionAdded = 1;
- public OptionalFieldAttribute() { }
-
- public int VersionAdded
- {
- get {
- return this.versionAdded;
- }
- set {
- if (value < 1)
- throw new ArgumentException(Environment.GetResourceString("Serialization_OptionalFieldVersionValue"));
- Contract.EndContractBlock();
- this.versionAdded = value;
- }
- }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnSerializingAttribute : Attribute
- {
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnSerializedAttribute : Attribute
- {
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnDeserializingAttribute : Attribute
- {
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited=false)]
- public sealed class OnDeserializedAttribute : Attribute
- {
- }
-
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
deleted file mode 100644
index e9cb79b7af..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationException.cs
+++ /dev/null
@@ -1,44 +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: Thrown when something goes wrong during serialization or
-** deserialization.
-**
-**
-=============================================================================*/
-
-namespace System.Runtime.Serialization {
-
- using System;
- using System.Runtime.Serialization;
-
- [Serializable]
- public class SerializationException : SystemException {
-
- private static String _nullMessage = Environment.GetResourceString("Arg_SerializationException");
-
- // Creates a new SerializationException with its message
- // string set to a default message.
- public SerializationException()
- : base(_nullMessage) {
- SetErrorCode(__HResults.COR_E_SERIALIZATION);
- }
-
- public SerializationException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_SERIALIZATION);
- }
-
- public SerializationException(String message, Exception innerException) : base (message, innerException) {
- SetErrorCode(__HResults.COR_E_SERIALIZATION);
- }
-
- protected SerializationException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
index 45521f2397..7fc3ce27d9 100644
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
+++ b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfo.cs
@@ -11,25 +11,25 @@
**
**
===========================================================*/
-namespace System.Runtime.Serialization
-{
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- using System.Runtime.Remoting;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Security;
- using System.Runtime.CompilerServices;
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using System.Runtime.Remoting;
+using System.Globalization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Security;
+using System.Runtime.CompilerServices;
+namespace System.Runtime.Serialization
+{
public sealed class SerializationInfo
{
private const int defaultSize = 4;
private const string s_mscorlibAssemblySimpleName = System.CoreLib.Name;
private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll";
-
+
// Even though we have a dictionary, we're still keeping all the arrays around for back-compat.
// Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added.
internal String[] m_members;
@@ -94,7 +94,7 @@ namespace System.Runtime.Serialization
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
-
+
m_fullTypeName = value;
isFullTypeNameSetExplicit = true;
}
@@ -113,9 +113,9 @@ namespace System.Runtime.Serialization
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
- if (this.requireSameTokenInPartialTrust)
+ if (requireSameTokenInPartialTrust)
{
- DemandForUnsafeAssemblyNameAssignments(this.m_assemName, value);
+ DemandForUnsafeAssemblyNameAssignments(m_assemName, value);
}
m_assemName = value;
isAssemblyNameSetExplicit = true;
@@ -130,7 +130,7 @@ namespace System.Runtime.Serialization
}
Contract.EndContractBlock();
- if (this.requireSameTokenInPartialTrust)
+ if (requireSameTokenInPartialTrust)
{
DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName);
}
@@ -331,7 +331,7 @@ namespace System.Runtime.Serialization
if (m_nameToIndex.ContainsKey(name))
{
BCLDebug.Trace("SER", "[SerializationInfo.AddValue]Tried to add ", name, " twice to the SI.");
- throw new SerializationException(Environment.GetResourceString("Serialization_SameNameTwice"));
+ throw new SerializationException(SR.Serialization_SameNameTwice);
}
m_nameToIndex.Add(name, m_currMember);
@@ -382,7 +382,6 @@ namespace System.Runtime.Serialization
m_data[index] = value;
m_types[index] = type;
}
-
}
private int FindElement(String name)
@@ -416,7 +415,7 @@ namespace System.Runtime.Serialization
int index = FindElement(name);
if (index == -1)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
+ throw new SerializationException(SR.Format(SR.Serialization_NotFound, name));
}
Debug.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
@@ -451,7 +450,6 @@ namespace System.Runtime.Serialization
public Object GetValue(String name, Type type)
{
-
if ((object)type == null)
{
throw new ArgumentNullException(nameof(type));
@@ -460,7 +458,7 @@ namespace System.Runtime.Serialization
RuntimeType rt = type as RuntimeType;
if (rt == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeType);
Type foundType;
Object value;
@@ -698,6 +696,5 @@ namespace System.Runtime.Serialization
}
return m_converter.ToString(value);
}
-
}
}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs b/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
deleted file mode 100644
index 0858dfc19f..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/SerializationInfoEnumerator.cs
+++ /dev/null
@@ -1,145 +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: A formatter-friendly mechanism for walking all of
-** the data in a SerializationInfo. Follows the IEnumerator
-** mechanism from Collections.
-**
-**
-============================================================*/
-namespace System.Runtime.Serialization {
- using System;
- using System.Diagnostics;
- using System.Collections;
- using System.Diagnostics.Contracts;
-
- //
- // The tuple returned by SerializationInfoEnumerator.Current.
- //
- public struct SerializationEntry {
- private Type m_type;
- private Object m_value;
- private String m_name;
-
- public Object Value {
- get {
- return m_value;
- }
- }
-
- public String Name {
- get {
- return m_name;
- }
- }
-
- public Type ObjectType {
- get {
- return m_type;
- }
- }
-
- internal SerializationEntry(String entryName, Object entryValue, Type entryType) {
- m_value = entryValue;
- m_name = entryName;
- m_type = entryType;
- }
- }
-
- //
- // A simple enumerator over the values stored in the SerializationInfo.
- // This does not snapshot the values, it just keeps pointers to the
- // member variables of the SerializationInfo that created it.
- //
- public sealed class SerializationInfoEnumerator : IEnumerator {
- String[] m_members;
- Object[] m_data;
- Type[] m_types;
- int m_numItems;
- int m_currItem;
- bool m_current;
-
- internal SerializationInfoEnumerator(String[] members, Object[] info, Type[] types, int numItems) {
- Debug.Assert(members!=null, "[SerializationInfoEnumerator.ctor]members!=null");
- Debug.Assert(info!=null, "[SerializationInfoEnumerator.ctor]info!=null");
- Debug.Assert(types!=null, "[SerializationInfoEnumerator.ctor]types!=null");
- Debug.Assert(numItems>=0, "[SerializationInfoEnumerator.ctor]numItems>=0");
- Debug.Assert(members.Length>=numItems, "[SerializationInfoEnumerator.ctor]members.Length>=numItems");
- Debug.Assert(info.Length>=numItems, "[SerializationInfoEnumerator.ctor]info.Length>=numItems");
- Debug.Assert(types.Length>=numItems, "[SerializationInfoEnumerator.ctor]types.Length>=numItems");
-
- m_members = members;
- m_data = info;
- m_types = types;
- //The MoveNext semantic is much easier if we enforce that [0..m_numItems] are valid entries
- //in the enumerator, hence we subtract 1.
- m_numItems = numItems-1;
- m_currItem = -1;
- m_current = false;
- }
-
- public bool MoveNext() {
- if (m_currItem<m_numItems) {
- m_currItem++;
- m_current = true;
- } else {
- m_current = false;
- }
- return m_current;
- }
-
- /// <internalonly/>
- Object IEnumerator.Current { //Actually returns a SerializationEntry
- get {
- if (m_current==false) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- }
- return (Object)(new SerializationEntry(m_members[m_currItem], m_data[m_currItem], m_types[m_currItem]));
- }
- }
-
- public SerializationEntry Current { //Actually returns a SerializationEntry
- get {
- if (m_current==false) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- }
- return (new SerializationEntry(m_members[m_currItem], m_data[m_currItem], m_types[m_currItem]));
- }
- }
-
- public void Reset() {
- m_currItem = -1;
- m_current = false;
- }
-
- public String Name {
- get {
- if (m_current==false) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- }
- return m_members[m_currItem];
- }
- }
- public Object Value {
- get {
- if (m_current==false) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- }
- return m_data[m_currItem];
- }
- }
- public Type ObjectType {
- get {
- if (m_current==false) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen"));
- }
- return m_types[m_currItem];
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs b/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
deleted file mode 100644
index c01a3edc4f..0000000000
--- a/src/mscorlib/src/System/Runtime/Serialization/StreamingContext.cs
+++ /dev/null
@@ -1,72 +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.
-
-/*============================================================
-**
-** ValueType: StreamingContext
-**
-**
-** Purpose: A value type indicating the source or destination of our streaming.
-**
-**
-===========================================================*/
-namespace System.Runtime.Serialization {
-
- using System.Runtime.Remoting;
- using System;
- [Serializable]
- public struct StreamingContext {
- internal Object m_additionalContext;
- internal StreamingContextStates m_state;
-
- public StreamingContext(StreamingContextStates state)
- : this (state, null) {
- }
-
- public StreamingContext(StreamingContextStates state, Object additional) {
- m_state = state;
- m_additionalContext = additional;
- }
-
- public Object Context {
- get { return m_additionalContext; }
- }
-
- public override bool Equals(Object obj) {
- if (!(obj is StreamingContext)) {
- return false;
- }
- if (((StreamingContext)obj).m_additionalContext == m_additionalContext &&
- ((StreamingContext)obj).m_state == m_state) {
- return true;
- }
- return false;
- }
-
- public override int GetHashCode() {
- return (int)m_state;
- }
-
- public StreamingContextStates State {
- get { return m_state; }
- }
- }
-
- // **********************************************************
- // Keep these in sync with the version in vm\runtimehandles.h
- // **********************************************************
-[Serializable]
-[Flags]
- public enum StreamingContextStates {
- CrossProcess=0x01,
- CrossMachine=0x02,
- File =0x04,
- Persistence =0x08,
- Remoting =0x10,
- Other =0x20,
- Clone =0x40,
- CrossAppDomain =0x80,
- All =0xFF,
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.cs
deleted file mode 100644
index 0a9845d9c2..0000000000
--- a/src/mscorlib/src/System/Runtime/Versioning/NonVersionableAttribute.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.
-
-/*============================================================
-**
-** Class: NonVersionableAttribute
-**
-**
-** The [NonVersionable] attribute is applied to indicate that the implementation
-** of a particular member or layout of a struct cannot be changed for given platform in incompatible way.
-** This allows cross-module inlining of methods and data structures whose implementation
-** is never changed in ReadyToRun native images. Any changes to such members or types would be
-** breaking changes for ReadyToRun.
-**
-===========================================================*/
-using System;
-using System.Diagnostics;
-
-namespace System.Runtime.Versioning {
-
- // This Conditional is here to strip the annotations for targets where ReadyToRun is not supported.
- // If this attribute is ever made public, this Conditional should be removed.
- [Conditional("FEATURE_READYTORUN")]
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor,
- AllowMultiple = false, Inherited = false)]
- sealed class NonVersionableAttribute : Attribute {
-
- public NonVersionableAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs b/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
deleted file mode 100644
index 600ba3f154..0000000000
--- a/src/mscorlib/src/System/Runtime/Versioning/TargetFrameworkAttribute.cs
+++ /dev/null
@@ -1,45 +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: Identifies which SKU and version of the .NET
-** Framework that a particular library was compiled against.
-** Emitted by VS, and can help catch deployment problems.
-**
-===========================================================*/
-using System;
-using System.Diagnostics.Contracts;
-
-namespace System.Runtime.Versioning {
-
- [AttributeUsageAttribute(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
- public sealed class TargetFrameworkAttribute : Attribute {
- private String _frameworkName; // A target framework moniker
- private String _frameworkDisplayName;
-
- // The frameworkName parameter is intended to be the string form of a FrameworkName instance.
- public TargetFrameworkAttribute(String frameworkName)
- {
- if (frameworkName == null)
- throw new ArgumentNullException(nameof(frameworkName));
- Contract.EndContractBlock();
- _frameworkName = frameworkName;
- }
-
- // The target framework moniker that this assembly was compiled against.
- // Use the FrameworkName class to interpret target framework monikers.
- public String FrameworkName {
- get { return _frameworkName; }
- }
-
- public String FrameworkDisplayName {
- get { return _frameworkDisplayName; }
- set { _frameworkDisplayName = value; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/RuntimeArgumentHandle.cs b/src/mscorlib/src/System/RuntimeArgumentHandle.cs
index 3e13614930..6b56ae8f01 100644
--- a/src/mscorlib/src/System/RuntimeArgumentHandle.cs
+++ b/src/mscorlib/src/System/RuntimeArgumentHandle.cs
@@ -2,9 +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.
-namespace System {
-
- using System;
+
+using System;
+
+namespace System
+{
// This value type is used for constructing System.ArgIterator.
//
// SECURITY : m_ptr cannot be set to anything other than null by untrusted
@@ -19,5 +21,4 @@ namespace System {
internal IntPtr Value { get { return m_ptr; } }
}
-
}
diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs
index 39c85ad4e2..ab125e741e 100644
--- a/src/mscorlib/src/System/RuntimeHandles.cs
+++ b/src/mscorlib/src/System/RuntimeHandles.cs
@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
-namespace System
+namespace System
{
using System;
using System.Reflection;
@@ -32,7 +32,7 @@ namespace System
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
- throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
+ throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeTypeHandle(type);
}
@@ -42,13 +42,13 @@ namespace System
// Create local copy to avoid a race condition
RuntimeType type = m_type;
if (type == null)
- throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
+ throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return type;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInstanceOfType(RuntimeType type, Object o);
-
+
internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers)
{
Type type = typeStart;
@@ -61,11 +61,11 @@ namespace System
if (cModifiers > 0)
{
int* arModifiers = (int*)pModifiers.ToPointer();
- for(int i = 0; i < cModifiers; i++)
+ for (int i = 0; i < cModifiers; i++)
{
if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.Ptr)
type = type.MakePointerType();
-
+
else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ByRef)
type = type.MakeByRefType();
@@ -76,18 +76,18 @@ namespace System
type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int)));
}
}
-
+
return type;
}
public static bool operator ==(RuntimeTypeHandle left, object right) { return left.Equals(right); }
-
+
public static bool operator ==(object left, RuntimeTypeHandle right) { return right.Equals(left); }
-
+
public static bool operator !=(RuntimeTypeHandle left, object right) { return !left.Equals(right); }
public static bool operator !=(object left, RuntimeTypeHandle right) { return !right.Equals(left); }
-
+
// This is the RuntimeType for the type
private RuntimeType m_type;
@@ -99,10 +99,10 @@ namespace System
public override bool Equals(object obj)
{
- if(!(obj is RuntimeTypeHandle))
+ if (!(obj is RuntimeTypeHandle))
return false;
- RuntimeTypeHandle handle =(RuntimeTypeHandle)obj;
+ RuntimeTypeHandle handle = (RuntimeTypeHandle)obj;
return handle.m_type == m_type;
}
@@ -153,7 +153,7 @@ namespace System
return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray);
}
- internal static bool IsSzArray(RuntimeType type)
+ internal static bool IsSZArray(RuntimeType type)
{
CorElementType corElemType = GetCorElementType(type);
return (corElemType == CorElementType.SzArray);
@@ -203,7 +203,7 @@ namespace System
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool noCheck, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor, ref bool bNeedSecurityCheck);
+ internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
@@ -213,7 +213,7 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter);
-
+
internal RuntimeType GetRuntimeType()
{
return m_type;
@@ -233,12 +233,12 @@ namespace System
{
return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type));
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetBaseType(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static TypeAttributes GetAttributes(RuntimeType type);
+ internal extern static TypeAttributes GetAttributes(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetElementType(RuntimeType type);
@@ -247,27 +247,27 @@ namespace System
internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static int GetArrayRank(RuntimeType type);
+ internal extern static int GetArrayRank(RuntimeType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static int GetToken(RuntimeType type);
-
+ internal extern static int GetToken(RuntimeType type);
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot);
// This is managed wrapper for MethodTable::IntroducedMethodIterator
internal struct IntroducedMethodEnumerator
{
- bool _firstCall;
- RuntimeMethodHandleInternal _handle;
+ private bool _firstCall;
+ private RuntimeMethodHandleInternal _handle;
internal IntroducedMethodEnumerator(RuntimeType type)
{
_handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type);
_firstCall = true;
}
-
- public bool MoveNext()
+
+ public bool MoveNext()
{
if (_firstCall)
{
@@ -281,8 +281,9 @@ namespace System
}
public RuntimeMethodHandleInternal Current
- {
- get {
+ {
+ get
+ {
return _handle;
}
}
@@ -304,13 +305,13 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static Type[] GetInterfaces(RuntimeType type);
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types);
@@ -333,7 +334,7 @@ namespace System
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static int GetNumVirtuals(RuntimeType type);
+ internal extern static int GetNumVirtuals(RuntimeType type);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
@@ -354,7 +355,7 @@ namespace System
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
+ internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
@@ -363,7 +364,7 @@ namespace System
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
private extern static bool _IsVisible(RuntimeTypeHandle typeHandle);
-
+
internal static bool IsVisible(RuntimeType type)
{
return _IsVisible(new RuntimeTypeHandle(type));
@@ -427,24 +428,24 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeType GetDeclaringType(RuntimeType type);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type);
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method);
- internal IRuntimeMethodInfo GetDefaultConstructor()
+ internal IRuntimeMethodInfo GetDefaultConstructor()
{
IRuntimeMethodInfo ctor = null;
GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor));
return ctor;
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
+ private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark,
IntPtr pPrivHostBinder,
bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive);
@@ -461,7 +462,7 @@ namespace System
if (name == null || name.Length == 0)
{
if (throwOnError)
- throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr"));
+ throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
return null;
}
@@ -485,7 +486,7 @@ namespace System
internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope)
{
if (name == null || name.Length == 0)
- throw new ArgumentException(null, nameof(name));
+ throw new ArgumentException(null, nameof(name));
Contract.EndContractBlock();
RuntimeType type = null;
@@ -520,7 +521,7 @@ namespace System
{
// defensive copy to be sure array is not mutated from the outside during processing
int instCount;
- IntPtr []instHandles = CopyRuntimeTypeHandles(inst, out instCount);
+ IntPtr[] instHandles = CopyRuntimeTypeHandles(inst, out instCount);
fixed (IntPtr* pInst = instHandles)
{
@@ -552,7 +553,7 @@ namespace System
MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type);
@@ -563,7 +564,7 @@ namespace System
MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type);
@@ -578,7 +579,7 @@ namespace System
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal extern static bool IsCollectible(RuntimeTypeHandle handle);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool HasInstantiation(RuntimeType type);
@@ -598,7 +599,7 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericTypeDefinition(RuntimeType type);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericVariable(RuntimeType type);
@@ -610,7 +611,7 @@ namespace System
RuntimeType type = GetTypeChecked();
if (!IsGenericVariable(type))
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
+ throw new InvalidOperationException(SR.Arg_NotGenericParameter);
return GetGenericVariableIndex(type);
}
@@ -622,9 +623,9 @@ namespace System
{
return ContainsGenericVariables(GetTypeChecked());
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr *pTypeContext, int typeContextLength, IntPtr *pMethodContext, int methodContextLength, RuntimeType toType);
+ private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType);
internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType)
{
@@ -632,8 +633,8 @@ namespace System
int methodContextLength;
IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength);
IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength);
-
- fixed (IntPtr *pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
+
+ fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles)
{
bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType);
@@ -651,10 +652,10 @@ namespace System
{
return new MetadataImport(_GetMetadataImport(type), type);
}
-
+
private RuntimeTypeHandle(SerializationInfo info, StreamingContext context)
{
- if(info == null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
@@ -663,17 +664,17 @@ namespace System
m_type = m;
if (m_type == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
+ throw new SerializationException(SR.Serialization_InsufficientState);
}
- public void GetObjectData(SerializationInfo info, StreamingContext context)
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if(info == null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_type == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidFieldState"));
+ throw new SerializationException(SR.Serialization_InvalidFieldState);
info.AddValue("TypeObj", m_type, typeof(RuntimeType));
}
@@ -715,7 +716,7 @@ namespace System
{
m_handle = value;
}
-
+
internal IntPtr m_handle;
}
@@ -733,17 +734,17 @@ namespace System
m_value = new RuntimeMethodHandleInternal(methodHandleValue);
}
- object m_keepalive;
+ private object m_keepalive;
// These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo
#pragma warning disable 169
- object m_a;
- object m_b;
- object m_c;
- object m_d;
- object m_e;
- object m_f;
- object m_g;
+ private object m_a;
+ private object m_b;
+ private object m_c;
+ private object m_d;
+ private object m_e;
+ private object m_f;
+ private object m_g;
#pragma warning restore 169
public RuntimeMethodHandleInternal m_value;
@@ -772,12 +773,12 @@ namespace System
internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method)
{
if (method == null)
- throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
+ throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return method;
}
private IRuntimeMethodInfo m_value;
-
+
internal RuntimeMethodHandle(IRuntimeMethodInfo method)
{
m_value = method;
@@ -793,31 +794,31 @@ namespace System
{
return rmh.Value;
}
-
+
// ISerializable interface
private RuntimeMethodHandle(SerializationInfo info, StreamingContext context)
{
- if(info == null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
-
- MethodBase m =(MethodBase)info.GetValue("MethodObj", typeof(MethodBase));
+
+ MethodBase m = (MethodBase)info.GetValue("MethodObj", typeof(MethodBase));
m_value = m.MethodHandle.m_value;
if (m_value == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
+ throw new SerializationException(SR.Serialization_InsufficientState);
}
- public void GetObjectData(SerializationInfo info, StreamingContext context)
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_value == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidFieldState"));
-
+ throw new SerializationException(SR.Serialization_InvalidFieldState);
+
// This is either a RuntimeMethodInfo or a RuntimeConstructorInfo
MethodBase methodInfo = RuntimeType.GetMethodBase(m_value);
@@ -863,9 +864,9 @@ namespace System
}
[Pure]
- internal bool IsNullHandle()
- {
- return m_value == null;
+ internal bool IsNullHandle()
+ {
+ return m_value == null;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -896,7 +897,7 @@ namespace System
{
return _GetCurrentMethod(ref stackMark);
}
-
+
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method);
@@ -910,7 +911,7 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method);
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString);
@@ -943,7 +944,7 @@ namespace System
GC.KeepAlive(method);
return slot;
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMethodDef(IRuntimeMethodInfo method);
@@ -973,7 +974,7 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor);
-#region Private Invocation Helpers
+ #region Private Invocation Helpers
internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
{
return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle);
@@ -982,10 +983,10 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method);
-#endregion
+ #endregion
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- [SuppressUnmanagedCodeSecurity]
+ [SuppressUnmanagedCodeSecurity]
private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray);
internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method)
@@ -1023,10 +1024,10 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method);
@@ -1044,7 +1045,7 @@ namespace System
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
-
+
internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method)
{
if (!IsTypicalMethodDefinition(method))
@@ -1056,7 +1057,7 @@ namespace System
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
-
+
internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method)
{
IRuntimeMethodInfo strippedMethod = method;
@@ -1097,7 +1098,6 @@ namespace System
// When in doubt, do not use.
internal struct RuntimeFieldHandleInternal
{
-
internal bool IsNullHandle()
{
return m_handle.IsNull();
@@ -1130,15 +1130,14 @@ namespace System
[StructLayout(LayoutKind.Sequential)]
internal class RuntimeFieldInfoStub : IRuntimeFieldInfo
{
-
// These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo
#pragma warning disable 169
- object m_keepalive;
- object m_c;
- object m_d;
- int m_b;
- object m_e;
- RuntimeFieldHandleInternal m_fieldHandle;
+ private object m_keepalive;
+ private object m_c;
+ private object m_d;
+ private int m_b;
+ private object m_e;
+ private RuntimeFieldHandleInternal m_fieldHandle;
#pragma warning restore 169
RuntimeFieldHandleInternal IRuntimeFieldInfo.Value
@@ -1159,7 +1158,7 @@ namespace System
// Create local copy to avoid a race condition
IRuntimeFieldInfo field = m_ptr;
if (field == null)
- throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
+ throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
return new RuntimeFieldHandle(field);
}
@@ -1183,16 +1182,16 @@ namespace System
}
}
- internal bool IsNullHandle()
+ internal bool IsNullHandle()
{
- return m_ptr == null;
+ return m_ptr == null;
}
public override int GetHashCode()
{
return ValueType.GetHashCodeOfPtr(Value);
}
-
+
public override bool Equals(object obj)
{
if (!(obj is RuntimeFieldHandle))
@@ -1218,11 +1217,11 @@ namespace System
return !left.Equals(right);
}
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern String GetName(RtFieldInfo field);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal static extern String GetName(RtFieldInfo field);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field);
internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); }
@@ -1230,8 +1229,8 @@ namespace System
internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
-
+ internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field);
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field);
@@ -1242,16 +1241,16 @@ namespace System
return type;
}
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern int GetToken(RtFieldInfo field);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal static extern int GetToken(RtFieldInfo field);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void *pTypedRef, RuntimeType contextType);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1300,68 +1299,68 @@ namespace System
// ISerializable interface
private RuntimeFieldHandle(SerializationInfo info, StreamingContext context)
{
- if(info==null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
-
- FieldInfo f =(RuntimeFieldInfo) info.GetValue("FieldObj", typeof(RuntimeFieldInfo));
-
- if( f == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
+
+ FieldInfo f = (RuntimeFieldInfo)info.GetValue("FieldObj", typeof(RuntimeFieldInfo));
+
+ if (f == null)
+ throw new SerializationException(SR.Serialization_InsufficientState);
m_ptr = f.FieldHandle.m_ptr;
if (m_ptr == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InsufficientState"));
+ throw new SerializationException(SR.Serialization_InsufficientState);
}
- public void GetObjectData(SerializationInfo info, StreamingContext context)
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
+ if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
if (m_ptr == null)
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidFieldState"));
+ throw new SerializationException(SR.Serialization_InvalidFieldState);
+
+ RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo());
- RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo());
-
- info.AddValue("FieldObj",fldInfo, typeof(RuntimeFieldInfo));
+ info.AddValue("FieldObj", fldInfo, typeof(RuntimeFieldInfo));
}
}
public unsafe struct ModuleHandle
{
// Returns handle for interop with EE. The handle is guaranteed to be non-null.
-#region Public Static Members
+ #region Public Static Members
public static readonly ModuleHandle EmptyHandle = GetEmptyMH();
-#endregion
+ #endregion
unsafe static private ModuleHandle GetEmptyMH()
{
return new ModuleHandle();
}
-#region Private Data Members
+ #region Private Data Members
private RuntimeModule m_ptr;
-#endregion
-
-#region Constructor
- internal ModuleHandle(RuntimeModule module)
+ #endregion
+
+ #region Constructor
+ internal ModuleHandle(RuntimeModule module)
{
m_ptr = module;
}
-#endregion
+ #endregion
-#region Internal FCalls
+ #region Internal FCalls
internal RuntimeModule GetRuntimeModule()
{
return m_ptr;
}
-
+
public override int GetHashCode()
- {
+ {
return m_ptr != null ? m_ptr.GetHashCode() : 0;
}
@@ -1400,16 +1399,16 @@ namespace System
{
// Make sure we have a valid Module to resolve against.
if (module == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullModuleHandle"));
+ throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle);
}
// SQL-CLR LKG9 Compiler dependency
public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); }
- public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
+ public RuntimeTypeHandle ResolveTypeHandle(int typeToken)
{
return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null));
}
- public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
+ public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext));
}
@@ -1419,8 +1418,8 @@ namespace System
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken))
throw new ArgumentOutOfRangeException(nameof(typeToken),
- Environment.GetResourceString("Argument_InvalidToken", typeToken, new ModuleHandle(module)));
-
+ SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module)));
+
int typeInstCount, methodInstCount;
IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
@@ -1439,7 +1438,7 @@ namespace System
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveType(RuntimeModule module,
int typeToken,
- IntPtr* typeInstArgs,
+ IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
@@ -1473,7 +1472,7 @@ namespace System
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken))
throw new ArgumentOutOfRangeException(nameof(methodToken),
- Environment.GetResourceString("Argument_InvalidToken", methodToken, new ModuleHandle(module)));
+ SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module)));
fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext)
{
@@ -1485,7 +1484,7 @@ namespace System
[SuppressUnmanagedCodeSecurity]
private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module,
int methodToken,
- IntPtr* typeInstArgs,
+ IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount);
@@ -1494,19 +1493,19 @@ namespace System
public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); }
public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
- { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
+ { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); }
internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
{
ValidateModulePointer(module);
if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken))
throw new ArgumentOutOfRangeException(nameof(fieldToken),
- Environment.GetResourceString("Argument_InvalidToken", fieldToken, new ModuleHandle(module)));
-
+ SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module)));
+
// defensive copy to be sure array is not mutated from the outside during processing
int typeInstCount, methodInstCount;
- IntPtr [] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
- IntPtr [] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
+ IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount);
+ IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount);
fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles)
{
@@ -1522,7 +1521,7 @@ namespace System
[SuppressUnmanagedCodeSecurity]
private extern static void ResolveField(RuntimeModule module,
int fieldToken,
- IntPtr* typeInstArgs,
+ IntPtr* typeInstArgs,
int typeInstCount,
IntPtr* methodInstArgs,
int methodInstCount,
@@ -1547,11 +1546,11 @@ namespace System
GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type));
return type;
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine);
-
+
// making this internal, used by Module.GetPEKind
internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine)
{
@@ -1560,15 +1559,15 @@ namespace System
peKind = (PortableExecutableKinds)lKind;
machine = (ImageFileMachine)lMachine;
}
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static int GetMDStreamVersion(RuntimeModule module);
public int MDStreamVersion
{
get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); }
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static IntPtr _GetMetadataImport(RuntimeModule module);
@@ -1576,42 +1575,42 @@ namespace System
{
return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module);
}
-#endregion
+ #endregion
}
internal unsafe class Signature
{
-#region Definitions
+ #region Definitions
internal enum MdSigCallingConvention : byte
{
- Generics = 0x10,
- HasThis = 0x20,
- ExplicitThis = 0x40,
- CallConvMask = 0x0F,
- Default = 0x00,
- C = 0x01,
- StdCall = 0x02,
- ThisCall = 0x03,
- FastCall = 0x04,
- Vararg = 0x05,
- Field = 0x06,
- LocalSig = 0x07,
- Property = 0x08,
- Unmgd = 0x09,
- GenericInst = 0x0A,
- Max = 0x0B,
- }
-#endregion
-
-#region FCalls
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ Generics = 0x10,
+ HasThis = 0x20,
+ ExplicitThis = 0x40,
+ CallConvMask = 0x0F,
+ Default = 0x00,
+ C = 0x01,
+ StdCall = 0x02,
+ ThisCall = 0x03,
+ FastCall = 0x04,
+ Vararg = 0x05,
+ Field = 0x06,
+ LocalSig = 0x07,
+ Property = 0x08,
+ Unmgd = 0x09,
+ GenericInst = 0x0A,
+ Max = 0x0B,
+ }
+ #endregion
+
+ #region FCalls
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern void GetSignature(
void* pCorSig, int cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType);
-#endregion
+ #endregion
-#region Private Data Members
+ #region Private Data Members
//
// Keep the layout in sync with SignatureNative in the VM
//
@@ -1624,10 +1623,10 @@ namespace System
internal int m_nSizeOfArgStack;
internal int m_csig;
internal RuntimeMethodHandleInternal m_pMethod;
-#endregion
+ #endregion
-#region Constructors
- public Signature (
+ #region Constructors
+ public Signature(
IRuntimeMethodInfo method,
RuntimeType[] arguments,
RuntimeType returnType,
@@ -1656,9 +1655,9 @@ namespace System
{
GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType);
}
-#endregion
+ #endregion
-#region Internal Members
+ #region Internal Members
internal CallingConventions CallingConvention { get { return (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags; } }
internal RuntimeType[] Arguments { get { return m_arguments; } }
internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } }
@@ -1669,20 +1668,20 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern Type[] GetCustomModifiers(int position, bool required);
-#endregion
+ #endregion
}
internal abstract class Resolver
{
- internal struct CORINFO_EH_CLAUSE
+ internal struct CORINFO_EH_CLAUSE
{
internal int Flags;
internal int TryOffset;
internal int TryLength;
internal int HandlerOffset;
internal int HandlerLength;
- internal int ClassTokenOrFilterOffset;
+ internal int ClassTokenOrFilterOffset;
}
// ILHeader info
@@ -1698,5 +1697,4 @@ namespace System
//
internal abstract MethodInfo GetDynamicMethod();
}
-
}
diff --git a/src/mscorlib/src/System/SByte.cs b/src/mscorlib/src/System/SByte.cs
index e738dfc546..2f1b2da947 100644
--- a/src/mscorlib/src/System/SByte.cs
+++ b/src/mscorlib/src/System/SByte.cs
@@ -10,50 +10,58 @@
**
**
===========================================================*/
-namespace System {
- using System.Globalization;
- using System;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
+using System.Globalization;
+using System;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// A place holder class for signed bytes.
-[Serializable]
-[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+ [Serializable]
+ [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct SByte : IComparable, IFormattable, IConvertible
- , IComparable<SByte>, IEquatable<SByte>
+ , IComparable<SByte>, IEquatable<SByte>
{
private sbyte m_value;
-
+
// The maximum value that a Byte may represent: 127.
public const sbyte MaxValue = (sbyte)0x7F;
-
+
// The minimum value that a Byte may represent: -128.
public const sbyte MinValue = unchecked((sbyte)0x80);
-
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type SByte, this method throws an ArgumentException.
//
- public int CompareTo(Object obj) {
- if (obj == null) {
+ public int CompareTo(Object obj)
+ {
+ if (obj == null)
+ {
return 1;
}
- if (!(obj is SByte)) {
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeSByte"));
+ if (!(obj is SByte))
+ {
+ throw new ArgumentException(SR.Arg_MustBeSByte);
}
return m_value - ((SByte)obj).m_value;
}
- public int CompareTo(SByte value) {
+ public int CompareTo(SByte value)
+ {
return m_value - value;
}
-
+
// Determines whether two Byte objects are equal.
- public override bool Equals(Object obj) {
- if (!(obj is SByte)) {
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is SByte))
+ {
return false;
}
return m_value == ((SByte)obj).m_value;
@@ -66,204 +74,226 @@ namespace System {
}
// Gets a hash code for this instance.
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return ((int)m_value ^ (int)m_value << 8);
}
-
-
+
+
// Provides a string representation of a byte.
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
-
- public String ToString(String format) {
+
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return ToString(format, NumberFormatInfo.GetInstance(provider));
}
- private String ToString(String format, NumberFormatInfo info) {
+ private String ToString(String format, NumberFormatInfo info)
+ {
Contract.Ensures(Contract.Result<String>() != null);
- if (m_value<0 && format!=null && format.Length>0 && (format[0]=='X' || format[0]=='x')) {
+ if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x'))
+ {
uint temp = (uint)(m_value & 0x000000FF);
return Number.FormatUInt32(temp, format, info);
}
return Number.FormatInt32(m_value, format, info);
}
-
+
[CLSCompliant(false)]
- public static sbyte Parse(String s) {
+ public static sbyte Parse(String s)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
+
[CLSCompliant(false)]
- public static sbyte Parse(String s, NumberStyles style) {
- NumberFormatInfo.ValidateParseStyleInteger(style);
+ public static sbyte Parse(String s, NumberStyles style)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
- public static sbyte Parse(String s, IFormatProvider provider) {
+ public static sbyte Parse(String s, IFormatProvider provider)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
-
+
// Parses a signed byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
[CLSCompliant(false)]
- public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider) {
- NumberFormatInfo.ValidateParseStyleInteger(style);
+ public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
-
- private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info) {
-
+
+ private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info)
+ {
int i = 0;
- try {
+ try
+ {
i = Number.ParseInt32(s, style, info);
}
- catch(OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_SByte"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_SByte, e);
}
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number
- if ((i < 0) || i > Byte.MaxValue) {
- throw new OverflowException(Environment.GetResourceString("Overflow_SByte"));
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // We are parsing a hexadecimal number
+ if ((i < 0) || i > Byte.MaxValue)
+ {
+ throw new OverflowException(SR.Overflow_SByte);
}
return (sbyte)i;
}
-
- if (i < MinValue || i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_SByte"));
+
+ if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_SByte);
return (sbyte)i;
}
[CLSCompliant(false)]
- public static bool TryParse(String s, out SByte result) {
+ public static bool TryParse(String s, out SByte result)
+ {
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result) {
- NumberFormatInfo.ValidateParseStyleInteger(style);
+ public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result)
+ {
+ 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(String s, NumberStyles style, NumberFormatInfo info, out SByte result)
+ {
result = 0;
int i;
- if (!Number.TryParseInt32(s, style, info, out i)) {
+ if (!Number.TryParseInt32(s, style, info, out i))
+ {
return false;
}
- if ((style & NumberStyles.AllowHexSpecifier) != 0) { // We are parsing a hexadecimal number
- if ((i < 0) || i > Byte.MaxValue) {
+ if ((style & NumberStyles.AllowHexSpecifier) != 0)
+ { // We are parsing a hexadecimal number
+ if ((i < 0) || i > Byte.MaxValue)
+ {
return false;
}
result = (sbyte)i;
return true;
}
-
- if (i < MinValue || i > MaxValue) {
+
+ if (i < MinValue || i > MaxValue)
+ {
return false;
}
- result = (sbyte) i;
+ result = (sbyte)i;
return true;
}
-
+
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.SByte;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "SByte", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/Security/Attributes.cs b/src/mscorlib/src/System/Security/Attributes.cs
deleted file mode 100644
index f67a9f0ad1..0000000000
--- a/src/mscorlib/src/System/Security/Attributes.cs
+++ /dev/null
@@ -1,199 +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.Runtime.InteropServices;
-
-namespace System.Security
-{
- // DynamicSecurityMethodAttribute:
- // Indicates that calling the target method requires space for a security
- // object to be allocated on the callers stack. This attribute is only ever
- // set on certain security methods defined within mscorlib.
- [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false )]
- sealed internal class DynamicSecurityMethodAttribute : System.Attribute
- {
- }
-
- // SuppressUnmanagedCodeSecurityAttribute:
- // Indicates that the target P/Invoke method(s) should skip the per-call
- // security checked for unmanaged code permission.
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false )]
- sealed public class SuppressUnmanagedCodeSecurityAttribute : System.Attribute
- {
- }
-
- // UnverifiableCodeAttribute:
- // Indicates that the target module contains unverifiable code.
- [AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false )]
- sealed public class UnverifiableCodeAttribute : System.Attribute
- {
- }
-
- // AllowPartiallyTrustedCallersAttribute:
- // Indicates that the Assembly is secure and can be used by untrusted
- // and semitrusted clients
- // For v.1, this is valid only on Assemblies, but could be expanded to
- // include Module, Method, class
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
- sealed public class AllowPartiallyTrustedCallersAttribute : System.Attribute
- {
- private PartialTrustVisibilityLevel _visibilityLevel;
- public AllowPartiallyTrustedCallersAttribute () { }
-
- public PartialTrustVisibilityLevel PartialTrustVisibilityLevel
- {
- get { return _visibilityLevel; }
- set { _visibilityLevel = value; }
- }
- }
-
- public enum PartialTrustVisibilityLevel
- {
- VisibleToAllHosts = 0,
- NotVisibleByDefault = 1
- }
-
- [Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
- public enum SecurityCriticalScope
- {
- Explicit = 0,
- Everything = 0x1
- }
-
- // SecurityCriticalAttribute
- // Indicates that the decorated code or assembly performs security critical operations (e.g. Assert, "unsafe", LinkDemand, etc.)
- // The attribute can be placed on most targets, except on arguments/return values.
- [AttributeUsage(AttributeTargets.Assembly |
- AttributeTargets.Class |
- AttributeTargets.Struct |
- AttributeTargets.Enum |
- AttributeTargets.Constructor |
- AttributeTargets.Method |
- AttributeTargets.Field |
- AttributeTargets.Interface |
- AttributeTargets.Delegate,
- AllowMultiple = false,
- Inherited = false )]
- sealed public class SecurityCriticalAttribute : System.Attribute
- {
-#pragma warning disable 618 // We still use SecurityCriticalScope for v2 compat
-
- private SecurityCriticalScope _val;
-
- public SecurityCriticalAttribute () {}
-
- public SecurityCriticalAttribute(SecurityCriticalScope scope)
- {
- _val = scope;
- }
-
- [Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")]
- public SecurityCriticalScope Scope {
- get {
- return _val;
- }
- }
-
-#pragma warning restore 618
- }
-
- // SecurityTreatAsSafeAttribute:
- // Indicates that the code may contain violations to the security critical rules (e.g. transitions from
- // critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
- // security concerns and is considered security clean.
- // At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
- // At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
- // At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
-
- [AttributeUsage(AttributeTargets.Assembly |
- AttributeTargets.Class |
- AttributeTargets.Struct |
- AttributeTargets.Enum |
- AttributeTargets.Constructor |
- AttributeTargets.Method |
- AttributeTargets.Field |
- AttributeTargets.Interface |
- AttributeTargets.Delegate,
- AllowMultiple = false,
- Inherited = false )]
- [Obsolete("SecurityTreatAsSafe is only used for .NET 2.0 transparency compatibility. Please use the SecuritySafeCriticalAttribute instead.")]
- sealed public class SecurityTreatAsSafeAttribute : System.Attribute
- {
- public SecurityTreatAsSafeAttribute () { }
- }
-
- // SecuritySafeCriticalAttribute:
- // Indicates that the code may contain violations to the security critical rules (e.g. transitions from
- // critical to non-public transparent, transparent to non-public critical, etc.), has been audited for
- // security concerns and is considered security clean. Also indicates that the code is considered SecurityCritical.
- // The effect of this attribute is as if the code was marked [SecurityCritical][SecurityTreatAsSafe].
- // At assembly-scope, all rule checks will be suppressed within the assembly and for calls made against the assembly.
- // At type-scope, all rule checks will be suppressed for members within the type and for calls made against the type.
- // At member level (e.g. field and method) the code will be treated as public - i.e. no rule checks for the members.
-
- [AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Struct |
- AttributeTargets.Enum |
- AttributeTargets.Constructor |
- AttributeTargets.Method |
- AttributeTargets.Field |
- AttributeTargets.Interface |
- AttributeTargets.Delegate,
- AllowMultiple = false,
- Inherited = false )]
- sealed public class SecuritySafeCriticalAttribute : System.Attribute
- {
- public SecuritySafeCriticalAttribute () { }
- }
-
- // SecurityTransparentAttribute:
- // Indicates the assembly contains only transparent code.
- // Security critical actions will be restricted or converted into less critical actions. For example,
- // Assert will be restricted, SuppressUnmanagedCode, LinkDemand, unsafe, and unverifiable code will be converted
- // into Full-Demands.
-
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false )]
- sealed public class SecurityTransparentAttribute : System.Attribute
- {
- public SecurityTransparentAttribute () {}
- }
-
- public enum SecurityRuleSet : byte
- {
- None = 0,
- Level1 = 1, // v2.0 transparency model
- Level2 = 2, // v4.0 transparency model
- }
-
- // SecurityRulesAttribute
- //
- // Indicates which set of security rules an assembly was authored against, and therefore which set of
- // rules the runtime should enforce on the assembly. For instance, an assembly marked with
- // [SecurityRules(SecurityRuleSet.Level1)] will follow the v2.0 transparency rules, where transparent code
- // can call a LinkDemand by converting it to a full demand, public critical methods are implicitly
- // treat as safe, and the remainder of the v2.0 rules apply.
- [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
- public sealed class SecurityRulesAttribute : Attribute
- {
- private SecurityRuleSet m_ruleSet;
- private bool m_skipVerificationInFullTrust = false;
-
- public SecurityRulesAttribute(SecurityRuleSet ruleSet)
- {
- m_ruleSet = ruleSet;
- }
-
- // Should fully trusted transparent code skip IL verification
- public bool SkipVerificationInFullTrust
- {
- get { return m_skipVerificationInFullTrust; }
- set { m_skipVerificationInFullTrust = value; }
- }
-
- public SecurityRuleSet RuleSet
- {
- get { return m_ruleSet; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/DynamicSecurityMethodAttribute.cs b/src/mscorlib/src/System/Security/DynamicSecurityMethodAttribute.cs
new file mode 100644
index 0000000000..83be902a2c
--- /dev/null
+++ b/src/mscorlib/src/System/Security/DynamicSecurityMethodAttribute.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+
+namespace System.Security
+{
+ // DynamicSecurityMethodAttribute:
+ // All methods that use StackCrawlMark should be marked with this attribute. This attribute
+ // disables inlining of the calling method to allow stackwalking to find the exact caller.
+ //
+ // This attribute used to indicate that the target method requires space for a security object
+ // to be allocated on the callers stack. It is not used for this purpose anymore because of security
+ // stackwalks are not ever done in CoreCLR.
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, AllowMultiple = true, Inherited = false)]
+ internal sealed class DynamicSecurityMethodAttribute : Attribute
+ {
+ public DynamicSecurityMethodAttribute() { }
+ }
+}
diff --git a/src/mscorlib/src/System/Security/SecurityException.cs b/src/mscorlib/src/System/Security/SecurityException.cs
deleted file mode 100644
index 8811be82ff..0000000000
--- a/src/mscorlib/src/System/Security/SecurityException.cs
+++ /dev/null
@@ -1,110 +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 class for security
-**
-**
-=============================================================================*/
-
-namespace System.Security
-{
- using System.Security;
- using System;
- using System.Runtime.Serialization;
- using System.Reflection;
- using System.Text;
- using System.Security.Policy;
- using System.IO;
- using System.Globalization;
- using System.Diagnostics.Contracts;
-
- [Serializable]
- public class SecurityException : SystemException
- {
- internal static string GetResString(string sResourceName)
- {
- return Environment.GetResourceString(sResourceName);
- }
-
-#pragma warning disable 618
- internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, RuntimeMethodHandleInternal rmh, Object demand)
-#pragma warning restore 618
- {
- return new SecurityException(GetResString("Arg_SecurityException"));
- }
-
- public SecurityException()
- : base(GetResString("Arg_SecurityException"))
- {
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- }
-
- public SecurityException(String message)
- : base(message)
- {
- // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.)
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- }
-
- public SecurityException(String message, Exception inner)
- : base(message, inner)
- {
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- }
-
- protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
- }
-
- public override String ToString()
- {
- return base.ToString();
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- base.GetObjectData(info, context);
- }
-
- // Stubs for surface area compatibility only
- public SecurityException(String message, Type type)
- : base(message)
- {
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- PermissionType = type;
- }
-
- public SecurityException(string message, System.Type type, string state)
- : base(message)
- {
- SetErrorCode(System.__HResults.COR_E_SECURITY);
- PermissionType = type;
- PermissionState = state;
- }
-
- public object Demanded { get; set; }
- public object DenySetInstance { get; set; }
- public System.Reflection.AssemblyName FailedAssemblyInfo { get; set; }
- public string GrantedSet { get; set; }
- public System.Reflection.MethodInfo Method { get; set; }
- public string PermissionState { get; set; }
- public System.Type PermissionType { get; set; }
- public object PermitOnlySetInstance { get; set; }
- public string RefusedSet { get; set; }
- public string Url { get; set; }
- }
-}
diff --git a/src/mscorlib/src/System/Security/SecurityState.cs b/src/mscorlib/src/System/Security/SecurityState.cs
deleted file mode 100644
index 55dcce07c0..0000000000
--- a/src/mscorlib/src/System/Security/SecurityState.cs
+++ /dev/null
@@ -1,25 +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.Security;
-
-namespace System.Security
-{
- public abstract class SecurityState
- {
- protected SecurityState(){}
-
- public bool IsStateAvailable()
- {
- AppDomainManager domainManager = AppDomainManager.CurrentAppDomainManager;
-
- // CheckSecuritySettings only when appdomainManager is present. So if there is no
- // appDomain Manager return true as by default coreclr runs in fulltrust.
- return domainManager != null ? domainManager.CheckSecuritySettings(this) : true;
- }
- // override this function and throw the appropriate
- public abstract void EnsureState();
- }
-
-}
diff --git a/src/mscorlib/src/System/Security/Util/URLString.cs b/src/mscorlib/src/System/Security/Util/URLString.cs
deleted file mode 100644
index 4ec353876a..0000000000
--- a/src/mscorlib/src/System/Security/Util/URLString.cs
+++ /dev/null
@@ -1,138 +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.
-
-// URLString
-//
-//
-// Implementation of membership condition for zones
-//
-
-namespace System.Security.Util {
-
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Runtime.Serialization;
- using System.Globalization;
- using System.Text;
- using System.IO;
- using System.Diagnostics.Contracts;
-
- internal static class URLString
- {
- internal static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl)
- {
- bool isUncShare = false;
- return PreProcessForExtendedPathRemoval(checkPathLength: checkPathLength, url: url, isFileUrl: isFileUrl, isUncShare: ref isUncShare);
- }
-
- // Keeping this signature to avoid reflection breaks
- private static string PreProcessForExtendedPathRemoval(string url, bool isFileUrl, ref bool isUncShare)
- {
- return PreProcessForExtendedPathRemoval(checkPathLength: true, url: url, isFileUrl: isFileUrl, isUncShare: ref isUncShare);
- }
-
- private static string PreProcessForExtendedPathRemoval(bool checkPathLength, string url, bool isFileUrl, ref bool isUncShare)
- {
- // This is the modified URL that we will return
- StringBuilder modifiedUrl = new StringBuilder(url);
-
- // ITEM 1 - remove extended path characters.
- {
- // Keep track of where we are in both the comparison and altered strings.
- int curCmpIdx = 0;
- int curModIdx = 0;
-
- // If all the '\' have already been converted to '/', just check for //?/ or //./
- if ((url.Length - curCmpIdx) >= 4 &&
- (String.Compare(url, curCmpIdx, "//?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
- String.Compare(url, curCmpIdx, "//./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
- {
- modifiedUrl.Remove(curModIdx, 4);
- curCmpIdx += 4;
- }
- else
- {
- if (isFileUrl)
- {
- // We need to handle an indefinite number of leading front slashes for file URLs since we could
- // get something like:
- // file://\\?\
- // file:/\\?\
- // file:\\?\
- // etc...
- while (url[curCmpIdx] == '/')
- {
- curCmpIdx++;
- curModIdx++;
- }
- }
-
- // Remove the extended path characters
- if ((url.Length - curCmpIdx) >= 4 &&
- (String.Compare(url, curCmpIdx, "\\\\?\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
- String.Compare(url, curCmpIdx, "\\\\?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
- String.Compare(url, curCmpIdx, "\\\\.\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
- String.Compare(url, curCmpIdx, "\\\\./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
- {
- modifiedUrl.Remove(curModIdx, 4);
- curCmpIdx += 4;
- }
- }
- }
-
- // ITEM 2 - convert all slashes to forward slashes, and strip leading slashes.
- if (isFileUrl)
- {
- int slashCount = 0;
- bool seenFirstBackslash = false;
-
- while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\'))
- {
- // Look for sets of consecutive backslashes. We can't just look for these at the start
- // of the string, since file:// might come first. Instead, once we see the first \, look
- // for a second one following it.
- if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\')
- {
- seenFirstBackslash = true;
- if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\')
- isUncShare = true;
- }
-
- slashCount++;
- }
-
- modifiedUrl.Remove(0, slashCount);
- modifiedUrl.Replace('\\', '/');
- }
-
- // ITEM 3 - If the path is greater than or equal (due to terminating NULL in windows) MAX_PATH, we throw.
- if (checkPathLength)
- {
- // This needs to be a separate method to avoid hitting the static constructor on AppContextSwitches
- CheckPathTooLong(modifiedUrl);
- }
-
- // Create the result string from the StringBuilder
- return modifiedUrl.ToString();
- }
-
- [MethodImpl(MethodImplOptions.NoInlining)]
- private static void CheckPathTooLong(StringBuilder path)
- {
- if (path.Length >= (
-#if PLATFORM_UNIX
- Interop.Sys.MaxPath))
-#else
- PathInternal.MaxLongPath))
-#endif
- {
- throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Security/VerificationException.cs b/src/mscorlib/src/System/Security/VerificationException.cs
deleted file mode 100644
index 5defbd6603..0000000000
--- a/src/mscorlib/src/System/Security/VerificationException.cs
+++ /dev/null
@@ -1,32 +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.
-
-//
-
-namespace System.Security {
- using System.Security;
- using System;
- using System.Runtime.Serialization;
-
- [Serializable]
- public class VerificationException : SystemException {
- public VerificationException()
- : base(Environment.GetResourceString("Verification_Exception")) {
- SetErrorCode(__HResults.COR_E_VERIFICATION);
- }
-
- public VerificationException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_VERIFICATION);
- }
-
- public VerificationException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_VERIFICATION);
- }
-
- protected VerificationException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
- }
-}
diff --git a/src/mscorlib/src/System/SerializableAttribute.cs b/src/mscorlib/src/System/SerializableAttribute.cs
index 1c99654eec..266e73d78d 100644
--- a/src/mscorlib/src/System/SerializableAttribute.cs
+++ b/src/mscorlib/src/System/SerializableAttribute.cs
@@ -10,24 +10,26 @@
**
**
============================================================*/
-namespace System {
- using System;
- using System.Reflection;
+using System;
+using System.Reflection;
+namespace System
+{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
- public sealed class SerializableAttribute : Attribute
+ public sealed class SerializableAttribute : Attribute
{
- internal static Attribute GetCustomAttribute(RuntimeType type)
- {
- return (type.Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable ? new SerializableAttribute() : null;
+ 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;
+ internal static bool IsDefined(RuntimeType type)
+ {
+ return type.IsSerializable;
}
- public SerializableAttribute() {
+ public SerializableAttribute()
+ {
}
}
}
diff --git a/src/mscorlib/src/System/SharedStatics.cs b/src/mscorlib/src/System/SharedStatics.cs
index d9364335f5..a6a04d9614 100644
--- a/src/mscorlib/src/System/SharedStatics.cs
+++ b/src/mscorlib/src/System/SharedStatics.cs
@@ -11,22 +11,22 @@
**
=============================================================================*/
+using System.Threading;
+using System.Runtime.Remoting;
+using System.Security;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System
{
- using System.Threading;
- using System.Runtime.Remoting;
- using System.Security;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
internal sealed class SharedStatics
{
// this is declared static but is actually forced to be the same object
// for each AppDomain at AppDomain create time.
private static SharedStatics _sharedStatics;
-
+
// Note: Do not add any code in this ctor because it is not called
// when we set up _sharedStatics via AppDomain::SetupSharedStatics
private SharedStatics()
@@ -34,12 +34,6 @@ namespace System
BCLDebug.Assert(false, "SharedStatics..ctor() is never called.");
}
- private volatile String _Remoting_Identity_IDGuid;
-
- // Note this may not need to be process-wide.
- private int _Remoting_Identity_IDSeqNum;
-
-
// This is the total amount of memory currently "reserved" via
// all MemoryFailPoints allocated within the process.
// Stored as a long because we need to use Interlocked.Add.
@@ -48,13 +42,15 @@ namespace System
internal static long AddMemoryFailPointReservation(long size)
{
// Size can legitimately be negative - see Dispose.
- return Interlocked.Add(ref _sharedStatics._memFailPointReservedMemory, (long) size);
+ return Interlocked.Add(ref _sharedStatics._memFailPointReservedMemory, (long)size);
}
- internal static ulong MemoryFailPointReservedMemory {
- get {
+ internal static ulong MemoryFailPointReservedMemory
+ {
+ get
+ {
Debug.Assert(Volatile.Read(ref _sharedStatics._memFailPointReservedMemory) >= 0, "Process-wide MemoryFailPoint reserved memory was negative!");
- return (ulong) Volatile.Read(ref _sharedStatics._memFailPointReservedMemory);
+ return (ulong)Volatile.Read(ref _sharedStatics._memFailPointReservedMemory);
}
}
}
diff --git a/src/mscorlib/src/System/Single.cs b/src/mscorlib/src/System/Single.cs
index 657d7aef32..1c39df7d94 100644
--- a/src/mscorlib/src/System/Single.cs
+++ b/src/mscorlib/src/System/Single.cs
@@ -10,19 +10,20 @@
**
**
===========================================================*/
-namespace System {
- using System.Globalization;
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics.Contracts;
-
-[Serializable]
-[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+using System.Globalization;
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [Serializable]
+ [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct Single : IComparable, IFormattable, IConvertible
- , IComparable<Single>, IEquatable<Single>
+ , IComparable<Single>, IEquatable<Single>
{
internal float m_value;
@@ -37,33 +38,38 @@ namespace System {
public const float NaN = (float)0.0 / (float)0.0;
internal static float NegativeZero = BitConverter.Int32BitsToSingle(unchecked((int)0x80000000));
-
+
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool IsInfinity(float f) {
+ public unsafe static bool IsInfinity(float f)
+ {
return (*(int*)(&f) & 0x7FFFFFFF) == 0x7F800000;
}
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool IsPositiveInfinity(float f) {
+ public unsafe static bool IsPositiveInfinity(float f)
+ {
return *(int*)(&f) == 0x7F800000;
}
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool IsNegativeInfinity(float f) {
+ public unsafe static bool IsNegativeInfinity(float f)
+ {
return *(int*)(&f) == unchecked((int)0xFF800000);
}
[Pure]
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool IsNaN(float f) {
+ public unsafe static bool IsNaN(float f)
+ {
return (*(int*)(&f) & 0x7FFFFFFF) > 0x7F800000;
}
-
+
[Pure]
- internal unsafe static bool IsNegative(float f) {
+ internal unsafe static bool IsNegative(float f)
+ {
return (*(uint*)(&f) & 0x80000000) == 0x80000000;
}
@@ -73,11 +79,14 @@ namespace System {
// null is considered to be less than any instance.
// If object is not of type Single, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is Single) {
+ if (value is Single)
+ {
float f = (float)value;
if (m_value < f) return -1;
if (m_value > f) return 1;
@@ -89,11 +98,12 @@ namespace System {
else // f is NaN.
return 1;
}
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeSingle"));
+ throw new ArgumentException(SR.Arg_MustBeSingle);
}
- public int CompareTo(Single value) {
+ public int CompareTo(Single value)
+ {
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
@@ -106,41 +116,50 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator ==(Single left, Single right) {
+ public static bool operator ==(Single left, Single right)
+ {
return left == right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator !=(Single left, Single right) {
+ public static bool operator !=(Single left, Single right)
+ {
return left != right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator <(Single left, Single right) {
+ public static bool operator <(Single left, Single right)
+ {
return left < right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator >(Single left, Single right) {
+ public static bool operator >(Single left, Single right)
+ {
return left > right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator <=(Single left, Single right) {
+ public static bool operator <=(Single left, Single right)
+ {
return left <= right;
}
[System.Runtime.Versioning.NonVersionable]
- public static bool operator >=(Single left, Single right) {
+ public static bool operator >=(Single left, Single right)
+ {
return left >= right;
}
- public override bool Equals(Object obj) {
- if (!(obj is Single)) {
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Single))
+ {
return false;
}
float temp = ((Single)obj).m_value;
- if (temp == m_value) {
+ if (temp == m_value)
+ {
return true;
}
@@ -149,16 +168,19 @@ namespace System {
public bool Equals(Single obj)
{
- if (obj == m_value) {
+ if (obj == m_value)
+ {
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
- public unsafe override int GetHashCode() {
+ public unsafe override int GetHashCode()
+ {
float f = m_value;
- if (f == 0) {
+ if (f == 0)
+ {
// Ensure that 0 and -0 have the same hash code
return 0;
}
@@ -166,22 +188,26 @@ namespace System {
return v;
}
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
}
@@ -194,139 +220,155 @@ namespace System {
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
//
- public static float Parse(String s) {
+ public static float Parse(String s)
+ {
return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
- public static float Parse(String s, NumberStyles style) {
+ public static float Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
- public static float Parse(String s, IFormatProvider provider) {
+ public static float Parse(String s, IFormatProvider provider)
+ {
return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
- public static float Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static float Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
-
- private static float Parse(String s, NumberStyles style, NumberFormatInfo info) {
+
+ private static float Parse(String s, NumberStyles style, NumberFormatInfo info)
+ {
return Number.ParseSingle(s, style, info);
}
- public static Boolean TryParse(String s, out Single result) {
+ public static Boolean TryParse(String s, out Single result)
+ {
return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
- public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single 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) {
+
+ private static Boolean TryParse(String s, NumberStyles style, NumberFormatInfo info, out Single result)
+ {
+ if (s == null)
+ {
result = 0;
return false;
}
bool success = Number.TryParseSingle(s, style, info, out result);
- if (!success) {
+ if (!success)
+ {
String sTrim = s.Trim();
- if (sTrim.Equals(info.PositiveInfinitySymbol)) {
+ if (sTrim.Equals(info.PositiveInfinitySymbol))
+ {
result = PositiveInfinity;
- } else if (sTrim.Equals(info.NegativeInfinitySymbol)) {
+ }
+ else if (sTrim.Equals(info.NegativeInfinitySymbol))
+ {
result = NegativeInfinity;
- } else if (sTrim.Equals(info.NaNSymbol)) {
+ }
+ else if (sTrim.Equals(info.NaNSymbol))
+ {
result = NaN;
- } else
+ }
+ else
return false; // We really failed
}
return true;
-
}
//
// IConvertible implementation
//
- public TypeCode GetTypeCode() {
+ public TypeCode GetTypeCode()
+ {
return TypeCode.Single;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Single", "Char"));
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char"));
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Single", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/Span.cs b/src/mscorlib/src/System/Span.cs
index c77a1994c9..4211083def 100644
--- a/src/mscorlib/src/System/Span.cs
+++ b/src/mscorlib/src/System/Span.cs
@@ -3,12 +3,20 @@
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
+using System.Runtime;
using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
+#if BIT64
+using nuint = System.UInt64;
+#else
+using nuint = System.UInt32;
+#endif
+
namespace System
{
/// <summary>
@@ -112,7 +120,7 @@ namespace System
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe Span(void* pointer, int length)
{
- if (JitHelpers.ContainsReferences<T>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
if (length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
@@ -123,28 +131,15 @@ namespace System
/// <summary>
/// Create a new span over a portion of a regular managed object. This can be useful
- /// if part of a managed object represents a "fixed array." This is dangerous because
- /// "length" is not checked, nor is the fact that "rawPointer" actually lies within the object.
+ /// if part of a managed object represents a "fixed array." This is dangerous because neither the
+ /// <paramref name="length"/> is checked, nor <paramref name="obj"/> being null, nor the fact that
+ /// "rawPointer" actually lies within <paramref name="obj"/>.
/// </summary>
/// <param name="obj">The managed object that contains the data to span over.</param>
/// <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>
- /// <exception cref="System.ArgumentNullException">
- /// Thrown when the specified object is null.
- /// </exception>
- /// <exception cref="System.ArgumentOutOfRangeException">
- /// Thrown when the specified <paramref name="length"/> is negative.
- /// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static Span<T> DangerousCreate(object obj, ref T objectData, int length)
- {
- if (obj == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj);
- if (length < 0)
- ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length);
-
- return new Span<T>(ref objectData, length);
- }
+ public static Span<T> DangerousCreate(object obj, ref T objectData, int length) => new Span<T>(ref objectData, length);
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@@ -183,11 +178,7 @@ namespace System
/// <exception cref="System.IndexOutOfRangeException">
/// Thrown when index less than 0 or index greater than or equal to Length
/// </exception>
-
- // TODO: https://github.com/dotnet/corefx/issues/13681
- // Until we get over the hurdle of C# 7 tooling, this indexer will return "T" and have a setter rather than a "ref T". (The doc comments
- // continue to reflect the original intent of returning "ref T")
- public T this[int index]
+ public ref T this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
@@ -195,49 +186,23 @@ namespace System
if ((uint)index >= (uint)_length)
ThrowHelper.ThrowIndexOutOfRangeException();
- return Unsafe.Add(ref _pointer.Value, index);
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- set
- {
- if ((uint)index >= (uint)_length)
- ThrowHelper.ThrowIndexOutOfRangeException();
-
- Unsafe.Add(ref _pointer.Value, index) = value;
+ return ref Unsafe.Add(ref _pointer.Value, index);
}
}
/// <summary>
- /// Returns a reference to specified element of the Span.
- /// </summary>
- /// <param name="index"></param>
- /// <returns></returns>
- /// <exception cref="System.IndexOutOfRangeException">
- /// Thrown when index less than 0 or index greater than or equal to Length
- /// </exception>
-
- // TODO: https://github.com/dotnet/corefx/issues/13681
- // Until we get over the hurdle of C# 7 tooling, this temporary method will simulate the intended "ref T" indexer for those
- // who need bypass the workaround for performance.
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public ref T GetItem(int index)
- {
- if ((uint)index >= ((uint)_length))
- ThrowHelper.ThrowIndexOutOfRangeException();
-
- return ref Unsafe.Add(ref _pointer.Value, index);
- }
-
- /// <summary>
/// Clears the contents of this span.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Clear()
{
- // TODO: Optimize - https://github.com/dotnet/coreclr/issues/9161
- for (int i = 0; i < _length; i++)
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
+ {
+ SpanHelper.ClearWithReferences(ref Unsafe.As<T, IntPtr>(ref _pointer.Value), (nuint)_length * (nuint)(Unsafe.SizeOf<T>() / sizeof(nuint)));
+ }
+ else
{
- this[i] = default(T);
+ SpanHelper.ClearWithoutReferences(ref Unsafe.As<T, byte>(ref _pointer.Value), (nuint)_length * (nuint)Unsafe.SizeOf<T>());
}
}
@@ -246,47 +211,50 @@ namespace System
/// </summary>
public void Fill(T value)
{
- int length = _length;
-
- if (length == 0)
- return;
-
if (Unsafe.SizeOf<T>() == 1)
{
- byte fill = Unsafe.As<T, byte>(ref value);
- ref byte r = ref Unsafe.As<T, byte>(ref _pointer.Value);
- Unsafe.InitBlockUnaligned(ref r, fill, (uint)length);
+ uint length = (uint)_length;
+ if (length == 0)
+ return;
+
+ T tmp = value; // Avoid taking address of the "value" argument. It would regress performance of the loop below.
+ Unsafe.InitBlockUnaligned(ref Unsafe.As<T, byte>(ref _pointer.Value), Unsafe.As<T, byte>(ref tmp), length);
}
else
{
+ // Do all math as nuint to avoid unnecessary 64->32->64 bit integer truncations
+ nuint length = (uint)_length;
+ if (length == 0)
+ return;
+
ref T r = ref DangerousGetPinnableReference();
// TODO: Create block fill for value types of power of two sizes e.g. 2,4,8,16
- // Simple loop unrolling
- int i = 0;
- for (; i < (length & ~7); i += 8)
+ nuint elementSize = (uint)Unsafe.SizeOf<T>();
+ nuint i = 0;
+ for (; i < (length & ~(nuint)7); i += 8)
{
- Unsafe.Add<T>(ref r, i + 0) = value;
- Unsafe.Add<T>(ref r, i + 1) = value;
- Unsafe.Add<T>(ref r, i + 2) = value;
- Unsafe.Add<T>(ref r, i + 3) = value;
- Unsafe.Add<T>(ref r, i + 4) = value;
- Unsafe.Add<T>(ref r, i + 5) = value;
- Unsafe.Add<T>(ref r, i + 6) = value;
- Unsafe.Add<T>(ref r, i + 7) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 4) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 5) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 6) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 7) * elementSize) = value;
}
- if (i < (length & ~3))
+ if (i < (length & ~(nuint)3))
{
- Unsafe.Add<T>(ref r, i + 0) = value;
- Unsafe.Add<T>(ref r, i + 1) = value;
- Unsafe.Add<T>(ref r, i + 2) = value;
- Unsafe.Add<T>(ref r, i + 3) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 0) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 1) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 2) * elementSize) = value;
+ Unsafe.AddByteOffset<T>(ref r, (i + 3) * elementSize) = value;
i += 4;
}
for (; i < length; i++)
{
- Unsafe.Add<T>(ref r, i) = value;
+ Unsafe.AddByteOffset<T>(ref r, i * elementSize) = value;
}
}
}
@@ -348,9 +316,7 @@ namespace System
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
- ThrowHelper.ThrowNotSupportedException_CannotCallEqualsOnSpan();
- // Prevent compiler error CS0161: 'Span<T>.Equals(object)': not all code paths return a value
- return default(bool);
+ throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan);
}
/// <summary>
@@ -363,9 +329,7 @@ namespace System
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
- ThrowHelper.ThrowNotSupportedException_CannotCallGetHashCodeOnSpan();
- // Prevent compiler error CS0161: 'Span<T>.GetHashCode()': not all code paths return a value
- return default(int);
+ throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan);
}
/// <summary>
@@ -448,10 +412,11 @@ namespace System
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<byte> AsBytes<T>(this Span<T> source)
where T : struct
{
- if (JitHelpers.ContainsReferences<T>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
return new Span<byte>(
@@ -467,10 +432,11 @@ namespace System
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="T"/> contains pointers.
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> AsBytes<T>(this ReadOnlySpan<T> source)
where T : struct
{
- if (JitHelpers.ContainsReferences<T>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<T>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T));
return new ReadOnlySpan<byte>(
@@ -489,13 +455,14 @@ namespace System
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Span<TTo> NonPortableCast<TFrom, TTo>(this Span<TFrom> source)
where TFrom : struct
where TTo : struct
{
- if (JitHelpers.ContainsReferences<TFrom>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
- if (JitHelpers.ContainsReferences<TTo>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
return new Span<TTo>(
@@ -514,13 +481,14 @@ namespace System
/// <exception cref="System.ArgumentException">
/// Thrown when <typeparamref name="TFrom"/> or <typeparamref name="TTo"/> contains pointers.
/// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<TTo> NonPortableCast<TFrom, TTo>(this ReadOnlySpan<TFrom> source)
where TFrom : struct
where TTo : struct
{
- if (JitHelpers.ContainsReferences<TFrom>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<TFrom>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom));
- if (JitHelpers.ContainsReferences<TTo>())
+ if (RuntimeHelpers.IsReferenceOrContainsReferences<TTo>())
ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo));
return new ReadOnlySpan<TTo>(
@@ -535,94 +503,407 @@ 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> Slice(this string text)
+ public static ReadOnlySpan<char> AsSpan(this string text)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
return new ReadOnlySpan<char>(ref text.GetFirstCharRef(), text.Length);
}
-
- /// <summary>
- /// Creates a new readonly span over the portion of the target string, beginning at 'start'.
- /// </summary>
- /// <param name="text">The target string.</param>
- /// <param name="start">The index at which to begin this slice.</param>
- /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
- /// reference (Nothing in Visual Basic).</exception>
- /// <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 static ReadOnlySpan<char> Slice(this string text, int start)
- {
- if (text == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
- if ((uint)start > (uint)text.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException();
-
- return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), text.Length - start);
- }
-
- /// <summary>
- /// Creates a new readonly span over the portion of the target string, beginning at <paramref name="start"/>, of given <paramref name="length"/>.
- /// </summary>
- /// <param name="text">The target string.</param>
- /// <param name="start">The index at which to begin this slice.</param>
- /// <param name="length">The number of items in the span.</param>
- /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
- /// reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArgumentOutOfRangeException">
- /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;&eq;Length).
- /// </exception>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ReadOnlySpan<char> Slice(this string text, int start, int length)
- {
- if (text == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
- if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start))
- ThrowHelper.ThrowArgumentOutOfRangeException();
-
- return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetFirstCharRef(), start), length);
- }
}
internal static class SpanHelper
{
internal static unsafe void CopyTo<T>(ref T destination, ref T source, int elementsCount)
{
- if (elementsCount == 0)
+ if (Unsafe.AreSame(ref destination, ref source))
return;
- if (Unsafe.AreSame(ref destination, ref source))
+ if (elementsCount <= 1)
+ {
+ if (elementsCount == 1)
+ {
+ destination = source;
+ }
return;
+ }
- if (!JitHelpers.ContainsReferences<T>())
+ nuint byteCount = (nuint)elementsCount * (nuint)Unsafe.SizeOf<T>();
+ if (!RuntimeHelpers.IsReferenceOrContainsReferences<T>())
{
fixed (byte* pDestination = &Unsafe.As<T, byte>(ref destination))
{
fixed (byte* pSource = &Unsafe.As<T, byte>(ref source))
{
-#if BIT64
- Buffer.Memmove(pDestination, pSource, (ulong)elementsCount * (ulong)Unsafe.SizeOf<T>());
-#else
- Buffer.Memmove(pDestination, pSource, (uint)elementsCount * (uint)Unsafe.SizeOf<T>());
-#endif
+ Buffer.Memmove(pDestination, pSource, byteCount);
}
}
}
else
{
- if (JitHelpers.ByRefLessThan(ref destination, ref source)) // copy forward
- {
- for (int i = 0; i < elementsCount; i++)
- Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i);
- }
- else // copy backward to avoid overlapping issues
+ RuntimeImports.RhBulkMoveWithWriteBarrier(
+ ref Unsafe.As<T, byte>(ref destination),
+ ref Unsafe.As<T, byte>(ref source),
+ byteCount);
+ }
+ }
+
+ internal static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength)
+ {
+ if (byteLength == 0)
+ return;
+
+#if AMD64
+ if (byteLength > 4096) goto PInvoke;
+ Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength);
+ return;
+#else // AMD64
+ // TODO: Optimize this method on X86 machine
+ // Note: It's important that this switch handles lengths at least up to 22.
+ // See notes below near the main loop for why.
+
+ // The switch will be very fast since it can be implemented using a jump
+ // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info.
+
+ switch (byteLength)
+ {
+ case 1:
+ b = 0;
+ return;
+ case 2:
+ Unsafe.As<byte, short>(ref b) = 0;
+ return;
+ case 3:
+ Unsafe.As<byte, short>(ref b) = 0;
+ Unsafe.Add<byte>(ref b, 2) = 0;
+ return;
+ case 4:
+ Unsafe.As<byte, int>(ref b) = 0;
+ return;
+ case 5:
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.Add<byte>(ref b, 4) = 0;
+ return;
+ case 6:
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ return;
+ case 7:
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.Add<byte>(ref b, 6) = 0;
+ return;
+ case 8:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ return;
+ case 9:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.Add<byte>(ref b, 8) = 0;
+ return;
+ case 10:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ return;
+ case 11:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.Add<byte>(ref b, 10) = 0;
+ return;
+ case 12:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ return;
+ case 13:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.Add<byte>(ref b, 12) = 0;
+ return;
+ case 14:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+ return;
+ case 15:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+ Unsafe.Add<byte>(ref b, 14) = 0;
+ return;
+ case 16:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ return;
+ case 17:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ Unsafe.Add<byte>(ref b, 16) = 0;
+ return;
+ case 18:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
+ return;
+ case 19:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
+ Unsafe.Add<byte>(ref b, 18) = 0;
+ return;
+ case 20:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
+ return;
+ case 21:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
+ Unsafe.Add<byte>(ref b, 20) = 0;
+ return;
+ case 22:
+#if BIT64
+ Unsafe.As<byte, long>(ref b) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref b) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0;
+#endif
+ Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0;
+ Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 20)) = 0;
+ return;
+ }
+
+ // P/Invoke into the native version for large lengths
+ if (byteLength >= 512) goto PInvoke;
+
+ nuint i = 0; // byte offset at which we're copying
+
+ if ((Unsafe.As<byte, int>(ref b) & 3) != 0)
+ {
+ if ((Unsafe.As<byte, int>(ref b) & 1) != 0)
{
- for (int i = elementsCount - 1; i >= 0; i--)
- Unsafe.Add(ref destination, i) = Unsafe.Add(ref source, i);
+ Unsafe.AddByteOffset<byte>(ref b, i) = 0;
+ i += 1;
+ if ((Unsafe.As<byte, int>(ref b) & 2) != 0)
+ goto IntAligned;
}
+ Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ i += 2;
+ }
+
+ IntAligned:
+
+ // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If
+ // (int)b % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1
+ // bytes to the next aligned address (respectively), so do nothing. On the other hand,
+ // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until
+ // we're aligned.
+ // The thing 1, 2, 3, and 4 have in common that the others don't is that if you
+ // subtract one from them, their 3rd lsb will not be set. Hence, the below check.
+
+ if (((Unsafe.As<byte, int>(ref b) - 1) & 4) == 0)
+ {
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ i += 4;
+ }
+
+ nuint end = byteLength - 16;
+ byteLength -= i; // lower 4 bits of byteLength represent how many bytes are left *after* the unrolled loop
+
+ // We know due to the above switch-case that this loop will always run 1 iteration; max
+ // bytes we clear before checking is 23 (7 to align the pointers, 16 for 1 iteration) so
+ // the switch handles lengths 0-22.
+ Debug.Assert(end >= 7 && i <= end);
+
+ // This is separated out into a different variable, so the i + 16 addition can be
+ // performed at the start of the pipeline and the loop condition does not have
+ // a dependency on the writes.
+ nuint counter;
+
+ do
+ {
+ counter = i + 16;
+
+ // This loop looks very costly since there appear to be a bunch of temporary values
+ // being created with the adds, but the jit (for x86 anyways) will convert each of
+ // these to use memory addressing operands.
+
+ // So the only cost is a bit of code size, which is made up for by the fact that
+ // we save on writes to b.
+
+#if BIT64
+ Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0;
+#else
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 12)) = 0;
+#endif
+
+ i = counter;
+
+ // See notes above for why this wasn't used instead
+ // i += 16;
+ }
+ while (counter <= end);
+
+ if ((byteLength & 8) != 0)
+ {
+#if BIT64
+ Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+#else
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0;
+#endif
+ i += 8;
+ }
+ if ((byteLength & 4) != 0)
+ {
+ Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ i += 4;
+ }
+ if ((byteLength & 2) != 0)
+ {
+ Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0;
+ i += 2;
+ }
+ if ((byteLength & 1) != 0)
+ {
+ Unsafe.AddByteOffset<byte>(ref b, i) = 0;
+ // We're not using i after this, so not needed
+ // i += 1;
+ }
+
+ return;
+#endif // AMD64
+
+ PInvoke:
+ RuntimeImports.RhZeroMemory(ref b, byteLength);
+ }
+
+ internal static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength)
+ {
+ if (pointerSizeLength == 0)
+ return;
+
+ // TODO: Perhaps do switch casing to improve small size perf
+
+ nuint i = 0;
+ nuint n = 0;
+ while ((n = i + 8) <= (pointerSizeLength))
+ {
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 4) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 5) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 6) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 7) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ i = n;
+ }
+ if ((n = i + 4) <= (pointerSizeLength))
+ {
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 2) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 3) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ i = n;
+ }
+ if ((n = i + 2) <= (pointerSizeLength))
+ {
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 1) * (nuint)sizeof(IntPtr)) = default(IntPtr);
+ i = n;
+ }
+ if ((i + 1) <= (pointerSizeLength))
+ {
+ Unsafe.AddByteOffset<IntPtr>(ref ip, (i + 0) * (nuint)sizeof(IntPtr)) = default(IntPtr);
}
}
}
diff --git a/src/mscorlib/src/System/StackOverflowException.cs b/src/mscorlib/src/System/StackOverflowException.cs
deleted file mode 100644
index 0a875e7373..0000000000
--- a/src/mscorlib/src/System/StackOverflowException.cs
+++ /dev/null
@@ -1,41 +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 for stack overflow.
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class StackOverflowException : SystemException
- {
- public StackOverflowException()
- : base(SR.Arg_StackOverflowException)
- {
- HResult = __HResults.COR_E_STACKOVERFLOW;
- }
-
- public StackOverflowException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_STACKOVERFLOW;
- }
-
- public StackOverflowException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_STACKOVERFLOW;
- }
-
- internal StackOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs
index 2ac1d78997..c2c3a8709a 100644
--- a/src/mscorlib/src/System/String.Comparison.cs
+++ b/src/mscorlib/src/System/String.Comparison.cs
@@ -24,16 +24,17 @@ namespace System
Contract.Requires(strB != null);
Contract.EndContractBlock();
int length = Math.Min(strA.Length, strB.Length);
-
+
fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)
{
char* a = ap;
char* b = bp;
+ int charA = 0, charB = 0;
- while (length != 0)
+ while (length != 0)
{
- int charA = *a;
- int charB = *b;
+ charA = *a;
+ charB = *b;
Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
@@ -43,7 +44,7 @@ namespace System
//Return the (case-insensitive) difference between them.
if (charA != charB)
- return charA - charB;
+ goto ReturnCharAMinusCharB; // TODO: Workaround for https://github.com/dotnet/coreclr/issues/9692
// Next char
a++; b++;
@@ -51,6 +52,9 @@ namespace System
}
return strA.Length - strB.Length;
+
+ ReturnCharAMinusCharB:
+ return charA - charB;
}
}
@@ -61,14 +65,14 @@ namespace System
//This will not work in case-insensitive mode for any character greater than 0x80.
//We'll throw an ArgumentException.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte *strBBytes);
+ unsafe internal static extern int nativeCompareOrdinalIgnoreCaseWC(String strA, sbyte* strBBytes);
//
//
// NATIVE INSTANCE METHODS
//
//
-
+
//
// Search/Query methods
//
@@ -120,7 +124,7 @@ namespace System
// always zero terminated and that the terminating zero is not included
// in the length. For odd string sizes, the last compare will include
// the zero terminator.
- while (length > 0)
+ while (length > 0)
{
if (*(int*)a != *(int*)b) goto ReturnFalse;
length -= 2; a += 2; b += 2;
@@ -128,7 +132,49 @@ namespace System
return true;
- ReturnFalse:
+ ReturnFalse:
+ return false;
+ }
+ }
+
+ private unsafe static bool EqualsIgnoreCaseAsciiHelper(String strA, String strB)
+ {
+ Contract.Requires(strA != null);
+ Contract.Requires(strB != null);
+ Contract.Requires(strA.Length == strB.Length);
+ Contract.EndContractBlock();
+ int length = strA.Length;
+
+ fixed (char* ap = &strA.m_firstChar) fixed (char* bp = &strB.m_firstChar)
+ {
+ char* a = ap;
+ char* b = bp;
+
+ while (length != 0)
+ {
+ int charA = *a;
+ int charB = *b;
+
+ Debug.Assert((charA | charB) <= 0x7F, "strings have to be ASCII");
+
+ // Ordinal equals or lowercase equals if the result ends up in the a-z range
+ if (charA == charB ||
+ ((charA | 0x20) == (charB | 0x20) &&
+ (uint)((charA | 0x20) - 'a') <= (uint)('z' - 'a')))
+ {
+ a++;
+ b++;
+ length--;
+ }
+ else
+ {
+ goto ReturnFalse;
+ }
+ }
+
+ return true;
+
+ ReturnFalse:
return false;
}
}
@@ -183,7 +229,7 @@ namespace System
// this compare can include the zero terminator. Bitwise OR avoids a branch.
return length == 0 | *a == *b;
- ReturnFalse:
+ ReturnFalse:
return false;
}
}
@@ -214,7 +260,7 @@ namespace System
// if the first two chars the same we can increment by 4 bytes,
// leaving us word-aligned on both 32-bit (12 bytes into the string)
// and 64-bit (16 bytes) platforms.
-
+
// For empty strings, the second char will be null due to padding.
// The start of the string (not including sync block pointer)
// is the method table pointer + string length, which takes up
@@ -222,7 +268,7 @@ namespace System
// terminator immediately follows, leaving us with an object
// 10/14 bytes in size. Since everything needs to be a multiple
// of 4/8, this will get padded and zeroed out.
-
+
// For one-char strings the second char will be the null terminator.
// NOTE: If in the future there is a way to read the second char
@@ -231,7 +277,7 @@ namespace System
// then do that and short-circuit before the fixed.
if (*(a + 1) != *(b + 1)) goto DiffOffset1;
-
+
// Since we know that the first two chars are the same,
// we can increment by 2 here and skip 4 bytes.
// This leaves us 8-byte aligned, which results
@@ -269,17 +315,17 @@ namespace System
{
if (*(int*)a != *(int*)b) goto DiffNextInt;
length -= 2;
- a += 2;
- b += 2;
+ a += 2;
+ b += 2;
}
// At this point, we have compared all the characters in at least one string.
// The longer string will be larger.
return strA.Length - strB.Length;
-
+
#if BIT64
- DiffOffset8: a += 4; b += 4;
- DiffOffset4: a += 4; b += 4;
+ DiffOffset8: a += 4; b += 4;
+ DiffOffset4: a += 4; b += 4;
#else // BIT64
// Use jumps instead of falling through, since
// otherwise going to DiffOffset8 will involve
@@ -289,8 +335,8 @@ namespace System
DiffOffset4: a += 2; b += 2;
DiffOffset2: a += 2; b += 2;
#endif // BIT64
-
- DiffOffset0:
+
+ DiffOffset0:
// If we reached here, we already see a difference in the unrolled loop above
#if BIT64
if (*(int*)a == *(int*)b)
@@ -299,7 +345,7 @@ namespace System
}
#endif // BIT64
- DiffNextInt:
+ DiffNextInt:
if (*a != *b) return *a - *b;
DiffOffset1:
@@ -307,7 +353,7 @@ namespace System
return *(a + 1) - *(b + 1);
}
}
-
+
// Provides a culture-correct string comparison. StrA is compared to StrB
// to determine whether it is lexicographically less, equal, or greater, and then returns
// either a negative integer, 0, or a positive integer; respectively.
@@ -317,7 +363,7 @@ namespace System
{
return Compare(strA, strB, StringComparison.CurrentCulture);
}
-
+
// Provides a culture-correct string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
@@ -331,16 +377,16 @@ namespace System
return Compare(strA, strB, comparisonType);
}
-
+
// Provides a more flexible function for string comparision. See StringComparison
// for meaning of different comparisonType.
[Pure]
- public static int Compare(String strA, String strB, StringComparison comparisonType)
+ public static int Compare(String strA, String strB, StringComparison comparisonType)
{
// Single comparison to check if comparisonType is within [CurrentCulture .. OrdinalIgnoreCase]
if ((uint)(comparisonType - StringComparison.CurrentCulture) > (uint)(StringComparison.OrdinalIgnoreCase - StringComparison.CurrentCulture))
{
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
@@ -359,7 +405,8 @@ namespace System
return 1;
}
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, CompareOptions.None);
@@ -384,19 +431,15 @@ namespace System
case StringComparison.OrdinalIgnoreCase:
// If both strings are ASCII strings, we can take the fast path.
- if (strA.IsAscii() && strB.IsAscii()) {
+ if (strA.IsAscii() && strB.IsAscii())
+ {
return (CompareOrdinalIgnoreCaseHelper(strA, strB));
}
-#if FEATURE_COREFX_GLOBALIZATION
return CompareInfo.CompareOrdinalIgnoreCase(strA, 0, strA.Length, strB, 0, strB.Length);
-#else
- // Take the slow path.
- return TextInfo.CompareOrdinalIgnoreCase(strA, strB);
-#endif
default:
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_StringComparison"));
+ throw new NotSupportedException(SR.NotSupported_StringComparison);
}
}
@@ -406,7 +449,8 @@ namespace System
// negative integer, 0, or a positive integer is returned; respectively.
//
[Pure]
- public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options) {
+ public static int Compare(String strA, String strB, CultureInfo culture, CompareOptions options)
+ {
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
@@ -466,7 +510,7 @@ namespace System
int lengthA = length;
int lengthB = length;
-
+
if (strA != null)
{
lengthA = Math.Min(lengthA, strA.Length - indexA);
@@ -519,17 +563,19 @@ namespace System
{
lengthB = Math.Min(lengthB, strB.Length - indexB);
}
-
+
return culture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, options);
}
[Pure]
- public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType) {
- if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ public static int Compare(String strA, int indexA, String strB, int indexB, int length, StringComparison comparisonType)
+ {
+ if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
+ {
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
-
+
if (strA == null || strB == null)
{
if (object.ReferenceEquals(strA, strB))
@@ -543,19 +589,19 @@ namespace System
if (length < 0)
{
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
- throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (strA.Length - indexA < 0 || strB.Length - indexB < 0)
{
string paramName = strA.Length - indexA < 0 ? nameof(indexA) : nameof(indexB);
- throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
@@ -566,7 +612,8 @@ namespace System
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, lengthA, strB, indexB, lengthB, CompareOptions.None);
@@ -583,16 +630,11 @@ namespace System
return CompareOrdinalHelper(strA, indexA, lengthA, strB, indexB, lengthB);
case StringComparison.OrdinalIgnoreCase:
-#if FEATURE_COREFX_GLOBALIZATION
return (CompareInfo.CompareOrdinalIgnoreCase(strA, indexA, lengthA, strB, indexB, lengthB));
-#else
- return (TextInfo.CompareOrdinalIgnoreCaseEx(strA, indexA, strB, indexB, lengthA, lengthB));
-#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"));
+ throw new ArgumentException(SR.NotSupported_StringComparison);
}
-
}
// Compares strA and strB using an ordinal (code-point) comparison.
@@ -624,7 +666,7 @@ namespace System
return CompareOrdinalHelper(strA, strB);
}
-
+
// Compares strA and strB using an ordinal (code-point) comparison.
//
@@ -647,22 +689,22 @@ namespace System
if (length < 0)
{
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeCount);
}
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
- throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
-
+
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
- throw new ArgumentOutOfRangeException(paramName, Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index);
}
if (length == 0 || (object.ReferenceEquals(strA, strB) && indexA == indexB))
@@ -689,12 +731,12 @@ namespace System
if (other == null)
{
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeString"));
+ throw new ArgumentException(SR.Arg_MustBeString);
}
return CompareTo(other); // will call the string-based overload
}
-
+
// Determines the sorting relation of StrB to the current instance.
//
[Pure]
@@ -709,30 +751,37 @@ namespace System
// and the default culture is used.
//
[Pure]
- public Boolean EndsWith(String value) {
+ public Boolean EndsWith(String value)
+ {
return EndsWith(value, StringComparison.CurrentCulture);
}
[Pure]
- public Boolean EndsWith(String value, StringComparison comparisonType) {
- if( (Object)value == null) {
- throw new ArgumentNullException(nameof(value));
+ public Boolean EndsWith(String value, StringComparison comparisonType)
+ {
+ if ((Object)value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
}
- if( comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
+ {
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
- if( (Object)this == (Object)value) {
+ if ((Object)this == (Object)value)
+ {
return true;
}
- if( value.Length == 0) {
+ if (value.Length == 0)
+ {
return true;
}
-
- switch (comparisonType) {
+
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
@@ -743,30 +792,29 @@ namespace System
return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
- return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
+ return CultureInfo.InvariantCulture.CompareInfo.IsSuffix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return this.Length < value.Length ? false : (CompareOrdinalHelper(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
case StringComparison.OrdinalIgnoreCase:
-#if FEATURE_COREFX_GLOBALIZATION
return this.Length < value.Length ? false : (CompareInfo.CompareOrdinalIgnoreCase(this, this.Length - value.Length, value.Length, value, 0, value.Length) == 0);
-#else
- return this.Length < value.Length ? false : (TextInfo.CompareOrdinalIgnoreCaseEx(this, this.Length - value.Length, value, 0, value.Length, value.Length) == 0);
-#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
+ }
}
[Pure]
- public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture) {
- if (null==value) {
+ public Boolean EndsWith(String value, Boolean ignoreCase, CultureInfo culture)
+ {
+ if (null == value)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
-
- if((object)this == (object)value) {
+
+ if ((object)this == (object)value)
+ {
return true;
}
@@ -780,21 +828,15 @@ namespace System
}
[Pure]
- internal bool EndsWith(char value) {
- int thisLen = this.Length;
- if (thisLen != 0) {
- if (this[thisLen - 1] == value)
- return true;
- }
- return false;
+ public bool EndsWith(char value)
+ {
+ int thisLen = Length;
+ return thisLen != 0 && this[thisLen - 1] == value;
}
// Determines whether two strings match.
public override bool Equals(Object obj)
{
- if (this == null) // this is necessary to guard against reverse-pinvokes and
- throw new NullReferenceException(); // other callers who do not use the callvirt instruction
-
if (object.ReferenceEquals(this, obj))
return true;
@@ -812,9 +854,6 @@ namespace System
[Pure]
public bool Equals(String value)
{
- if (this == null) // this is necessary to guard against reverse-pinvokes and
- throw new NullReferenceException(); // other callers who do not use the callvirt instruction
-
if (object.ReferenceEquals(this, value))
return true;
@@ -824,7 +863,7 @@ namespace System
// instead of calling string.op_Equality.
if (value == null)
return false;
-
+
if (this.Length != value.Length)
return false;
@@ -832,20 +871,24 @@ namespace System
}
[Pure]
- public bool Equals(String value, StringComparison comparisonType) {
+ public bool Equals(String value, StringComparison comparisonType)
+ {
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
Contract.EndContractBlock();
- if ((Object)this == (Object)value) {
+ if ((Object)this == (Object)value)
+ {
return true;
}
- if ((Object)value == null) {
+ if ((Object)value == null)
+ {
return false;
}
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, CompareOptions.None) == 0);
@@ -868,31 +911,30 @@ namespace System
return false;
// If both strings are ASCII strings, we can take the fast path.
- if (this.IsAscii() && value.IsAscii()) {
- return (CompareOrdinalIgnoreCaseHelper(this, value) == 0);
+ if (this.IsAscii() && value.IsAscii())
+ {
+ return EqualsIgnoreCaseAsciiHelper(this, value);
}
-#if FEATURE_COREFX_GLOBALIZATION
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, this.Length, value, 0, value.Length) == 0);
-#else
- // Take the slow path.
- return (TextInfo.CompareOrdinalIgnoreCase(this, value) == 0);
-#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
// Determines whether two Strings match.
[Pure]
- public static bool Equals(String a, String b) {
- if ((Object)a==(Object)b) {
+ public static bool Equals(String a, String b)
+ {
+ if ((Object)a == (Object)b)
+ {
return true;
}
- if ((Object)a == null || (Object)b == null || a.Length != b.Length) {
+ if ((Object)a == null || (Object)b == null || a.Length != b.Length)
+ {
return false;
}
@@ -900,20 +942,24 @@ namespace System
}
[Pure]
- public static bool Equals(String a, String b, StringComparison comparisonType) {
+ public static bool Equals(String a, String b, StringComparison comparisonType)
+ {
if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
Contract.EndContractBlock();
- if ((Object)a==(Object)b) {
+ if ((Object)a == (Object)b)
+ {
return true;
}
-
- if ((Object)a==null || (Object)b==null) {
+
+ if ((Object)a == null || (Object)b == null)
+ {
return false;
}
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return (CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, CompareOptions.None) == 0);
@@ -935,31 +981,31 @@ namespace System
case StringComparison.OrdinalIgnoreCase:
if (a.Length != b.Length)
return false;
- else {
+ else
+ {
// If both strings are ASCII strings, we can take the fast path.
- if (a.IsAscii() && b.IsAscii()) {
- return (CompareOrdinalIgnoreCaseHelper(a, b) == 0);
+ if (a.IsAscii() && b.IsAscii())
+ {
+ return EqualsIgnoreCaseAsciiHelper(a, b);
}
// Take the slow path.
-#if FEATURE_COREFX_GLOBALIZATION
return (CompareInfo.CompareOrdinalIgnoreCase(a, 0, a.Length, b, 0, b.Length) == 0);
-#else
- return (TextInfo.CompareOrdinalIgnoreCase(a, b) == 0);
-#endif
}
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
}
- public static bool operator == (String a, String b) {
- return String.Equals(a, b);
+ public static bool operator ==(String a, String b)
+ {
+ return String.Equals(a, b);
}
- public static bool operator != (String a, String b) {
- return !String.Equals(a, b);
+ public static bool operator !=(String a, String b)
+ {
+ return !String.Equals(a, b);
}
#if FEATURE_RANDOMIZED_STRING_HASHING
@@ -968,7 +1014,8 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int InternalMarvin32HashString(string s, int strLen, long additionalEntropy);
- internal static bool UseRandomizedHashing() {
+ internal static bool UseRandomizedHashing()
+ {
return InternalUseRandomizedHashing();
}
@@ -997,11 +1044,14 @@ namespace System
// Use this if and only if you need the hashcode to not change across app domains (e.g. you have an app domain agile
// hash table).
- internal int GetLegacyNonRandomizedHashCode() {
- unsafe {
- fixed (char* src = &m_firstChar) {
+ internal int GetLegacyNonRandomizedHashCode()
+ {
+ unsafe
+ {
+ fixed (char* src = &m_firstChar)
+ {
Debug.Assert(src[this.Length] == '\0', "src[this.Length] == '\\0'");
- Debug.Assert( ((int)src)%4 == 0, "Managed string should start at 4 bytes boundary");
+ Debug.Assert(((int)src) % 4 == 0, "Managed string should start at 4 bytes boundary");
#if BIT64
int hash1 = 5381;
#else // !BIT64 (32)
@@ -1010,9 +1060,10 @@ namespace System
int hash2 = hash1;
#if BIT64
- int c;
- char *s = src;
- while ((c = s[0]) != 0) {
+ int c;
+ char* s = src;
+ while ((c = s[0]) != 0)
+ {
hash1 = ((hash1 << 5) + hash1) ^ c;
c = s[1];
if (c == 0)
@@ -1048,12 +1099,14 @@ namespace System
}
}
}
-
+
// Determines whether a specified string is a prefix of the current instance
//
[Pure]
- public Boolean StartsWith(String value) {
- if ((Object)value == null) {
+ public Boolean StartsWith(String value)
+ {
+ if ((Object)value == null)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
@@ -1061,25 +1114,31 @@ namespace System
}
[Pure]
- public Boolean StartsWith(String value, StringComparison comparisonType) {
- if( (Object)value == null) {
- throw new ArgumentNullException(nameof(value));
+ public Boolean StartsWith(String value, StringComparison comparisonType)
+ {
+ if ((Object)value == null)
+ {
+ throw new ArgumentNullException(nameof(value));
}
- if( comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase) {
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
+ if (comparisonType < StringComparison.CurrentCulture || comparisonType > StringComparison.OrdinalIgnoreCase)
+ {
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
}
Contract.EndContractBlock();
- if( (Object)this == (Object)value) {
+ if ((Object)this == (Object)value)
+ {
return true;
}
- if( value.Length == 0) {
+ if (value.Length == 0)
+ {
return true;
}
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
@@ -1090,10 +1149,11 @@ namespace System
return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.None);
case StringComparison.InvariantCultureIgnoreCase:
- return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
+ return CultureInfo.InvariantCulture.CompareInfo.IsPrefix(this, value, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
- if( this.Length < value.Length || m_firstChar != value.m_firstChar) {
+ if (this.Length < value.Length || m_firstChar != value.m_firstChar)
+ {
return false;
}
return (value.Length == 1) ?
@@ -1101,29 +1161,29 @@ namespace System
StartsWithOrdinalHelper(this, value);
case StringComparison.OrdinalIgnoreCase:
- if( this.Length < value.Length) {
+ if (this.Length < value.Length)
+ {
return false;
}
-
-#if FEATURE_COREFX_GLOBALIZATION
+
return (CompareInfo.CompareOrdinalIgnoreCase(this, 0, value.Length, value, 0, value.Length) == 0);
-#else
- return (TextInfo.CompareOrdinalIgnoreCaseEx(this, 0, value, 0, value.Length, value.Length) == 0);
-#endif
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
+ }
}
[Pure]
- public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture) {
- if (null==value) {
+ public Boolean StartsWith(String value, Boolean ignoreCase, CultureInfo culture)
+ {
+ if (null == value)
+ {
throw new ArgumentNullException(nameof(value));
}
Contract.EndContractBlock();
- if((object)this == (object)value) {
+ if ((object)this == (object)value)
+ {
return true;
}
@@ -1135,5 +1195,8 @@ namespace System
return referenceCulture.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
+
+ [Pure]
+ public bool StartsWith(char value) => Length != 0 && m_firstChar == value;
}
-} \ No newline at end of file
+}
diff --git a/src/mscorlib/src/System/String.Manipulation.cs b/src/mscorlib/src/System/String.Manipulation.cs
index e06141d669..33e341c58e 100644
--- a/src/mscorlib/src/System/String.Manipulation.cs
+++ b/src/mscorlib/src/System/String.Manipulation.cs
@@ -18,18 +18,21 @@ namespace System
{
Contract.Requires(dest != null);
Contract.Requires(src != null);
- if (src.Length > dest.Length - destPos) {
+ if (src.Length > dest.Length - destPos)
+ {
throw new IndexOutOfRangeException();
}
Contract.EndContractBlock();
- fixed(char *pDest = &dest.m_firstChar)
- fixed (char *pSrc = &src.m_firstChar) {
- wstrcpy(pDest + destPos, pSrc, src.Length);
- }
+ fixed (char* pDest = &dest.m_firstChar)
+ fixed (char* pSrc = &src.m_firstChar)
+ {
+ wstrcpy(pDest + destPos, pSrc, src.Length);
+ }
}
- public static String Concat(Object arg0) {
+ public static String Concat(Object arg0)
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -39,8 +42,9 @@ namespace System
}
return arg0.ToString();
}
-
- public static String Concat(Object arg0, Object arg1) {
+
+ public static String Concat(Object arg0, Object arg1)
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -48,14 +52,16 @@ namespace System
{
arg0 = String.Empty;
}
-
- if (arg1==null) {
+
+ if (arg1 == null)
+ {
arg1 = String.Empty;
}
return Concat(arg0.ToString(), arg1.ToString());
}
-
- public static String Concat(Object arg0, Object arg1, Object arg2) {
+
+ public static String Concat(Object arg0, Object arg1, Object arg2)
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
@@ -63,42 +69,45 @@ namespace System
{
arg0 = String.Empty;
}
-
- if (arg1==null) {
+
+ if (arg1 == null)
+ {
arg1 = String.Empty;
}
-
- if (arg2==null) {
+
+ if (arg2 == null)
+ {
arg2 = String.Empty;
}
-
+
return Concat(arg0.ToString(), arg1.ToString(), arg2.ToString());
}
- [CLSCompliant(false)]
- public static String Concat(Object arg0, Object arg1, Object arg2, Object arg3, __arglist)
+ [CLSCompliant(false)]
+ public static String Concat(Object arg0, Object arg1, Object arg2, Object arg3, __arglist)
{
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
- Object[] objArgs;
- int argCount;
-
+ Object[] objArgs;
+ int argCount;
+
ArgIterator args = new ArgIterator(__arglist);
//+4 to account for the 4 hard-coded arguments at the beginning of the list.
argCount = args.GetRemainingCount() + 4;
-
+
objArgs = new Object[argCount];
-
+
//Handle the hard-coded arguments
objArgs[0] = arg0;
objArgs[1] = arg1;
objArgs[2] = arg2;
objArgs[3] = arg3;
-
+
//Walk all of the args in the variable part of the argument list.
- for (int i=4; i<argCount; i++) {
+ for (int i = 4; i < argCount; i++)
+ {
objArgs[i] = TypedReference.ToObject(args.GetNextArg());
}
@@ -131,7 +140,7 @@ namespace System
// linked-list style implementation)
var strings = new string[args.Length];
-
+
int totalLength = 0;
for (int i = 0; i < args.Length; i++)
@@ -183,7 +192,7 @@ namespace System
{
if (!en.MoveNext())
return string.Empty;
-
+
// We called MoveNext once, so this will be the first item
T currentValue = en.Current;
@@ -203,7 +212,7 @@ namespace System
}
StringBuilder result = StringBuilderCache.Acquire();
-
+
result.Append(firstString);
do
@@ -233,7 +242,7 @@ namespace System
{
if (!en.MoveNext())
return string.Empty;
-
+
string firstValue = en.Current;
if (!en.MoveNext())
@@ -255,35 +264,40 @@ namespace System
}
- public static String Concat(String str0, String str1) {
+ public static String Concat(String str0, String str1)
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length ==
(str0 == null ? 0 : str0.Length) +
(str1 == null ? 0 : str1.Length));
Contract.EndContractBlock();
- if (IsNullOrEmpty(str0)) {
- if (IsNullOrEmpty(str1)) {
+ if (IsNullOrEmpty(str0))
+ {
+ if (IsNullOrEmpty(str1))
+ {
return String.Empty;
}
return str1;
}
- if (IsNullOrEmpty(str1)) {
+ if (IsNullOrEmpty(str1))
+ {
return str0;
}
int str0Length = str0.Length;
-
+
String result = FastAllocateString(str0Length + str1.Length);
-
- FillStringChecked(result, 0, str0);
+
+ FillStringChecked(result, 0, str0);
FillStringChecked(result, str0Length, str1);
-
+
return result;
}
- public static String Concat(String str0, String str1, String str2) {
+ public static String Concat(String str0, String str1, String str2)
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length ==
(str0 == null ? 0 : str0.Length) +
@@ -316,9 +330,10 @@ namespace System
return result;
}
- public static String Concat(String str0, String str1, String str2, String str3) {
+ public static String Concat(String str0, String str1, String str2, String str3)
+ {
Contract.Ensures(Contract.Result<String>() != null);
- Contract.Ensures(Contract.Result<String>().Length ==
+ Contract.Ensures(Contract.Result<String>().Length ==
(str0 == null ? 0 : str0.Length) +
(str1 == null ? 0 : str1.Length) +
(str2 == null ? 0 : str2.Length) +
@@ -356,7 +371,8 @@ namespace System
return result;
}
- public static String Concat(params String[] values) {
+ public static String Concat(params String[] values)
+ {
if (values == null)
throw new ArgumentNullException(nameof(values));
Contract.Ensures(Contract.Result<String>() != null);
@@ -424,23 +440,27 @@ namespace System
// fall back should be extremely rare.
return copiedLength == totalLength ? result : Concat((string[])values.Clone());
}
-
- public static String Format(String format, Object arg0) {
+
+ public static String Format(String format, Object arg0)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(null, format, new ParamsArray(arg0));
}
-
- public static String Format(String format, Object arg0, Object arg1) {
+
+ public static String Format(String format, Object arg0, Object arg1)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(null, format, new ParamsArray(arg0, arg1));
}
-
- public static String Format(String format, Object arg0, Object arg1, Object arg2) {
+
+ public static String Format(String format, Object arg0, Object arg1, Object arg2)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
}
- public static String Format(String format, params Object[] args) {
+ public static String Format(String format, params Object[] args)
+ {
if (args == null)
{
// To preserve the original exception behavior, throw an exception about format if both
@@ -449,26 +469,30 @@ namespace System
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
-
+
return FormatHelper(null, format, new ParamsArray(args));
}
-
- public static String Format(IFormatProvider provider, String format, Object arg0) {
+
+ public static String Format(IFormatProvider provider, String format, Object arg0)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(provider, format, new ParamsArray(arg0));
}
-
- public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1) {
+
+ public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(provider, format, new ParamsArray(arg0, arg1));
}
-
- public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2) {
+
+ public static String Format(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return FormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
}
- public static String Format(IFormatProvider provider, String format, params Object[] args) {
+ public static String Format(IFormatProvider provider, String format, params Object[] args)
+ {
if (args == null)
{
// To preserve the original exception behavior, throw an exception about format if both
@@ -477,20 +501,21 @@ namespace System
}
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
-
+
return FormatHelper(provider, format, new ParamsArray(args));
}
-
- private static String FormatHelper(IFormatProvider provider, String format, ParamsArray args) {
+
+ private static String FormatHelper(IFormatProvider provider, String format, ParamsArray args)
+ {
if (format == null)
throw new ArgumentNullException(nameof(format));
-
+
return StringBuilderCache.GetStringAndRelease(
StringBuilderCache
.Acquire(format.Length + args.Length * 8)
.AppendFormatHelper(provider, format, args));
}
-
+
public String Insert(int startIndex, String value)
{
if (value == null)
@@ -500,15 +525,15 @@ namespace System
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length == this.Length + value.Length);
Contract.EndContractBlock();
-
+
int oldLength = Length;
int insertLength = value.Length;
-
+
if (oldLength == 0)
return value;
if (insertLength == 0)
return this;
-
+
// In case this computation overflows, newLength will be negative and FastAllocateString throws OutOfMemoryException
int newLength = oldLength + insertLength;
String result = FastAllocateString(newLength);
@@ -557,7 +582,7 @@ namespace System
// Defer argument validation to the internal function
return JoinCore(&separator, 1, value, startIndex, count);
}
-
+
// Joins an array of strings together as one string with a separator between each original string.
//
public static string Join(string separator, params string[] value)
@@ -686,7 +711,7 @@ namespace System
{
return string.Empty;
}
-
+
// We called MoveNext once, so this will be the first item
T currentValue = en.Current;
@@ -738,17 +763,17 @@ namespace System
}
if (startIndex < 0)
{
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
if (count < 0)
{
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
}
if (startIndex > value.Length - count)
{
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_IndexCountBuffer);
}
-
+
if (count <= 1)
{
return count == 0 ?
@@ -803,7 +828,7 @@ namespace System
FillStringChecked(result, copiedLength, currentValue);
copiedLength += valueLen;
}
-
+
if (i < end - 1)
{
// Fill in the separator.
@@ -833,18 +858,20 @@ namespace System
result :
JoinCore(separator, separatorLength, (string[])value.Clone(), startIndex, count);
}
-
+
//
//
[Pure]
- public String PadLeft(int totalWidth) {
+ public String PadLeft(int totalWidth)
+ {
return PadLeft(totalWidth, ' ');
}
[Pure]
- public String PadLeft(int totalWidth, char paddingChar) {
+ public String PadLeft(int totalWidth, char paddingChar)
+ {
if (totalWidth < 0)
- throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(totalWidth), SR.ArgumentOutOfRange_NeedNonNegNum);
int oldLength = Length;
int count = totalWidth - oldLength;
if (count <= 0)
@@ -866,14 +893,16 @@ namespace System
}
[Pure]
- public String PadRight(int totalWidth) {
+ public String PadRight(int totalWidth)
+ {
return PadRight(totalWidth, ' ');
}
[Pure]
- public String PadRight(int totalWidth, char paddingChar) {
+ public String PadRight(int totalWidth, char paddingChar)
+ {
if (totalWidth < 0)
- throw new ArgumentOutOfRangeException(nameof(totalWidth), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(totalWidth), SR.ArgumentOutOfRange_NeedNonNegNum);
int oldLength = Length;
int count = totalWidth - oldLength;
if (count <= 0)
@@ -897,24 +926,24 @@ namespace System
public String Remove(int startIndex, int count)
{
if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex),
- Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
+ SR.ArgumentOutOfRange_StartIndex);
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(count),
+ SR.ArgumentOutOfRange_NegativeCount);
if (count > Length - startIndex)
- throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ throw new ArgumentOutOfRangeException(nameof(count),
+ SR.ArgumentOutOfRange_IndexCount);
Contract.Ensures(Contract.Result<String>() != null);
Contract.Ensures(Contract.Result<String>().Length == this.Length - count);
Contract.EndContractBlock();
-
+
if (count == 0)
return this;
int newLength = Length - count;
if (newLength == 0)
return String.Empty;
-
+
String result = FastAllocateString(newLength);
unsafe
{
@@ -931,22 +960,113 @@ namespace System
}
// a remove that just takes a startindex.
- public string Remove( int startIndex ) {
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex),
- Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ public string Remove(int startIndex)
+ {
+ if (startIndex < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
+ SR.ArgumentOutOfRange_StartIndex);
}
-
- if (startIndex >= Length) {
- throw new ArgumentOutOfRangeException(nameof(startIndex),
- Environment.GetResourceString("ArgumentOutOfRange_StartIndexLessThanLength"));
+
+ if (startIndex >= Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex),
+ SR.ArgumentOutOfRange_StartIndexLessThanLength);
}
-
+
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return Substring(0, startIndex);
- }
+ }
+
+ public string Replace(string oldValue, string newValue, bool ignoreCase, CultureInfo culture)
+ {
+ Contract.Ensures(Contract.Result<String>() != null);
+ Contract.EndContractBlock();
+
+ return ReplaceCore(oldValue, newValue, culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
+ }
+
+ public string Replace(string oldValue, string newValue, StringComparison comparisonType)
+ {
+ Contract.Ensures(Contract.Result<String>() != null);
+ Contract.EndContractBlock();
+
+ switch (comparisonType)
+ {
+ case StringComparison.CurrentCulture:
+ return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture, CompareOptions.None);
+
+ case StringComparison.CurrentCultureIgnoreCase:
+ return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase);
+
+ case StringComparison.InvariantCulture:
+ return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, CompareOptions.None);
+
+ case StringComparison.InvariantCultureIgnoreCase:
+ return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, CompareOptions.IgnoreCase);
+
+ case StringComparison.Ordinal:
+ return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, CompareOptions.Ordinal);
+
+ case StringComparison.OrdinalIgnoreCase:
+ return ReplaceCore(oldValue, newValue, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase);
+
+ default:
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
+ }
+ }
+
+ private unsafe String ReplaceCore(string oldValue, string newValue, CultureInfo culture, CompareOptions options)
+ {
+ if (oldValue == null)
+ throw new ArgumentNullException(nameof(oldValue));
+
+ // If they asked to replace oldValue with a null, replace all occurences
+ // with the empty string.
+ if (newValue == null)
+ newValue = string.Empty;
+
+ CultureInfo referenceCulture = culture ?? CultureInfo.CurrentCulture;
+ StringBuilder result = StringBuilderCache.Acquire();
+
+ int startIndex = 0;
+ int index = 0;
+
+ int matchLength = 0;
+
+ bool hasDoneAnyReplacements = false;
+
+ do
+ {
+ index = referenceCulture.CompareInfo.IndexOfCore(this, oldValue, startIndex, m_stringLength - startIndex, options, &matchLength);
+ if (index >= 0)
+ {
+ // append the unmodified portion of string
+ result.Append(this, startIndex, index - startIndex);
+
+ // append the replacement
+ result.Append(newValue);
+
+ startIndex = index + matchLength;
+ hasDoneAnyReplacements = true;
+ }
+ else if (!hasDoneAnyReplacements)
+ {
+ // small optimization,
+ // if we have not done any replacements,
+ // we will return the original string
+ return this;
+ }
+ else
+ {
+ result.Append(this, startIndex, m_stringLength - startIndex);
+ }
+ } while (index >= 0);
+
+ return StringBuilderCache.GetStringAndRelease(result);
+ }
// Replaces all instances of oldChar with newChar.
//
@@ -1034,12 +1154,14 @@ namespace System
return ReplaceInternal(oldValue, newValue);
}
- public unsafe String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None) {
+ public unsafe String[] Split(char separator, StringSplitOptions options = StringSplitOptions.None)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(&separator, 1, int.MaxValue, options);
}
- public unsafe String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None) {
+ public unsafe String[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(&separator, 1, count, options);
}
@@ -1053,7 +1175,8 @@ namespace System
// If the separator is null
// whitespace (i.e., Character.IsWhitespace) is used as the separator.
//
- public String [] Split(params char [] separator) {
+ public String[] Split(params char[] separator)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, Int32.MaxValue, StringSplitOptions.None);
}
@@ -1069,12 +1192,14 @@ namespace System
// If there are more than count different strings, the last n-(count-1)
// elements are concatenated and added as the last String.
//
- public string[] Split(char[] separator, int count) {
+ public string[] Split(char[] separator, int count)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, count, StringSplitOptions.None);
}
- public String[] Split(char[] separator, StringSplitOptions options) {
+ public String[] Split(char[] separator, StringSplitOptions options)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator, Int32.MaxValue, options);
}
@@ -1098,72 +1223,79 @@ namespace System
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ SR.ArgumentOutOfRange_NegativeCount);
if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", options));
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, options));
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
bool omitEmptyEntries = (options == StringSplitOptions.RemoveEmptyEntries);
- if ((count == 0) || (omitEmptyEntries && this.Length == 0))
+ if ((count == 0) || (omitEmptyEntries && this.Length == 0))
{
- return EmptyArray<String>.Value;
+ return Array.Empty<String>();
}
if (count == 1)
{
return new String[] { this };
}
-
+
int[] sepList = new int[Length];
int numReplaces = MakeSeparatorList(separators, separatorsLength, sepList);
-
+
// Handle the special case of no replaces.
- if (0 == numReplaces) {
+ if (0 == numReplaces)
+ {
return new String[] { this };
}
- if(omitEmptyEntries)
+ if (omitEmptyEntries)
{
return SplitOmitEmptyEntries(sepList, null, 1, numReplaces, count);
}
- else
+ else
{
return SplitKeepEmptyEntries(sepList, null, 1, numReplaces, count);
}
}
- public String[] Split(String separator, StringSplitOptions options = StringSplitOptions.None) {
+ public String[] Split(String separator, StringSplitOptions options = StringSplitOptions.None)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator ?? String.Empty, null, Int32.MaxValue, options);
}
- public String[] Split(String separator, Int32 count, StringSplitOptions options = StringSplitOptions.None) {
+ public String[] Split(String separator, Int32 count, StringSplitOptions options = StringSplitOptions.None)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(separator ?? String.Empty, null, count, options);
}
- public String [] Split(String[] separator, StringSplitOptions options) {
+ public String[] Split(String[] separator, StringSplitOptions options)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(null, separator, Int32.MaxValue, options);
}
- public String[] Split(String[] separator, Int32 count, StringSplitOptions options) {
+ public String[] Split(String[] separator, Int32 count, StringSplitOptions options)
+ {
Contract.Ensures(Contract.Result<String[]>() != null);
return SplitInternal(null, separator, count, options);
}
private String[] SplitInternal(String separator, String[] separators, Int32 count, StringSplitOptions options)
{
- if (count < 0) {
+ if (count < 0)
+ {
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ SR.ArgumentOutOfRange_NegativeCount);
}
- if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries) {
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)options));
+ if (options < StringSplitOptions.None || options > StringSplitOptions.RemoveEmptyEntries)
+ {
+ throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options));
}
Contract.EndContractBlock();
@@ -1171,15 +1303,18 @@ namespace System
bool singleSeparator = separator != null;
- if (!singleSeparator && (separators == null || separators.Length == 0)) {
- return SplitInternal((char[]) null, count, options);
+ if (!singleSeparator && (separators == null || separators.Length == 0))
+ {
+ return SplitInternal((char[])null, count, options);
}
-
- if ((count == 0) || (omitEmptyEntries && this.Length ==0)) {
- return EmptyArray<String>.Value;
+
+ if ((count == 0) || (omitEmptyEntries && this.Length == 0))
+ {
+ return Array.Empty<String>();
}
- if (count == 1 || (singleSeparator && separator.Length == 0)) {
+ if (count == 1 || (singleSeparator && separator.Length == 0))
+ {
return new String[] { this };
}
@@ -1188,40 +1323,46 @@ namespace System
int defaultLength;
int numReplaces;
- if (singleSeparator) {
+ if (singleSeparator)
+ {
lengthList = null;
defaultLength = separator.Length;
numReplaces = MakeSeparatorList(separator, sepList);
}
- else {
+ else
+ {
lengthList = new int[Length];
defaultLength = 0;
numReplaces = MakeSeparatorList(separators, sepList, lengthList);
}
// Handle the special case of no replaces.
- if (0 == numReplaces) {
+ if (0 == numReplaces)
+ {
return new String[] { this };
}
-
- if (omitEmptyEntries) {
+
+ if (omitEmptyEntries)
+ {
return SplitOmitEmptyEntries(sepList, lengthList, defaultLength, numReplaces, count);
}
- else {
+ else
+ {
return SplitKeepEmptyEntries(sepList, lengthList, defaultLength, numReplaces, count);
}
- }
-
+ }
+
// Note a special case in this function:
// If there is no separator in the string, a string array which only contains
// the original string will be returned regardless of the count.
//
- private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) {
+ private String[] SplitKeepEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count)
+ {
Contract.Requires(numReplaces >= 0);
Contract.Requires(count >= 2);
Contract.Ensures(Contract.Result<String[]>() != null);
-
+
int currIndex = 0;
int arrIndex = 0;
@@ -1230,30 +1371,33 @@ namespace System
//Allocate space for the new array.
//+1 for the string from the end of the last replace to the end of the String.
- String[] splitStrings = new String[numActualReplaces+1];
+ String[] splitStrings = new String[numActualReplaces + 1];
- for (int i = 0; i < numActualReplaces && currIndex < Length; i++) {
- splitStrings[arrIndex++] = Substring(currIndex, sepList[i]-currIndex );
- currIndex=sepList[i] + ((lengthList == null) ? defaultLength : lengthList[i]);
+ for (int i = 0; i < numActualReplaces && currIndex < Length; i++)
+ {
+ splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex);
+ currIndex = sepList[i] + ((lengthList == null) ? defaultLength : lengthList[i]);
}
//Handle the last string at the end of the array if there is one.
- if (currIndex < Length && numActualReplaces >= 0) {
+ if (currIndex < Length && numActualReplaces >= 0)
+ {
splitStrings[arrIndex] = Substring(currIndex);
- }
- else if (arrIndex==numActualReplaces) {
+ }
+ else if (arrIndex == numActualReplaces)
+ {
//We had a separator character at the end of a string. Rather than just allowing
//a null character, we'll replace the last element in the array with an empty string.
splitStrings[arrIndex] = String.Empty;
-
}
return splitStrings;
}
-
+
// This function will not keep the Empty String
- private String[] SplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count) {
+ private String[] SplitOmitEmptyEntries(Int32[] sepList, Int32[] lengthList, Int32 defaultLength, Int32 numReplaces, int count)
+ {
Contract.Requires(numReplaces >= 0);
Contract.Requires(count >= 2);
Contract.Ensures(Contract.Result<String[]>() != null);
@@ -1262,20 +1406,24 @@ namespace System
// filled completely in this function, we will create a
// new array and copy string references to that new array.
- int maxItems = (numReplaces < count) ? (numReplaces+1): count ;
+ int maxItems = (numReplaces < count) ? (numReplaces + 1) : count;
String[] splitStrings = new String[maxItems];
int currIndex = 0;
int arrIndex = 0;
- for(int i=0; i< numReplaces && currIndex < Length; i++) {
- if( sepList[i]-currIndex > 0) {
- splitStrings[arrIndex++] = Substring(currIndex, sepList[i]-currIndex );
+ for (int i = 0; i < numReplaces && currIndex < Length; i++)
+ {
+ if (sepList[i] - currIndex > 0)
+ {
+ splitStrings[arrIndex++] = Substring(currIndex, sepList[i] - currIndex);
}
- currIndex=sepList[i] + ((lengthList == null) ? defaultLength : lengthList[i]);
- if( arrIndex == count -1 ) {
+ currIndex = sepList[i] + ((lengthList == null) ? defaultLength : lengthList[i]);
+ if (arrIndex == count - 1)
+ {
// If all the remaining entries at the end are empty, skip them
- while( i < numReplaces - 1 && currIndex == sepList[++i]) {
+ while (i < numReplaces - 1 && currIndex == sepList[++i])
+ {
currIndex += ((lengthList == null) ? defaultLength : lengthList[i]);
}
break;
@@ -1286,19 +1434,22 @@ namespace System
Debug.Assert(arrIndex < maxItems);
//Handle the last string at the end of the array if there is one.
- if (currIndex< Length) {
+ if (currIndex < Length)
+ {
splitStrings[arrIndex++] = Substring(currIndex);
}
String[] stringArray = splitStrings;
- if( arrIndex!= maxItems) {
+ if (arrIndex != maxItems)
+ {
stringArray = new String[arrIndex];
- for( int j = 0; j < arrIndex; j++) {
+ for (int j = 0; j < arrIndex; j++)
+ {
stringArray[j] = splitStrings[j];
- }
+ }
}
return stringArray;
- }
+ }
//--------------------------------------------------------------------
// This function returns the number of the places within this instance where
@@ -1306,56 +1457,71 @@ namespace System
// Args: separator -- A string containing all of the split characters.
// sepList -- an array of ints for split char indicies.
//--------------------------------------------------------------------
- private unsafe int MakeSeparatorList(char* separators, int separatorsLength, int[] sepList) {
+ private unsafe int MakeSeparatorList(char* separators, int separatorsLength, int[] sepList)
+ {
Debug.Assert(separatorsLength >= 0, "separatorsLength >= 0");
- int foundCount=0;
+ int foundCount = 0;
- if (separators == null || separatorsLength == 0) {
- fixed (char* pwzChars = &this.m_firstChar) {
+ if (separators == null || separatorsLength == 0)
+ {
+ fixed (char* pwzChars = &m_firstChar)
+ {
//If they passed null or an empty string, look for whitespace.
- for (int i=0; i < Length && foundCount < sepList.Length; i++) {
- if (Char.IsWhiteSpace(pwzChars[i])) {
- sepList[foundCount++]=i;
+ for (int i = 0; i < Length && foundCount < sepList.Length; i++)
+ {
+ if (Char.IsWhiteSpace(pwzChars[i]))
+ {
+ sepList[foundCount++] = i;
}
}
}
- }
- else {
+ }
+ else
+ {
int sepListCount = sepList.Length;
//If they passed in a string of chars, actually look for those chars.
- fixed (char* pwzChars = &this.m_firstChar) {
- for (int i=0; i< Length && foundCount < sepListCount; i++) {
+ fixed (char* pwzChars = &m_firstChar)
+ {
+ for (int i = 0; i < Length && foundCount < sepListCount; i++)
+ {
char* pSep = separators;
- for (int j = 0; j < separatorsLength; j++, pSep++) {
- if ( pwzChars[i] == *pSep) {
- sepList[foundCount++]=i;
- break;
- }
+ for (int j = 0; j < separatorsLength; j++, pSep++)
+ {
+ if (pwzChars[i] == *pSep)
+ {
+ sepList[foundCount++] = i;
+ break;
+ }
}
}
}
}
return foundCount;
- }
-
+ }
+
//--------------------------------------------------------------------
// This function returns number of the places within baseString where
// instances of the separator string occurs.
// Args: separator -- the separator
// sepList -- an array of ints for split string indicies.
//--------------------------------------------------------------------
- private unsafe int MakeSeparatorList(string separator, int[] sepList) {
+ private unsafe int MakeSeparatorList(string separator, int[] sepList)
+ {
Debug.Assert(!string.IsNullOrEmpty(separator), "!string.IsNullOrEmpty(separator)");
int foundCount = 0;
int sepListCount = sepList.Length;
int currentSepLength = separator.Length;
- fixed (char* pwzChars = &this.m_firstChar) {
- for (int i = 0; i < Length && foundCount < sepListCount; i++) {
- if (pwzChars[i] == separator[0] && currentSepLength <= Length - i) {
+ fixed (char* pwzChars = &m_firstChar)
+ {
+ for (int i = 0; i < Length && foundCount < sepListCount; i++)
+ {
+ if (pwzChars[i] == separator[0] && currentSepLength <= Length - i)
+ {
if (currentSepLength == 1
- || String.CompareOrdinal(this, i, separator, 0, currentSepLength) == 0) {
+ || String.CompareOrdinal(this, i, separator, 0, currentSepLength) == 0)
+ {
sepList[foundCount] = i;
foundCount++;
i += currentSepLength - 1;
@@ -1373,24 +1539,31 @@ namespace System
// sepList -- an array of ints for split string indicies.
// lengthList -- an array of ints for split string lengths.
//--------------------------------------------------------------------
- private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList) {
+ private unsafe int MakeSeparatorList(String[] separators, int[] sepList, int[] lengthList)
+ {
Debug.Assert(separators != null && separators.Length > 0, "separators != null && separators.Length > 0");
-
+
int foundCount = 0;
int sepListCount = sepList.Length;
int sepCount = separators.Length;
- fixed (char* pwzChars = &this.m_firstChar) {
- for (int i=0; i< Length && foundCount < sepListCount; i++) {
- for( int j =0; j < separators.Length; j++) {
+ fixed (char* pwzChars = &m_firstChar)
+ {
+ for (int i = 0; i < Length && foundCount < sepListCount; i++)
+ {
+ for (int j = 0; j < separators.Length; j++)
+ {
String separator = separators[j];
- if (String.IsNullOrEmpty(separator)) {
+ if (String.IsNullOrEmpty(separator))
+ {
continue;
}
Int32 currentSepLength = separator.Length;
- if ( pwzChars[i] == separator[0] && currentSepLength <= Length - i) {
- if (currentSepLength == 1
- || String.CompareOrdinal(this, i, separator, 0, currentSepLength) == 0) {
+ if (pwzChars[i] == separator[0] && currentSepLength <= Length - i)
+ {
+ if (currentSepLength == 1
+ || String.CompareOrdinal(this, i, separator, 0, currentSepLength) == 0)
+ {
sepList[foundCount] = i;
lengthList[foundCount] = currentSepLength;
foundCount++;
@@ -1403,71 +1576,82 @@ namespace System
}
return foundCount;
}
-
+
// Returns a substring of this string.
//
- public String Substring (int startIndex) {
- return this.Substring (startIndex, Length-startIndex);
+ public String Substring(int startIndex)
+ {
+ return this.Substring(startIndex, Length - startIndex);
}
-
+
// Returns a substring of this string.
//
- public String Substring(int startIndex, int length) {
-
+ public String Substring(int startIndex, int length)
+ {
//Bounds Checking.
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ if (startIndex < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
- if (startIndex > Length) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
+ if (startIndex > Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndexLargerThanLength);
}
- if (length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ if (length < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
- if (startIndex > Length - length) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
+ if (startIndex > Length - length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_IndexLength);
}
Contract.EndContractBlock();
- if( length == 0) {
+ if (length == 0)
+ {
return String.Empty;
}
- if( startIndex == 0 && length == this.Length) {
+ if (startIndex == 0 && length == this.Length)
+ {
return this;
}
return InternalSubString(startIndex, length);
}
- unsafe string InternalSubString(int startIndex, int length) {
- Debug.Assert( startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
- Debug.Assert( length >= 0 && startIndex <= this.Length - length, "length is out of range!");
-
+ private unsafe string InternalSubString(int startIndex, int length)
+ {
+ Debug.Assert(startIndex >= 0 && startIndex <= this.Length, "StartIndex is out of range!");
+ Debug.Assert(length >= 0 && startIndex <= this.Length - length, "length is out of range!");
+
String result = FastAllocateString(length);
- fixed(char* dest = &result.m_firstChar)
- fixed(char* src = &this.m_firstChar) {
- wstrcpy(dest, src + startIndex, length);
- }
+ fixed (char* dest = &result.m_firstChar)
+ fixed (char* src = &m_firstChar)
+ {
+ wstrcpy(dest, src + startIndex, length);
+ }
return result;
}
-
+
// Creates a copy of this string in lower case.
[Pure]
- public String ToLower() {
+ public String ToLower()
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this.ToLower(CultureInfo.CurrentCulture);
}
-
+
// Creates a copy of this string in lower case. The culture is set by culture.
[Pure]
- public String ToLower(CultureInfo culture) {
+ public String ToLower(CultureInfo culture)
+ {
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
@@ -1479,24 +1663,27 @@ namespace System
// Creates a copy of this string in lower case based on invariant culture.
[Pure]
- public String ToLowerInvariant() {
+ public String ToLowerInvariant()
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this.ToLower(CultureInfo.InvariantCulture);
}
-
+
// Creates a copy of this string in upper case.
[Pure]
- public String ToUpper() {
+ public String ToUpper()
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this.ToUpper(CultureInfo.CurrentCulture);
}
-
+
// Creates a copy of this string in upper case. The culture is set by culture.
[Pure]
- public String ToUpper(CultureInfo culture) {
+ public String ToUpper(CultureInfo culture)
+ {
if (culture == null)
{
throw new ArgumentNullException(nameof(culture));
@@ -1509,7 +1696,8 @@ namespace System
//Creates a copy of this string in upper case based on invariant culture.
[Pure]
- public String ToUpperInvariant() {
+ public String ToUpperInvariant()
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this.ToUpper(CultureInfo.InvariantCulture);
diff --git a/src/mscorlib/src/System/String.Searching.cs b/src/mscorlib/src/System/String.Searching.cs
index 2620cfd0dc..411a45c1a7 100644
--- a/src/mscorlib/src/System/String.Searching.cs
+++ b/src/mscorlib/src/System/String.Searching.cs
@@ -11,30 +11,34 @@ namespace System
public partial class String
{
[Pure]
- public bool Contains( string value ) {
- return ( IndexOf(value, StringComparison.Ordinal) >=0 );
+ public bool Contains(string value)
+ {
+ return (IndexOf(value, StringComparison.Ordinal) >= 0);
}
-
+
// Returns the index of the first occurrence of a specified character in the current instance.
// The search starts at startIndex and runs thorough the next count characters.
//
[Pure]
- public int IndexOf(char value) {
+ public int IndexOf(char value)
+ {
return IndexOf(value, 0, this.Length);
}
[Pure]
- public int IndexOf(char value, int startIndex) {
+ public int IndexOf(char value, int startIndex)
+ {
return IndexOf(value, startIndex, this.Length - startIndex);
}
[Pure]
- public unsafe int IndexOf(char value, int startIndex, int count) {
+ public unsafe int IndexOf(char value, int startIndex, int count)
+ {
if (startIndex < 0 || startIndex > Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || count > Length - startIndex)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
fixed (char* pChars = &m_firstChar)
{
@@ -62,39 +66,42 @@ namespace System
return -1;
- ReturnIndex3: pCh++;
- ReturnIndex2: pCh++;
- ReturnIndex1: pCh++;
- ReturnIndex:
+ ReturnIndex3: pCh++;
+ ReturnIndex2: pCh++;
+ ReturnIndex1: pCh++;
+ ReturnIndex:
return (int)(pCh - pChars);
}
}
-
+
// Returns the index of the first occurrence of any specified character in the current instance.
// The search starts at startIndex and runs to startIndex + count -1.
//
- [Pure]
- public int IndexOfAny(char [] anyOf) {
- return IndexOfAny(anyOf,0, this.Length);
+ [Pure]
+ public int IndexOfAny(char[] anyOf)
+ {
+ return IndexOfAny(anyOf, 0, this.Length);
}
-
+
[Pure]
- public int IndexOfAny(char [] anyOf, int startIndex) {
+ public int IndexOfAny(char[] anyOf, int startIndex)
+ {
return IndexOfAny(anyOf, startIndex, this.Length - startIndex);
}
-
+
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern int IndexOfAny(char [] anyOf, int startIndex, int count);
-
-
+ public extern int IndexOfAny(char[] anyOf, int startIndex, int count);
+
+
// Determines the position within this string of the first occurrence of the specified
// string, according to the specified search criteria. The search begins at
// the first character of this string, it is case-sensitive and the current culture
// comparison is used.
//
[Pure]
- public int IndexOf(String value) {
+ public int IndexOf(String value)
+ {
return IndexOf(value, StringComparison.CurrentCulture);
}
@@ -103,7 +110,8 @@ namespace System
// startIndex, it is case-sensitive and the current culture comparison is used.
//
[Pure]
- public int IndexOf(String value, int startIndex) {
+ public int IndexOf(String value, int startIndex)
+ {
return IndexOf(value, startIndex, StringComparison.CurrentCulture);
}
@@ -112,43 +120,50 @@ namespace System
// startIndex, ends at endIndex and the current culture comparison is used.
//
[Pure]
- public int IndexOf(String value, int startIndex, int count) {
- if (startIndex < 0 || startIndex > this.Length) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ public int IndexOf(String value, int startIndex, int count)
+ {
+ if (startIndex < 0 || startIndex > this.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
}
- if (count < 0 || count > this.Length - startIndex) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ if (count < 0 || count > this.Length - startIndex)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
Contract.EndContractBlock();
-
+
return IndexOf(value, startIndex, count, StringComparison.CurrentCulture);
}
[Pure]
- public int IndexOf(String value, StringComparison comparisonType) {
+ public int IndexOf(String value, StringComparison comparisonType)
+ {
return IndexOf(value, 0, this.Length, comparisonType);
}
[Pure]
- public int IndexOf(String value, int startIndex, StringComparison comparisonType) {
+ public int IndexOf(String value, int startIndex, StringComparison comparisonType)
+ {
return IndexOf(value, startIndex, this.Length - startIndex, comparisonType);
}
[Pure]
- public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
+ public int IndexOf(String value, int startIndex, int count, StringComparison comparisonType)
+ {
// Validate inputs
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0 || startIndex > this.Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || startIndex > this.Length - count)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
Contract.EndContractBlock();
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, CompareOptions.None);
@@ -171,8 +186,8 @@ namespace System
return TextInfo.IndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
+ }
}
// Returns the index of the last occurrence of a specified character in the current instance.
@@ -181,25 +196,28 @@ namespace System
// index within the string.
//
[Pure]
- public int LastIndexOf(char value) {
- return LastIndexOf(value, this.Length-1, this.Length);
+ public int LastIndexOf(char value)
+ {
+ return LastIndexOf(value, this.Length - 1, this.Length);
}
[Pure]
- public int LastIndexOf(char value, int startIndex){
- return LastIndexOf(value,startIndex,startIndex + 1);
+ public int LastIndexOf(char value, int startIndex)
+ {
+ return LastIndexOf(value, startIndex, startIndex + 1);
}
[Pure]
- public unsafe int LastIndexOf(char value, int startIndex, int count) {
+ public unsafe int LastIndexOf(char value, int startIndex, int count)
+ {
if (Length == 0)
return -1;
if (startIndex < 0 || startIndex >= Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (count < 0 || count - 1 > startIndex)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
fixed (char* pChars = &m_firstChar)
{
@@ -228,55 +246,61 @@ namespace System
return -1;
- ReturnIndex3: pCh--;
- ReturnIndex2: pCh--;
- ReturnIndex1: pCh--;
- ReturnIndex:
+ ReturnIndex3: pCh--;
+ ReturnIndex2: pCh--;
+ ReturnIndex1: pCh--;
+ ReturnIndex:
return (int)(pCh - pChars);
}
}
-
+
// Returns the index of the last occurrence of any specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
-
+
//ForceInline ... Jit can't recognize String.get_Length to determine that this is "fluff"
[Pure]
- public int LastIndexOfAny(char [] anyOf) {
- return LastIndexOfAny(anyOf,this.Length-1,this.Length);
+ public int LastIndexOfAny(char[] anyOf)
+ {
+ return LastIndexOfAny(anyOf, this.Length - 1, this.Length);
}
-
+
[Pure]
- public int LastIndexOfAny(char [] anyOf, int startIndex) {
- return LastIndexOfAny(anyOf,startIndex,startIndex + 1);
+ public int LastIndexOfAny(char[] anyOf, int startIndex)
+ {
+ return LastIndexOfAny(anyOf, startIndex, startIndex + 1);
}
[Pure]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern int LastIndexOfAny(char [] anyOf, int startIndex, int count);
-
-
+ public extern int LastIndexOfAny(char[] anyOf, int startIndex, int count);
+
+
// Returns the index of the last occurrence of any character in value in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
[Pure]
- public int LastIndexOf(String value) {
- return LastIndexOf(value, this.Length-1,this.Length, StringComparison.CurrentCulture);
+ public int LastIndexOf(String value)
+ {
+ return LastIndexOf(value, this.Length - 1, this.Length, StringComparison.CurrentCulture);
}
[Pure]
- public int LastIndexOf(String value, int startIndex) {
+ public int LastIndexOf(String value, int startIndex)
+ {
return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture);
}
[Pure]
- public int LastIndexOf(String value, int startIndex, int count) {
- if (count<0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ public int LastIndexOf(String value, int startIndex, int count)
+ {
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
}
Contract.EndContractBlock();
@@ -284,17 +308,20 @@ namespace System
}
[Pure]
- public int LastIndexOf(String value, StringComparison comparisonType) {
- return LastIndexOf(value, this.Length-1, this.Length, comparisonType);
+ public int LastIndexOf(String value, StringComparison comparisonType)
+ {
+ return LastIndexOf(value, this.Length - 1, this.Length, comparisonType);
}
[Pure]
- public int LastIndexOf(String value, int startIndex, StringComparison comparisonType) {
+ public int LastIndexOf(String value, int startIndex, StringComparison comparisonType)
+ {
return LastIndexOf(value, startIndex, startIndex + 1, comparisonType);
}
[Pure]
- public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType) {
+ public int LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType)
+ {
if (value == null)
throw new ArgumentNullException(nameof(value));
Contract.EndContractBlock();
@@ -305,8 +332,8 @@ namespace System
// Now after handling empty strings, make sure we're not out of range
if (startIndex < 0 || startIndex > this.Length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
-
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
+
// Make sure that we allow startIndex == this.Length
if (startIndex == this.Length)
{
@@ -321,10 +348,11 @@ namespace System
// 2nd half of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0.
if (count < 0 || startIndex - count + 1 < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Count"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
- switch (comparisonType) {
+ switch (comparisonType)
+ {
case StringComparison.CurrentCulture:
return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.None);
@@ -338,15 +366,15 @@ namespace System
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
case StringComparison.Ordinal:
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.Ordinal);
-
+
case StringComparison.OrdinalIgnoreCase:
if (value.IsAscii() && this.IsAscii())
return CultureInfo.InvariantCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, CompareOptions.IgnoreCase);
else
return TextInfo.LastIndexOfStringOrdinalIgnoreCase(this, value, startIndex, count);
default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
+ throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType));
+ }
}
}
}
diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs
index 175e396633..f3a4d0f197 100644
--- a/src/mscorlib/src/System/String.cs
+++ b/src/mscorlib/src/System/String.cs
@@ -11,7 +11,9 @@
**
**
===========================================================*/
-namespace System {
+
+namespace System
+{
using System.Text;
using System;
using System.Runtime;
@@ -19,9 +21,9 @@ namespace System {
using System.Globalization;
using System.Threading;
using System.Collections;
- using System.Collections.Generic;
+ using System.Collections.Generic;
using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
+ using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Diagnostics;
@@ -36,12 +38,11 @@ namespace System {
// instance and return the result as a new String. All comparison methods are
// implemented as a part of String. As with arrays, character positions
// (indices) are zero-based.
-
+
[Serializable]
public sealed partial class String : IComparable, ICloneable, IConvertible, IEnumerable
, IComparable<String>, IEnumerable<char>, IEquatable<String>
{
-
//
//NOTE NOTE NOTE NOTE
//These fields map directly onto the fields in an EE StringObject. See object.h for the layout.
@@ -51,7 +52,7 @@ namespace System {
// For empty strings, this will be '\0' since
// strings are both null-terminated and length prefixed
[NonSerialized] private char m_firstChar;
-
+
// The Empty constant holds the empty string value. It is initialized by the EE during startup.
// It is treated as intrinsic by the JIT as so the static constructor would never run.
// Leaving it uninitialized would confuse debuggers.
@@ -67,7 +68,8 @@ namespace System {
// than 0x80) before security is fully initialized. Without security initialized, we can't grab resources (the nlp's)
// from the assembly. This provides a workaround for that problem and should NOT be used anywhere else.
//
- internal unsafe static string SmallCharToUpper(string strIn) {
+ internal unsafe static string SmallCharToUpper(string strIn)
+ {
Contract.Requires(strIn != null);
Contract.EndContractBlock();
//
@@ -78,9 +80,10 @@ namespace System {
//
int length = strIn.Length;
String strOut = FastAllocateString(length);
- fixed (char * inBuff = &strIn.m_firstChar, outBuff = &strOut.m_firstChar) {
-
- for(int i = 0; i < length; i++) {
+ fixed (char* inBuff = &strIn.m_firstChar, outBuff = &strOut.m_firstChar)
+ {
+ for (int i = 0; i < length; i++)
+ {
int c = inBuff[i];
Debug.Assert(c <= 0x7F, "string has to be ASCII");
@@ -90,16 +93,17 @@ namespace System {
outBuff[i] = (char)c;
}
- Debug.Assert(outBuff[length]=='\0', "outBuff[length]=='\0'");
+ Debug.Assert(outBuff[length] == '\0', "outBuff[length]=='\0'");
}
return strOut;
}
-
+
// Gets the character at a specified position.
//
// Spec#: Apply the precondition here using a contract assembly. Potential perf issue.
[System.Runtime.CompilerServices.IndexerName("Chars")]
- public extern char this[int index] {
+ public extern char this[int index]
+ {
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
@@ -114,31 +118,32 @@ namespace System {
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NegativeCount);
if (sourceIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
if (count > Length - sourceIndex)
- throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_IndexCount);
if (destinationIndex > destination.Length - count || destinationIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(destinationIndex), Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_IndexCount);
Contract.EndContractBlock();
// Note: fixed does not like empty arrays
if (count > 0)
{
- fixed (char* src = &this.m_firstChar)
- fixed (char* dest = destination)
- wstrcpy(dest + destinationIndex, src + sourceIndex, count);
+ fixed (char* src = &m_firstChar)
+ fixed (char* dest = destination)
+ wstrcpy(dest + destinationIndex, src + sourceIndex, count);
}
}
-
+
// Returns the entire string as an array of characters.
- unsafe public char[] ToCharArray() {
+ unsafe public char[] ToCharArray()
+ {
int length = Length;
if (length > 0)
{
char[] chars = new char[length];
- fixed (char* src = &this.m_firstChar) fixed (char* dest = chars)
+ fixed (char* src = &m_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src, length);
}
@@ -147,22 +152,22 @@ namespace System {
return Array.Empty<char>();
}
-
+
// Returns a substring of this string as an array of characters.
//
unsafe public char[] ToCharArray(int startIndex, int length)
{
// Range check everything.
if (startIndex < 0 || startIndex > Length || startIndex > Length - length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
if (length < 0)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (length > 0)
{
char[] chars = new char[length];
- fixed (char* src = &this.m_firstChar) fixed (char* dest = chars)
+ fixed (char* src = &m_firstChar) fixed (char* dest = chars)
{
wstrcpy(dest, src + startIndex, length);
}
@@ -173,16 +178,19 @@ namespace System {
}
[Pure]
- public static bool IsNullOrEmpty(String value) {
+ public static bool IsNullOrEmpty(String value)
+ {
return (value == null || value.Length == 0);
}
[Pure]
- public static bool IsNullOrWhiteSpace(String value) {
+ public static bool IsNullOrWhiteSpace(String value)
+ {
if (value == null) return true;
- for(int i = 0; i < value.Length; i++) {
- if(!Char.IsWhiteSpace(value[i])) return false;
+ for (int i = 0; i < value.Length; i++)
+ {
+ if (!Char.IsWhiteSpace(value[i])) return false;
}
return true;
@@ -196,55 +204,60 @@ namespace System {
/// The actually code generated for this will be one instruction and will be inlined.
//
// Spec#: Add postcondition in a contract assembly. Potential perf problem.
- public extern int Length {
+ public extern int Length
+ {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
}
-
+
// Creates a new string with the characters copied in from ptr. If
// ptr is null, a 0-length string (like String.Empty) is returned.
//
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe public extern String(char *value);
+ unsafe public extern String(char* value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe public extern String(char *value, int startIndex, int length);
-
+ unsafe public extern String(char* value, int startIndex, int length);
+
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe public extern String(sbyte *value);
+ unsafe public extern String(sbyte* value);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe public extern String(sbyte *value, int startIndex, int length);
+ unsafe public extern String(sbyte* value, int startIndex, int length);
[CLSCompliant(false), MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe public extern String(sbyte *value, int startIndex, int length, Encoding enc);
-
- unsafe static private String CreateString(sbyte *value, int startIndex, int length, Encoding enc) {
+ unsafe public extern String(sbyte* value, int startIndex, int length, Encoding enc);
+
+ unsafe static private String CreateString(sbyte* value, int startIndex, int length, Encoding enc)
+ {
if (enc == null)
return new String(value, startIndex, length); // default to ANSI
if (length < 0)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum);
if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- if ((value + startIndex) < value) {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
+ if ((value + startIndex) < value)
+ {
// overflow check
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
}
- byte [] b = new byte[length];
+ byte[] b = new byte[length];
- try {
+ try
+ {
Buffer.Memcpy(b, 0, (byte*)value, startIndex, length);
}
- catch(NullReferenceException) {
+ catch (NullReferenceException)
+ {
// If we got a NullReferencException. It means the pointer or
// the index is out of range
- throw new ArgumentOutOfRangeException(nameof(value),
- Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(value),
+ SR.ArgumentOutOfRange_PartialWCHAR);
}
return enc.GetString(b);
}
-
+
// Helper for encodings so they can talk to our buffer directly
// stringLength must be the exact size we'll expect
unsafe static internal String CreateStringFromEncoding(
@@ -256,17 +269,17 @@ namespace System {
// Get our string length
int stringLength = encoding.GetCharCount(bytes, byteLength, null);
Debug.Assert(stringLength >= 0, "stringLength >= 0");
-
+
// They gave us an empty string if they needed one
// 0 bytelength might be possible if there's something in an encoder
if (stringLength == 0)
return String.Empty;
-
+
String s = FastAllocateString(stringLength);
- fixed(char* pTempChars = &s.m_firstChar)
+ fixed (char* pTempChars = &s.m_firstChar)
{
int doubleCheck = encoding.GetChars(bytes, byteLength, pTempChars, stringLength, null);
- Debug.Assert(stringLength == doubleCheck,
+ Debug.Assert(stringLength == doubleCheck,
"Expected encoding.GetChars to return same length as encoding.GetCharCount");
}
@@ -282,17 +295,17 @@ namespace System {
result.m_firstChar = c;
return result;
}
-
- unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer,Encoding encoding)
+
+ unsafe internal int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer, Encoding encoding)
{
// encoding == Encoding.UTF8
- fixed (char* pwzChar = &this.m_firstChar)
+ fixed (char* pwzChar = &m_firstChar)
{
return encoding.GetBytes(pwzChar, m_stringLength, pbNativeBuffer, cbNativeBuffer);
- }
+ }
}
- unsafe internal int ConvertToAnsi(byte *pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
+ unsafe internal int ConvertToAnsi(byte* pbNativeBuffer, int cbNativeBuffer, bool fBestFit, bool fThrowOnUnmappableChar)
{
Debug.Assert(cbNativeBuffer >= (Length + 1) * Marshal.SystemMaxDBCSCharSize, "Insufficient buffer length passed to ConvertToAnsi");
@@ -304,7 +317,7 @@ namespace System {
uint flgs = (fBestFit ? 0 : WC_NO_BEST_FIT_CHARS);
uint DefaultCharUsed = 0;
- fixed (char* pwzChar = &this.m_firstChar)
+ fixed (char* pwzChar = &m_firstChar)
{
nb = Win32Native.WideCharToMultiByte(
CP_ACP,
@@ -319,7 +332,7 @@ namespace System {
if (0 != DefaultCharUsed)
{
- throw new ArgumentException(Environment.GetResourceString("Interop_Marshal_Unmappable_Char"));
+ throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char);
}
pbNativeBuffer[nb] = 0;
@@ -339,12 +352,12 @@ namespace System {
if (this.IsFastSort())
{
// If its FastSort && one of the 4 main forms, then its already normalized
- if( normalizationForm == NormalizationForm.FormC ||
+ if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
- normalizationForm == NormalizationForm.FormKD )
+ normalizationForm == NormalizationForm.FormKD)
return true;
- }
+ }
return Normalization.IsNormalized(this, normalizationForm);
}
@@ -359,10 +372,10 @@ namespace System {
if (this.IsAscii())
{
// If its FastSort && one of the 4 main forms, then its already normalized
- if( normalizationForm == NormalizationForm.FormC ||
+ if (normalizationForm == NormalizationForm.FormC ||
normalizationForm == NormalizationForm.FormKC ||
normalizationForm == NormalizationForm.FormD ||
- normalizationForm == NormalizationForm.FormKD )
+ normalizationForm == NormalizationForm.FormKD)
return this;
}
return Normalization.Normalize(this, normalizationForm);
@@ -376,27 +389,30 @@ namespace System {
// startIndex + length - 1.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern String(char [] value, int startIndex, int length);
-
+ public extern String(char[] value, int startIndex, int length);
+
// Creates a new string from the characters in a subarray. The new string will be
// created from the characters in value.
//
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern String(char [] value);
+ public extern String(char[] value);
- internal static unsafe void wstrcpy(char *dmem, char *smem, int charCount)
+ internal static unsafe void wstrcpy(char* dmem, char* smem, int charCount)
{
Buffer.Memcpy((byte*)dmem, (byte*)smem, charCount * 2); // 2 used everywhere instead of sizeof(char)
}
- private String CtorCharArray(char [] value)
+ private String CtorCharArray(char[] value)
{
- if (value != null && value.Length != 0) {
+ if (value != null && value.Length != 0)
+ {
String result = FastAllocateString(value.Length);
- unsafe {
- fixed (char* dest = &result.m_firstChar, source = value) {
+ unsafe
+ {
+ fixed (char* dest = &result.m_firstChar, source = value)
+ {
wstrcpy(dest, source, value.Length);
}
}
@@ -406,26 +422,29 @@ namespace System {
return String.Empty;
}
- private String CtorCharArrayStartLength(char [] value, int startIndex, int length)
+ private String CtorCharArrayStartLength(char[] value, int startIndex, int length)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (startIndex < 0)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
if (length < 0)
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
if (startIndex > value.Length - length)
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
- if (length > 0) {
+ if (length > 0)
+ {
String result = FastAllocateString(length);
- unsafe {
- fixed (char* dest = &result.m_firstChar, source = value) {
+ unsafe
+ {
+ fixed (char* dest = &result.m_firstChar, source = value)
+ {
wstrcpy(dest, source + startIndex, length);
}
}
@@ -437,29 +456,36 @@ namespace System {
private String CtorCharCount(char c, int count)
{
- if (count > 0) {
+ if (count > 0)
+ {
String result = FastAllocateString(count);
if (c != 0)
{
- unsafe {
- fixed (char* dest = &result.m_firstChar) {
- char *dmem = dest;
- while (((uint)dmem & 3) != 0 && count > 0) {
+ unsafe
+ {
+ fixed (char* dest = &result.m_firstChar)
+ {
+ char* dmem = dest;
+ while (((uint)dmem & 3) != 0 && count > 0)
+ {
*dmem++ = c;
count--;
}
uint cc = (uint)((c << 16) | c);
- if (count >= 4) {
+ if (count >= 4)
+ {
count -= 4;
- do{
- ((uint *)dmem)[0] = cc;
- ((uint *)dmem)[1] = cc;
+ do
+ {
+ ((uint*)dmem)[0] = cc;
+ ((uint*)dmem)[1] = cc;
dmem += 4;
count -= 4;
} while (count >= 0);
}
- if ((count & 2) != 0) {
- ((uint *)dmem)[0] = cc;
+ if ((count & 2) != 0)
+ {
+ ((uint*)dmem)[0] = cc;
dmem += 2;
}
if ((count & 1) != 0)
@@ -472,13 +498,13 @@ namespace System {
else if (count == 0)
return String.Empty;
else
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(count)));
+ throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(count)));
}
- private static unsafe int wcslen(char *ptr)
+ internal static unsafe int wcslen(char* ptr)
{
- char *end = ptr;
-
+ char* end = ptr;
+
// First make sure our pointer is aligned on a word boundary
int alignment = IntPtr.Size - 1;
@@ -527,7 +553,7 @@ namespace System {
// NOTE: We can access a ulong a time since the ptr is aligned,
// and therefore we're only accessing the same word/page. (See notes
// for the 32-bit version above.)
-
+
const ulong MagicMask = 0x7fff7fff7fff7fff;
while (true)
@@ -555,13 +581,13 @@ namespace System {
end += 4;
}
- EndAt3: end++;
- EndAt2: end++;
- EndAt1: end++;
- EndAt0:
+ EndAt3: end++;
+ EndAt2: end++;
+ EndAt1: end++;
+ EndAt0:
#endif // !BIT64
- FoundZero:
+ FoundZero:
Debug.Assert(*end == 0);
int count = (int)(end - ptr);
@@ -569,19 +595,20 @@ namespace System {
return count;
}
- private unsafe String CtorCharPtr(char *ptr)
+ private unsafe String CtorCharPtr(char* ptr)
{
if (ptr == null)
return String.Empty;
#if !FEATURE_PAL
if (ptr < (char*)64000)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeStringPtrNotAtom"));
+ throw new ArgumentException(SR.Arg_MustBeStringPtrNotAtom);
#endif // FEATURE_PAL
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
- try {
+ try
+ {
int count = wcslen(ptr);
if (count == 0)
return String.Empty;
@@ -591,27 +618,31 @@ namespace System {
wstrcpy(dest, ptr, count);
return result;
}
- catch (NullReferenceException) {
- throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ catch (NullReferenceException)
+ {
+ throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
}
}
- private unsafe String CtorCharPtrStartLength(char *ptr, int startIndex, int length)
+ private unsafe String CtorCharPtrStartLength(char* ptr, int startIndex, int length)
{
- if (length < 0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
+ if (length < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_NegativeLength);
}
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
+ if (startIndex < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_StartIndex);
}
Contract.EndContractBlock();
Debug.Assert(this == null, "this == null"); // this is the string constructor, we allocate it
- char *pFrom = ptr + startIndex;
- if (pFrom < ptr) {
+ char* pFrom = ptr + startIndex;
+ if (pFrom < ptr)
+ {
// This means that the pointer operation has had an overflow
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_PartialWCHAR);
}
if (length == 0)
@@ -619,43 +650,50 @@ namespace System {
String result = FastAllocateString(length);
- try {
+ try
+ {
fixed (char* dest = &result.m_firstChar)
wstrcpy(dest, pFrom, length);
return result;
}
- catch (NullReferenceException) {
- throw new ArgumentOutOfRangeException(nameof(ptr), Environment.GetResourceString("ArgumentOutOfRange_PartialWCHAR"));
+ catch (NullReferenceException)
+ {
+ throw new ArgumentOutOfRangeException(nameof(ptr), SR.ArgumentOutOfRange_PartialWCHAR);
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
-
+
// Returns this string.
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
Contract.EndContractBlock();
return this;
}
-
+
// Method required for the ICloneable interface.
// There's no point in cloning a string since they're immutable, so we simply return this.
- public Object Clone() {
+ public Object Clone()
+ {
Contract.Ensures(Contract.Result<Object>() != null);
Contract.EndContractBlock();
return this;
}
-
- unsafe public static String Copy (String str) {
- if (str==null) {
+
+ unsafe public static String Copy(String str)
+ {
+ if (str == null)
+ {
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() != null);
@@ -665,15 +703,18 @@ namespace System {
String result = FastAllocateString(length);
- fixed(char* dest = &result.m_firstChar)
- fixed(char* src = &str.m_firstChar) {
- wstrcpy(dest, src, length);
- }
- return result;
+ fixed (char* dest = &result.m_firstChar)
+ fixed (char* src = &str.m_firstChar)
+ {
+ wstrcpy(dest, src, length);
+ }
+ return result;
}
-
- public static String Intern(String str) {
- if (str==null) {
+
+ public static String Intern(String str)
+ {
+ if (str == null)
+ {
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>().Length == str.Length);
@@ -684,8 +725,10 @@ namespace System {
}
[Pure]
- public static String IsInterned(String str) {
- if (str==null) {
+ public static String IsInterned(String str)
+ {
+ if (str == null)
+ {
throw new ArgumentNullException(nameof(str));
}
Contract.Ensures(Contract.Result<String>() == null || Contract.Result<String>().Length == str.Length);
@@ -698,83 +741,84 @@ namespace System {
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.String;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(this, provider);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(this, provider);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(this, provider);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(this, provider);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(this, provider);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(this, provider);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(this, provider);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(this, provider);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(this, provider);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(this, provider);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(this, provider);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(this, provider);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(this, provider);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
return Convert.ToDateTime(this, provider);
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
@@ -795,41 +839,45 @@ namespace System {
internal extern bool TryGetTrailByte(out byte data);
#endif
- public CharEnumerator GetEnumerator() {
+ public CharEnumerator GetEnumerator()
+ {
Contract.Ensures(Contract.Result<CharEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
- IEnumerator<char> IEnumerable<char>.GetEnumerator() {
+ IEnumerator<char> IEnumerable<char>.GetEnumerator()
+ {
Contract.Ensures(Contract.Result<IEnumerator<char>>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
- /// <internalonly/>
- IEnumerator IEnumerable.GetEnumerator() {
+ IEnumerator IEnumerable.GetEnumerator()
+ {
Contract.Ensures(Contract.Result<IEnumerator>() != null);
Contract.EndContractBlock();
BCLDebug.Perf(false, "Avoid using String's CharEnumerator until C# special cases foreach on String - use the indexed property on String instead.");
return new CharEnumerator(this);
}
- // Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
- internal unsafe static void InternalCopy(String src, IntPtr dest,int len)
+ // Copies the source String (byte buffer) to the destination IntPtr memory allocated with len bytes.
+ internal unsafe static void InternalCopy(String src, IntPtr dest, int len)
{
if (len == 0)
return;
- fixed(char* charPtr = &src.m_firstChar) {
- byte* srcPtr = (byte*) charPtr;
- byte* dstPtr = (byte*) dest;
+ fixed (char* charPtr = &src.m_firstChar)
+ {
+ byte* srcPtr = (byte*)charPtr;
+ byte* dstPtr = (byte*)dest;
Buffer.Memcpy(dstPtr, srcPtr, len);
}
}
- internal ref char GetFirstCharRef() {
+ internal ref char GetFirstCharRef()
+ {
return ref m_firstChar;
}
}
diff --git a/src/mscorlib/src/System/StringComparer.cs b/src/mscorlib/src/System/StringComparer.cs
deleted file mode 100644
index cf65c48c2b..0000000000
--- a/src/mscorlib/src/System/StringComparer.cs
+++ /dev/null
@@ -1,300 +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.
-
-
-namespace System {
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Diagnostics.Contracts;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
-
-
- [Serializable]
- public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string>{
- private static readonly StringComparer _invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false);
- private static readonly StringComparer _invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true);
- private static readonly StringComparer _ordinal = new OrdinalComparer(false);
- private static readonly StringComparer _ordinalIgnoreCase = new OrdinalComparer(true);
-
- public static StringComparer InvariantCulture {
- get {
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- return _invariantCulture;
- }
- }
-
- public static StringComparer InvariantCultureIgnoreCase {
- get {
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- return _invariantCultureIgnoreCase;
- }
- }
-
- public static StringComparer CurrentCulture {
- get {
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- return new CultureAwareComparer(CultureInfo.CurrentCulture, false);
- }
- }
-
- public static StringComparer CurrentCultureIgnoreCase {
- get {
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- return new CultureAwareComparer(CultureInfo.CurrentCulture, true);
- }
- }
-
- public static StringComparer Ordinal {
- get {
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- return _ordinal;
- }
- }
-
- public static StringComparer OrdinalIgnoreCase {
- get {
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- return _ordinalIgnoreCase;
- }
- }
-
- // Convert a StringComparison to a StringComparer
- public static StringComparer FromComparison(StringComparison comparisonType)
- {
- switch (comparisonType)
- {
- case StringComparison.CurrentCulture:
- return CurrentCulture;
- case StringComparison.CurrentCultureIgnoreCase:
- return CurrentCultureIgnoreCase;
- case StringComparison.InvariantCulture:
- return InvariantCulture;
- case StringComparison.InvariantCultureIgnoreCase:
- return InvariantCultureIgnoreCase;
- case StringComparison.Ordinal:
- return Ordinal;
- case StringComparison.OrdinalIgnoreCase:
- return OrdinalIgnoreCase;
- default:
- throw new ArgumentException(Environment.GetResourceString("NotSupported_StringComparison"), nameof(comparisonType));
- }
- }
-
- public static StringComparer Create(CultureInfo culture, bool ignoreCase) {
- if( culture == null) {
- throw new ArgumentNullException(nameof(culture));
- }
- Contract.Ensures(Contract.Result<StringComparer>() != null);
- Contract.EndContractBlock();
-
- return new CultureAwareComparer(culture, ignoreCase);
- }
-
- public int Compare(object x, object y) {
- if (x == y) return 0;
- if (x == null) return -1;
- if (y == null) return 1;
-
- String sa = x as String;
- if (sa != null) {
- String sb = y as String;
- if( sb != null) {
- return Compare(sa, sb);
- }
- }
-
- IComparable ia = x as IComparable;
- if (ia != null) {
- return ia.CompareTo(y);
- }
-
- throw new ArgumentException(Environment.GetResourceString("Argument_ImplementIComparable"));
- }
-
-
- public new bool Equals(Object x, Object y) {
- if (x == y) return true;
- if (x == null || y == null) return false;
-
- String sa = x as String;
- if (sa != null) {
- String sb = y as String;
- if( sb != null) {
- return Equals(sa, sb);
- }
- }
- return x.Equals(y);
- }
-
- public int GetHashCode(object obj) {
- if( obj == null) {
- throw new ArgumentNullException(nameof(obj));
- }
- Contract.EndContractBlock();
-
- string s = obj as string;
- if( s != null) {
- return GetHashCode(s);
- }
- return obj.GetHashCode();
- }
-
- public abstract int Compare(String x, String y);
- public abstract bool Equals(String x, String y);
- public abstract int GetHashCode(string obj);
- }
-
- [Serializable]
- internal sealed class CultureAwareComparer : StringComparer
-#if FEATURE_RANDOMIZED_STRING_HASHING
- , IWellKnownStringEqualityComparer
-#endif
- {
- private CompareInfo _compareInfo;
- private bool _ignoreCase;
-
- internal CultureAwareComparer(CultureInfo culture, bool ignoreCase) {
- _compareInfo = culture.CompareInfo;
- _ignoreCase = ignoreCase;
- }
-
- public override int Compare(string x, string y) {
- if (Object.ReferenceEquals(x, y)) return 0;
- if (x == null) return -1;
- if (y == null) return 1;
- return _compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None);
- }
-
- public override bool Equals(string x, string y) {
- if (Object.ReferenceEquals(x ,y)) return true;
- if (x == null || y == null) return false;
-
- return (_compareInfo.Compare(x, y, _ignoreCase? CompareOptions.IgnoreCase : CompareOptions.None) == 0);
- }
-
- public override int GetHashCode(string obj) {
- if( obj == null) {
- throw new ArgumentNullException(nameof(obj));
- }
- Contract.EndContractBlock();
-
- CompareOptions options = CompareOptions.None;
-
- if( _ignoreCase) {
- options |= CompareOptions.IgnoreCase;
- }
-
- return _compareInfo.GetHashCodeOfString(obj, options);
- }
-
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- CultureAwareComparer comparer = obj as CultureAwareComparer;
- if( comparer == null) {
- return false;
- }
- return (this._ignoreCase == comparer._ignoreCase) && (this._compareInfo.Equals(comparer._compareInfo));
- }
-
- public override int GetHashCode() {
- int hashCode = _compareInfo.GetHashCode() ;
- return _ignoreCase ? (~hashCode) : hashCode;
- }
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
- return this;
- }
-#endif
-
- }
-
- // Provide x more optimal implementation of ordinal comparison.
- [Serializable]
- internal sealed class OrdinalComparer : StringComparer
-#if FEATURE_RANDOMIZED_STRING_HASHING
- , IWellKnownStringEqualityComparer
-#endif
- {
- private bool _ignoreCase;
-
- internal OrdinalComparer(bool ignoreCase) {
- _ignoreCase = ignoreCase;
- }
-
- public override int Compare(string x, string y) {
- if (Object.ReferenceEquals(x, y)) return 0;
- if (x == null) return -1;
- if (y == null) return 1;
-
- if( _ignoreCase) {
- return String.Compare(x, y, StringComparison.OrdinalIgnoreCase);
- }
-
- return String.CompareOrdinal(x, y);
- }
-
- public override bool Equals(string x, string y) {
- if (Object.ReferenceEquals(x ,y)) return true;
- if (x == null || y == null) return false;
-
- if( _ignoreCase) {
- if( x.Length != y.Length) {
- return false;
- }
- return (String.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0);
- }
- return x.Equals(y);
- }
-
- public override int GetHashCode(string obj) {
- if( obj == null) {
- throw new ArgumentNullException(nameof(obj));
- }
- Contract.EndContractBlock();
-
- if( _ignoreCase) {
- return TextInfo.GetHashCodeOrdinalIgnoreCase(obj);
- }
-
- return obj.GetHashCode();
- }
-
- // Equals method for the comparer itself.
- public override bool Equals(Object obj){
- OrdinalComparer comparer = obj as OrdinalComparer;
- if( comparer == null) {
- return false;
- }
- return (this._ignoreCase == comparer._ignoreCase);
- }
-
- public override int GetHashCode() {
- string name = "OrdinalComparer";
- int hashCode = name.GetHashCode();
- return _ignoreCase ? (~hashCode) : hashCode;
- }
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-
- IEqualityComparer IWellKnownStringEqualityComparer.GetEqualityComparerForSerialization() {
- return this;
- }
-#endif
-
- }
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
-
- // This interface is implemented by string comparers in the framework that can opt into
- // randomized hashing behaviors.
- internal interface IWellKnownStringEqualityComparer {
- // Get an IEqaulityComparer that can be serailzied (e.g., it exists in older versions).
- IEqualityComparer GetEqualityComparerForSerialization();
- }
-#endif
-}
diff --git a/src/mscorlib/src/System/StringComparison.cs b/src/mscorlib/src/System/StringComparison.cs
deleted file mode 100644
index c654f7200f..0000000000
--- a/src/mscorlib/src/System/StringComparison.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.
-
-/*============================================================
-**
-** Enum: StringComparison
-**
-**
-** Purpose: A mechanism to expose a simplified infrastructure for
-** Comparing strings. This enum lets you choose of the custom
-** implementations provided by the runtime for the user.
-**
-**
-===========================================================*/
-
-namespace System
-{
- [Serializable]
- public enum StringComparison
- {
- CurrentCulture = 0,
- CurrentCultureIgnoreCase = 1,
- InvariantCulture = 2,
- InvariantCultureIgnoreCase = 3,
- Ordinal = 4,
- OrdinalIgnoreCase = 5,
- }
-}
diff --git a/src/mscorlib/src/System/StringFreezingAttribute.cs b/src/mscorlib/src/System/StringFreezingAttribute.cs
deleted file mode 100644
index d488a88445..0000000000
--- a/src/mscorlib/src/System/StringFreezingAttribute.cs
+++ /dev/null
@@ -1,25 +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: Custom attribute to indicate that strings should be frozen
-**
-**
-===========================================================*/
-
-namespace System.Runtime.CompilerServices
-{
-
-[Serializable]
- [AttributeUsage(AttributeTargets.Assembly, Inherited = false)]
- public sealed class StringFreezingAttribute : Attribute
- {
- public StringFreezingAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/StringSplitOptions.cs b/src/mscorlib/src/System/StringSplitOptions.cs
deleted file mode 100644
index 43b626a010..0000000000
--- a/src/mscorlib/src/System/StringSplitOptions.cs
+++ /dev/null
@@ -1,13 +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.
-
-namespace System
-{
- [Flags]
- public enum StringSplitOptions
- {
- None = 0,
- RemoveEmptyEntries = 1
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs
index 2d5926b923..f584ece6fc 100644
--- a/src/mscorlib/src/System/StubHelpers.cs
+++ b/src/mscorlib/src/System/StubHelpers.cs
@@ -3,8 +3,8 @@
// See the LICENSE file in the project root for more information.
-namespace System.StubHelpers {
-
+namespace System.StubHelpers
+{
using System.Text;
using Microsoft.Win32;
using System.Security;
@@ -27,7 +27,7 @@ namespace System.StubHelpers {
{
byte[] buffer = new byte[(str.Length + 1) * Marshal.SystemMaxDBCSCharSize];
BCLDebug.Assert(buffer.Length != 0);
- fixed (byte *bufferPtr = &buffer[0])
+ fixed (byte* bufferPtr = &buffer[0])
{
cbLength = str.ConvertToAnsi(bufferPtr, buffer.Length, fBestFit, fThrowOnUnmappableChar);
}
@@ -65,7 +65,7 @@ namespace System.StubHelpers {
StubHelpers.CheckStringLength(strManaged.Length);
int nb;
- byte *pbNativeBuffer = (byte *)pNativeBuffer;
+ byte* pbNativeBuffer = (byte*)pNativeBuffer;
if (pbNativeBuffer != null || Marshal.SystemMaxDBCSCharSize == 1)
{
@@ -100,11 +100,11 @@ namespace System.StubHelpers {
Buffer.Memcpy(pbNativeBuffer, 0, bytes, 0, nb);
}
- pbNativeBuffer[nb] = 0x00;
+ pbNativeBuffer[nb] = 0x00;
pbNativeBuffer[nb + 1] = 0x00;
return (IntPtr)pbNativeBuffer;
- }
+ }
static internal unsafe string ConvertToManaged(IntPtr cstr)
{
@@ -122,7 +122,7 @@ namespace System.StubHelpers {
internal static class UTF8Marshaler
{
- const int MAX_UTF8_CHAR_SIZE = 3;
+ private const int MAX_UTF8_CHAR_SIZE = 3;
static internal unsafe IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer)
{
if (null == strManaged)
@@ -249,29 +249,29 @@ namespace System.StubHelpers {
lengthInBytes++;
}
- byte *ptrToFirstChar;
+ byte* ptrToFirstChar;
if (pNativeBuffer != IntPtr.Zero)
{
// If caller provided a buffer, construct the BSTR manually. The size
// of the buffer must be at least (lengthInBytes + 6) bytes.
#if _DEBUG
- uint length = *((uint *)pNativeBuffer.ToPointer());
+ uint length = *((uint*)pNativeBuffer.ToPointer());
BCLDebug.Assert(length >= lengthInBytes + 6, "BSTR localloc'ed buffer is too small");
#endif // _DEBUG
// set length
- *((uint *)pNativeBuffer.ToPointer()) = lengthInBytes;
+ *((uint*)pNativeBuffer.ToPointer()) = lengthInBytes;
- ptrToFirstChar = (byte *)pNativeBuffer.ToPointer() + 4;
+ ptrToFirstChar = (byte*)pNativeBuffer.ToPointer() + 4;
}
else
{
// If not provided, allocate the buffer using SysAllocStringByteLen so
// that odd-sized strings will be handled as well.
- ptrToFirstChar = (byte *)Win32Native.SysAllocStringByteLen(null, lengthInBytes).ToPointer();
+ ptrToFirstChar = (byte*)Win32Native.SysAllocStringByteLen(null, lengthInBytes).ToPointer();
- if (ptrToFirstChar == null)
+ if (ptrToFirstChar == null)
{
throw new OutOfMemoryException();
}
@@ -282,7 +282,7 @@ namespace System.StubHelpers {
{
Buffer.Memcpy(
ptrToFirstChar,
- (byte *)ch,
+ (byte*)ch,
(strManaged.Length + 1) * 2);
}
@@ -334,7 +334,7 @@ namespace System.StubHelpers {
if ((length & 1) == 1)
{
// odd-sized strings need to have the trailing byte saved in their sync block
- ret.SetTrailByte(((byte *)bstr.ToPointer())[length - 1]);
+ ret.SetTrailByte(((byte*)bstr.ToPointer())[length - 1]);
}
return ret;
@@ -363,7 +363,7 @@ namespace System.StubHelpers {
}
byte* pNative;
-
+
cch = strManaged.Length;
StubHelpers.CheckStringLength(cch);
@@ -373,7 +373,7 @@ namespace System.StubHelpers {
pNative = (byte*)Marshal.AllocCoTaskMem(nbytes);
int* pLength = (int*)pNative;
-
+
pNative = pNative + sizeof(uint);
if (0 == cch)
@@ -405,7 +405,7 @@ namespace System.StubHelpers {
return new String((sbyte*)pNative, 0, cch);
}
-
+
static internal unsafe void ClearNative(IntPtr pNative)
{
if (IntPtr.Zero != pNative)
@@ -431,8 +431,8 @@ namespace System.StubHelpers {
StubHelpers.CheckStringLength(length);
- byte[] bytes = null;
- int nb = 0;
+ byte[] bytes = null;
+ int nb = 0;
if (length > 0)
{
@@ -499,23 +499,23 @@ namespace System.StubHelpers {
public Int64 UniversalTime;
};
- internal static class DateTimeOffsetMarshaler {
-
+ internal static class DateTimeOffsetMarshaler
+ {
// Numer of ticks counted between 0001-01-01, 00:00:00 and 1601-01-01, 00:00:00.
// You can get this through: (new DateTimeOffset(1601, 1, 1, 0, 0, 1, TimeSpan.Zero)).Ticks;
private const Int64 ManagedUtcTicksAtNativeZero = 504911232000000000;
- internal static void ConvertToNative(ref DateTimeOffset managedDTO, out DateTimeNative dateTime) {
-
+ internal static void ConvertToNative(ref DateTimeOffset managedDTO, out DateTimeNative dateTime)
+ {
Int64 managedUtcTicks = managedDTO.UtcTicks;
dateTime.UniversalTime = managedUtcTicks - ManagedUtcTicksAtNativeZero;
}
- internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks) {
-
+ internal static void ConvertToManaged(out DateTimeOffset managedLocalDTO, ref DateTimeNative nativeTicks)
+ {
Int64 managedUtcTicks = ManagedUtcTicksAtNativeZero + nativeTicks.UniversalTime;
DateTimeOffset managedUtcDTO = new DateTimeOffset(managedUtcTicks, TimeSpan.Zero);
-
+
// Some Utc times cannot be represented in local time in certain timezones. E.g. 0001-01-01 12:00:00 AM cannot
// be represented in any timezones with a negative offset from Utc. We throw an ArgumentException in that case.
managedLocalDTO = managedUtcDTO.ToLocalTime(true);
@@ -532,7 +532,7 @@ namespace System.StubHelpers {
internal static unsafe IntPtr ConvertToNative(string managed)
{
if (!Environment.IsWinRTSupported)
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (managed == null)
throw new ArgumentNullException(); // We don't have enough information to get the argument name
@@ -549,16 +549,16 @@ namespace System.StubHelpers {
// the returned HSTRING object. If the string is not pinned, or becomes unpinned before the HSTRING's
// lifetime ends, the HSTRING instance will be corrupted.
internal static unsafe IntPtr ConvertToNativeReference(string managed,
- [Out] HSTRING_HEADER *hstringHeader)
+ [Out] HSTRING_HEADER* hstringHeader)
{
if (!Environment.IsWinRTSupported)
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
if (managed == null)
throw new ArgumentNullException(); // We don't have enough information to get the argument name
// The string must also be pinned by the caller to ConvertToNativeReference, which also owns
// the HSTRING_HEADER.
- fixed (char *pManaged = managed)
+ fixed (char* pManaged = managed)
{
IntPtr hstring;
int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateStringReference(pManaged, managed.Length, hstringHeader, &hstring);
@@ -571,7 +571,7 @@ namespace System.StubHelpers {
{
if (!Environment.IsWinRTSupported)
{
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
return WindowsRuntimeMarshal.HStringToString(hstring);
@@ -651,15 +651,14 @@ namespace System.StubHelpers {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static unsafe internal extern IntPtr CreateNativeUriInstanceHelper(char* rawUri, int strLen);
-
+
static unsafe internal IntPtr CreateNativeUriInstance(string rawUri)
{
- fixed(char* pManaged = rawUri)
+ fixed (char* pManaged = rawUri)
{
return CreateNativeUriInstanceHelper(pManaged, rawUri.Length);
}
}
-
} // class InterfaceMarshaler
[FriendAccessAllowed]
@@ -703,7 +702,7 @@ namespace System.StubHelpers {
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
@@ -719,7 +718,7 @@ namespace System.StubHelpers {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ClearNative(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ClearNativeContents(IntPtr pMarshalState, IntPtr pNativeHome, int cElements);
} // class MngdNativeArrayMarshaler
@@ -729,7 +728,7 @@ namespace System.StubHelpers {
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int iRank, int dwFlags);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
@@ -750,7 +749,7 @@ namespace System.StubHelpers {
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, IntPtr cbElementSize, ushort vt);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
@@ -761,7 +760,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- DateTimeNative *nativeBuffer = *(DateTimeNative **)pNativeHome;
+ DateTimeNative* nativeBuffer = *(DateTimeNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
DateTimeOffsetMarshaler.ConvertToNative(ref managedArray[i], out nativeBuffer[i]);
@@ -773,7 +772,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- TypeNameNative *nativeBuffer = *(TypeNameNative **)pNativeHome;
+ TypeNameNative* nativeBuffer = *(TypeNameNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
SystemTypeMarshaler.ConvertToNative(managedArray[i], &nativeBuffer[i]);
@@ -785,7 +784,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- Int32 *nativeBuffer = *(Int32 **)pNativeHome;
+ Int32* nativeBuffer = *(Int32**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
nativeBuffer[i] = HResultExceptionMarshaler.ConvertToNative(managedArray[i]);
@@ -798,7 +797,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- IntPtr *nativeBuffer = *(IntPtr **)pNativeHome;
+ IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
nativeBuffer[i] = NullableMarshaler.ConvertToNative<T>(ref managedArray[i]);
@@ -810,7 +809,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- IntPtr *nativeBuffer = *(IntPtr **)pNativeHome;
+ IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
nativeBuffer[i] = KeyValuePairMarshaler.ConvertToNative<K, V>(ref managedArray[i]);
@@ -828,7 +827,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- DateTimeNative *nativeBuffer = *(DateTimeNative **)pNativeHome;
+ DateTimeNative* nativeBuffer = *(DateTimeNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
DateTimeOffsetMarshaler.ConvertToManaged(out managedArray[i], ref nativeBuffer[i]);
@@ -840,7 +839,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- TypeNameNative *nativeBuffer = *(TypeNameNative **)pNativeHome;
+ TypeNameNative* nativeBuffer = *(TypeNameNative**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
SystemTypeMarshaler.ConvertToManaged(&nativeBuffer[i], ref managedArray[i]);
@@ -852,7 +851,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- Int32 *nativeBuffer = *(Int32 **)pNativeHome;
+ Int32* nativeBuffer = *(Int32**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
managedArray[i] = HResultExceptionMarshaler.ConvertToManaged(nativeBuffer[i]);
@@ -865,7 +864,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- IntPtr *nativeBuffer = *(IntPtr **)pNativeHome;
+ IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
managedArray[i] = NullableMarshaler.ConvertToManaged<T>(nativeBuffer[i]);
@@ -877,7 +876,7 @@ namespace System.StubHelpers {
{
if (managedArray != null)
{
- IntPtr *nativeBuffer = *(IntPtr **)pNativeHome;
+ IntPtr* nativeBuffer = *(IntPtr**)pNativeHome;
for (int i = 0; i < managedArray.Length; i++)
{
managedArray[i] = KeyValuePairMarshaler.ConvertToManaged<K, V>(nativeBuffer[i]);
@@ -892,7 +891,7 @@ namespace System.StubHelpers {
{
Debug.Assert(Environment.IsWinRTSupported);
- TypeNameNative *pNativeTypeArray = *(TypeNameNative **)pNativeHome;
+ TypeNameNative* pNativeTypeArray = *(TypeNameNative**)pNativeHome;
if (pNativeTypeArray != null)
{
for (int i = 0; i < cElements; ++i)
@@ -910,7 +909,7 @@ namespace System.StubHelpers {
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pCMHelper);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome);
@@ -927,7 +926,7 @@ namespace System.StubHelpers {
internal struct AsAnyMarshaler
{
private const ushort VTHACK_ANSICHAR = 253;
- private const ushort VTHACK_WINBOOL = 254;
+ private const ushort VTHACK_WINBOOL = 254;
private enum BackPropAction
{
@@ -950,9 +949,9 @@ namespace System.StubHelpers {
// Cleanup list to be destroyed when clearing the native view (for layouts with SafeHandles).
private CleanupWorkList cleanupWorkList;
- private static bool IsIn(int dwFlags) { return ((dwFlags & 0x10000000) != 0); }
- private static bool IsOut(int dwFlags) { return ((dwFlags & 0x20000000) != 0); }
- private static bool IsAnsi(int dwFlags) { return ((dwFlags & 0x00FF0000) != 0); }
+ private static bool IsIn(int dwFlags) { return ((dwFlags & 0x10000000) != 0); }
+ private static bool IsOut(int dwFlags) { return ((dwFlags & 0x20000000) != 0); }
+ private static bool IsAnsi(int dwFlags) { return ((dwFlags & 0x00FF0000) != 0); }
private static bool IsThrowOn(int dwFlags) { return ((dwFlags & 0x0000FF00) != 0); }
private static bool IsBestFit(int dwFlags) { return ((dwFlags & 0x000000FF) != 0); }
@@ -962,9 +961,9 @@ namespace System.StubHelpers {
BCLDebug.Assert(pvArrayMarshaler != IntPtr.Zero, "pvArrayMarshaler must not be null");
this.pvArrayMarshaler = pvArrayMarshaler;
- this.backPropAction = BackPropAction.None;
- this.layoutType = null;
- this.cleanupWorkList = null;
+ backPropAction = BackPropAction.None;
+ layoutType = null;
+ cleanupWorkList = null;
}
#region ConvertToNative helpers
@@ -976,35 +975,35 @@ namespace System.StubHelpers {
switch (Type.GetTypeCode(elementType))
{
- case TypeCode.SByte: vt = VarEnum.VT_I1; break;
- case TypeCode.Byte: vt = VarEnum.VT_UI1; break;
- case TypeCode.Int16: vt = VarEnum.VT_I2; break;
- case TypeCode.UInt16: vt = VarEnum.VT_UI2; break;
- case TypeCode.Int32: vt = VarEnum.VT_I4; break;
- case TypeCode.UInt32: vt = VarEnum.VT_UI4; break;
- case TypeCode.Int64: vt = VarEnum.VT_I8; break;
- case TypeCode.UInt64: vt = VarEnum.VT_UI8; break;
- case TypeCode.Single: vt = VarEnum.VT_R4; break;
- case TypeCode.Double: vt = VarEnum.VT_R8; break;
- case TypeCode.Char: vt = (IsAnsi(dwFlags) ? (VarEnum)VTHACK_ANSICHAR : VarEnum.VT_UI2); break;
+ case TypeCode.SByte: vt = VarEnum.VT_I1; break;
+ case TypeCode.Byte: vt = VarEnum.VT_UI1; break;
+ case TypeCode.Int16: vt = VarEnum.VT_I2; break;
+ case TypeCode.UInt16: vt = VarEnum.VT_UI2; break;
+ case TypeCode.Int32: vt = VarEnum.VT_I4; break;
+ case TypeCode.UInt32: vt = VarEnum.VT_UI4; break;
+ case TypeCode.Int64: vt = VarEnum.VT_I8; break;
+ case TypeCode.UInt64: vt = VarEnum.VT_UI8; break;
+ case TypeCode.Single: vt = VarEnum.VT_R4; break;
+ case TypeCode.Double: vt = VarEnum.VT_R8; break;
+ case TypeCode.Char: vt = (IsAnsi(dwFlags) ? (VarEnum)VTHACK_ANSICHAR : VarEnum.VT_UI2); break;
case TypeCode.Boolean: vt = (VarEnum)VTHACK_WINBOOL; break;
case TypeCode.Object:
- {
- if (elementType == typeof(IntPtr))
- {
- vt = (IntPtr.Size == 4 ? VarEnum.VT_I4 : VarEnum.VT_I8);
- }
- else if (elementType == typeof(UIntPtr))
{
- vt = (IntPtr.Size == 4 ? VarEnum.VT_UI4 : VarEnum.VT_UI8);
+ if (elementType == typeof(IntPtr))
+ {
+ vt = (IntPtr.Size == 4 ? VarEnum.VT_I4 : VarEnum.VT_I8);
+ }
+ else if (elementType == typeof(UIntPtr))
+ {
+ vt = (IntPtr.Size == 4 ? VarEnum.VT_UI4 : VarEnum.VT_UI8);
+ }
+ else goto default;
+ break;
}
- else goto default;
- break;
- }
default:
- throw new ArgumentException(Environment.GetResourceString("Arg_NDirectBadObject"));
+ throw new ArgumentException(SR.Arg_NDirectBadObject);
}
// marshal the object as C-style array (UnmanagedType.LPArray)
@@ -1152,7 +1151,7 @@ namespace System.StubHelpers {
// marshal the object as class with layout (UnmanagedType.LPStruct)
if (IsIn(dwFlags))
{
- StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte *)pNativeHome.ToPointer(), ref cleanupWorkList);
+ StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte*)pNativeHome.ToPointer(), ref cleanupWorkList);
}
if (IsOut(dwFlags))
{
@@ -1171,7 +1170,7 @@ namespace System.StubHelpers {
return IntPtr.Zero;
if (pManagedHome is ArrayWithOffset)
- throw new ArgumentException(Environment.GetResourceString("Arg_MarshalAsAnyRestriction"));
+ throw new ArgumentException(SR.Arg_MarshalAsAnyRestriction);
IntPtr pNativeHome;
@@ -1203,7 +1202,7 @@ namespace System.StubHelpers {
else
{
// this type is not supported for AsAny marshaling
- throw new ArgumentException(Environment.GetResourceString("Arg_NDirectBadObject"));
+ throw new ArgumentException(SR.Arg_NDirectBadObject);
}
}
@@ -1215,35 +1214,35 @@ namespace System.StubHelpers {
switch (backPropAction)
{
case BackPropAction.Array:
- {
- MngdNativeArrayMarshaler.ConvertContentsToManaged(
- pvArrayMarshaler,
- ref pManagedHome,
- new IntPtr(&pNativeHome));
- break;
- }
+ {
+ MngdNativeArrayMarshaler.ConvertContentsToManaged(
+ pvArrayMarshaler,
+ ref pManagedHome,
+ new IntPtr(&pNativeHome));
+ break;
+ }
case BackPropAction.Layout:
- {
- StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte *)pNativeHome.ToPointer());
- break;
- }
+ {
+ StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte*)pNativeHome.ToPointer());
+ break;
+ }
case BackPropAction.StringBuilderAnsi:
- {
- sbyte* ptr = (sbyte*)pNativeHome.ToPointer();
- ((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal(ptr, Win32Native.lstrlenA(pNativeHome));
- break;
- }
+ {
+ sbyte* ptr = (sbyte*)pNativeHome.ToPointer();
+ ((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal(ptr, Win32Native.lstrlenA(pNativeHome));
+ break;
+ }
case BackPropAction.StringBuilderUnicode:
- {
- char* ptr = (char*)pNativeHome.ToPointer();
- ((StringBuilder)pManagedHome).ReplaceBufferInternal(ptr, Win32Native.lstrlenW(pNativeHome));
- break;
- }
+ {
+ char* ptr = (char*)pNativeHome.ToPointer();
+ ((StringBuilder)pManagedHome).ReplaceBufferInternal(ptr, Win32Native.lstrlenW(pNativeHome));
+ break;
+ }
- // nothing to do for BackPropAction.None
+ // nothing to do for BackPropAction.None
}
}
@@ -1264,7 +1263,7 @@ namespace System.StubHelpers {
#if FEATURE_COMINTEROP
internal static class NullableMarshaler
- {
+ {
static internal IntPtr ConvertToNative<T>(ref Nullable<T> pManaged) where T : struct
{
if (pManaged.HasValue)
@@ -1277,7 +1276,7 @@ namespace System.StubHelpers {
return IntPtr.Zero;
}
}
-
+
static internal void ConvertToManagedRetVoid<T>(IntPtr pNative, ref Nullable<T> retObj) where T : struct
{
retObj = ConvertToManaged<T>(pNative);
@@ -1302,9 +1301,8 @@ namespace System.StubHelpers {
[StructLayout(LayoutKind.Sequential)]
internal struct TypeNameNative
{
-
- internal IntPtr typeName; // HSTRING
- internal TypeKind typeKind; // TypeKind enum
+ internal IntPtr typeName; // HSTRING
+ internal TypeKind typeKind; // TypeKind enum
}
// Corresponds to Windows.UI.Xaml.TypeSource
@@ -1319,26 +1317,26 @@ namespace System.StubHelpers {
{
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern string ConvertToWinRTTypeName(System.Type managedType, out bool isPrimitive);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern System.Type GetTypeFromWinRTTypeName(string typeName, out bool isPrimitive);
}
-
+
internal static class SystemTypeMarshaler
- {
- internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative *pNativeType)
+ {
+ internal static unsafe void ConvertToNative(System.Type managedType, TypeNameNative* pNativeType)
{
if (!Environment.IsWinRTSupported)
{
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
-
+
string typeName;
if (managedType != null)
{
if (managedType.GetType() != typeof(System.RuntimeType))
{ // The type should be exactly System.RuntimeType (and not its child System.ReflectionOnlyType, or other System.Type children)
- throw new ArgumentException(Environment.GetResourceString("Argument_WinRTSystemRuntimeType", managedType.GetType().ToString()));
+ throw new ArgumentException(SR.Format(SR.Argument_WinRTSystemRuntimeType, managedType.GetType().ToString()));
}
bool isPrimitive;
@@ -1368,14 +1366,14 @@ namespace System.StubHelpers {
int hrCreate = System.Runtime.InteropServices.WindowsRuntime.UnsafeNativeMethods.WindowsCreateString(typeName, typeName.Length, &pNativeType->typeName);
Marshal.ThrowExceptionForHR(hrCreate, new IntPtr(-1));
}
-
- internal static unsafe void ConvertToManaged(TypeNameNative *pNativeType, ref System.Type managedType)
+
+ internal static unsafe void ConvertToManaged(TypeNameNative* pNativeType, ref System.Type managedType)
{
if (!Environment.IsWinRTSupported)
{
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
-
+
string typeName = WindowsRuntimeMarshal.HStringToString(pNativeType->typeName);
if (String.IsNullOrEmpty(typeName))
{
@@ -1394,11 +1392,11 @@ namespace System.StubHelpers {
// TypeSource must match
if (isPrimitive != (pNativeType->typeKind == TypeKind.Primitive))
- throw new ArgumentException(Environment.GetResourceString("Argument_Unexpected_TypeSource"));
+ throw new ArgumentException(SR.Argument_Unexpected_TypeSource);
}
}
-
- internal static unsafe void ClearNative(TypeNameNative *pNativeType)
+
+ internal static unsafe void ClearNative(TypeNameNative* pNativeType)
{
Debug.Assert(Environment.IsWinRTSupported);
@@ -1416,7 +1414,7 @@ namespace System.StubHelpers {
{
if (!Environment.IsWinRTSupported)
{
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
if (ex == null)
@@ -1431,7 +1429,7 @@ namespace System.StubHelpers {
if (!Environment.IsWinRTSupported)
{
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_WinRT"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_WinRT);
}
Exception e = null;
@@ -1448,13 +1446,13 @@ namespace System.StubHelpers {
} // class HResultExceptionMarshaler
internal static class KeyValuePairMarshaler
- {
+ {
internal static IntPtr ConvertToNative<K, V>([In] ref KeyValuePair<K, V> pair)
{
IKeyValuePair<K, V> impl = new CLRIKeyValuePairImpl<K, V>(ref pair);
return Marshal.GetComInterfaceForObject(impl, typeof(IKeyValuePair<K, V>));
}
-
+
internal static KeyValuePair<K, V> ConvertToManaged<K, V>(IntPtr pInsp)
{
object obj = InterfaceMarshaler.ConvertToManagedWithoutUnboxing(pInsp);
@@ -1475,10 +1473,10 @@ namespace System.StubHelpers {
[StructLayout(LayoutKind.Sequential)]
internal struct NativeVariant
{
- ushort vt;
- ushort wReserved1;
- ushort wReserved2;
- ushort wReserved3;
+ private ushort vt;
+ private ushort wReserved1;
+ private ushort wReserved2;
+ private ushort wReserved3;
// The union portion of the structure contains at least one 64-bit type that on some 32-bit platforms
// (notably ARM) requires 64-bit alignment. So on 32-bit platforms we'll actually size the variant
@@ -1487,8 +1485,8 @@ namespace System.StubHelpers {
// VARIANTs). Note that the field names here don't matter: none of the code refers to these fields,
// the structure just exists to provide size information to the IL marshaler.
#if BIT64
- IntPtr data1;
- IntPtr data2;
+ private IntPtr data1;
+ private IntPtr data2;
#else
Int64 data1;
#endif
@@ -1514,7 +1512,7 @@ namespace System.StubHelpers {
internal sealed class CleanupWorkList
{
private List<CleanupWorkListElement> m_list = new List<CleanupWorkListElement>();
-
+
public void Add(CleanupWorkListElement elem)
{
BCLDebug.Assert(elem.m_owned == false, "m_owned is supposed to be false and set later by DangerousAddRef");
@@ -1612,19 +1610,17 @@ namespace System.StubHelpers {
//-------------------------------------------------------
// SafeHandle Helpers
//-------------------------------------------------------
-
+
// AddRefs the SH and returns the underlying unmanaged handle.
static internal IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success)
{
if (pHandle == null)
{
- throw new ArgumentNullException(nameof(pHandle), Environment.GetResourceString("ArgumentNull_SafeHandle"));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle);
}
- Contract.EndContractBlock();
pHandle.DangerousAddRef(ref success);
-
- return (success ? pHandle.DangerousGetHandle() : IntPtr.Zero);
+ return pHandle.DangerousGetHandle();
}
// Releases the SH (to be called from finally block).
@@ -1632,9 +1628,8 @@ namespace System.StubHelpers {
{
if (pHandle == null)
{
- throw new ArgumentNullException(nameof(pHandle), Environment.GetResourceString("ArgumentNull_SafeHandle"));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle);
}
- Contract.EndContractBlock();
try
{
@@ -1673,7 +1668,7 @@ namespace System.StubHelpers {
//-------------------------------------------------------
// Helper for the MDA RaceOnRCWCleanup
//-------------------------------------------------------
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void StubRegisterRCW(object pThis);
@@ -1727,7 +1722,7 @@ namespace System.StubHelpers {
{
if (length > 0x7ffffff0)
{
- throw new MarshalDirectiveException(Environment.GetResourceString("Marshaler_StringTooLong"));
+ throw new MarshalDirectiveException(SR.Marshaler_StringTooLong);
}
}
@@ -1736,7 +1731,7 @@ namespace System.StubHelpers {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void DecimalCanonicalizeInternal(ref Decimal dec);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal unsafe extern void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkList pCleanupWorkList);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -1751,10 +1746,10 @@ namespace System.StubHelpers {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void MarshalToManagedVaListInternal(IntPtr va_list, IntPtr pArgIterator);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern uint CalcVaListSize(IntPtr va_list);
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern void ValidateObject(object obj, IntPtr pMD, object pThis);
diff --git a/src/mscorlib/src/System/SystemException.cs b/src/mscorlib/src/System/SystemException.cs
deleted file mode 100644
index f4779a2cd4..0000000000
--- a/src/mscorlib/src/System/SystemException.cs
+++ /dev/null
@@ -1,32 +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.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class SystemException : Exception
- {
- public SystemException()
- : base(SR.Arg_SystemException)
- {
- HResult = __HResults.COR_E_SYSTEM;
- }
-
- public SystemException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_SYSTEM;
- }
-
- public SystemException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_SYSTEM;
- }
-
- protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Text/ASCIIEncoding.cs b/src/mscorlib/src/System/Text/ASCIIEncoding.cs
deleted file mode 100644
index 07b7f3e890..0000000000
--- a/src/mscorlib/src/System/Text/ASCIIEncoding.cs
+++ /dev/null
@@ -1,757 +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.
-
-namespace System.Text
-{
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- // ASCIIEncoding
- //
- // Note that ASCIIEncoding is optomized with no best fit and ? for fallback.
- // It doesn't come in other flavors.
- //
- // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit).
- //
- // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd
- // use fallbacks, and we cannot guarantee that fallbacks are normalized.
- //
-
- [Serializable]
- public class ASCIIEncoding : Encoding
- {
- // Used by Encoding.ASCII for lazy initialization
- // The initialization code will not be run until a static member of the class is referenced
- internal static readonly ASCIIEncoding s_default = new ASCIIEncoding();
-
- public ASCIIEncoding() : base(Encoding.CodePageASCII)
- {
- }
-
- internal override void SetDefaultFallbacks()
- {
- // For ASCIIEncoding we just use default replacement fallback
- this.encoderFallback = EncoderFallback.ReplacementFallback;
- this.decoderFallback = DecoderFallback.ReplacementFallback;
- }
-
- // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...)
- // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted,
- // WARNING: or it'll break VB's way of calling these.
-
- // NOTE: Many methods in this class forward to EncodingForwarder for
- // validating arguments/wrapping the unsafe methods in this class
- // which do the actual work. That class contains
- // shared logic for doing this which is used by
- // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
- // UTF7Encoding, and UTF8Encoding.
- // The reason the code is separated out into a static class, rather
- // than a base class which overrides all of these methods for us
- // (which is what EncodingNLS is for internal Encodings) is because
- // that's really more of an implementation detail so it's internal.
- // At the same time, C# doesn't allow a public class subclassing an
- // internal/private one, so we end up having to re-override these
- // methods in all of the public Encodings + EncodingNLS.
-
- // Returns the number of bytes required to encode a range of characters in
- // a character array.
-
- public override int GetByteCount(char[] chars, int index, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, index, count);
- }
-
- public override int GetByteCount(String chars)
- {
- return EncodingForwarder.GetByteCount(this, chars);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetByteCount(char* chars, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, count);
- }
-
- public override int GetBytes(String chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
- }
-
- // Encodes a range of characters in a character array into a range of bytes
- // in a byte array. An exception occurs if the byte array is not large
- // enough to hold the complete encoding of the characters. The
- // GetByteCount method can be used to determine the exact number of
- // bytes that will be produced for a given range of characters.
- // Alternatively, the GetMaxByteCount method can be used to
- // determine the maximum number of bytes that will be produced for a given
- // number of characters, regardless of the actual character values.
-
- public override int GetBytes(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
- {
- return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
- }
-
- // Returns the number of characters produced by decoding a range of bytes
- // in a byte array.
-
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, index, count);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetCharCount(byte* bytes, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, count);
- }
-
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex)
- {
- return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
- }
-
- [CLSCompliant(false)]
- public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
- {
- return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
- }
-
- // Returns a string containing the decoded representation of a range of
- // bytes in a byte array.
-
- public override String GetString(byte[] bytes, int byteIndex, int byteCount)
- {
- return EncodingForwarder.GetString(this, bytes, byteIndex, byteCount);
- }
-
- // End of overridden methods which use EncodingForwarder
-
- // GetByteCount
- // Note: We start by assuming that the output will be the same as count. Having
- // an encoder or fallback may change that assumption
- internal override unsafe int GetByteCount(char* chars, int charCount, EncoderNLS encoder)
- {
- // Just need to ASSERT, this is called by something else internal that checked parameters already
- Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetByteCount]count is negative");
- Debug.Assert(chars != null, "[ASCIIEncoding.GetByteCount]chars is null");
-
- // Assert because we shouldn't be able to have a null encoder.
- Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetByteCount]Attempting to use null fallback encoder");
-
- char charLeftOver = (char)0;
- EncoderReplacementFallback fallback = null;
-
- // Start by assuming default count, then +/- for fallback characters
- char* charEnd = chars + charCount;
-
- // For fallback we may need a fallback buffer, we know we aren't default fallback.
- EncoderFallbackBuffer fallbackBuffer = null;
-
- if (encoder != null)
- {
- charLeftOver = encoder.charLeftOver;
- Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
- "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
-
- fallback = encoder.Fallback as EncoderReplacementFallback;
-
- // We mustn't have left over fallback data when counting
- if (encoder.InternalHasFallbackBuffer)
- {
- // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
- fallbackBuffer = encoder.FallbackBuffer;
- if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
- }
-
- // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
- encoder.FallbackBuffer.Remaining == 0,
- "[ASCIICodePageEncoding.GetByteCount]Expected empty fallback buffer");
-// if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
-// throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
-// this.EncodingName, encoder.Fallback.GetType()));
- }
- else
- {
- fallback = this.EncoderFallback as EncoderReplacementFallback;
- }
-
- // If we have an encoder AND we aren't using default fallback,
- // then we may have a complicated count.
- if (fallback != null && fallback.MaxCharCount == 1)
- {
- // Replacement fallback encodes surrogate pairs as two ?? (or two whatever), so return size is always
- // same as input size.
- // Note that no existing SBCS code pages map code points to supplimentary characters, so this is easy.
-
- // We could however have 1 extra byte if the last call had an encoder and a funky fallback and
- // if we don't use the funky fallback this time.
-
- // Do we have an extra char left over from last time?
- if (charLeftOver > 0)
- charCount++;
-
- return (charCount);
- }
-
- // Count is more complicated if you have a funky fallback
- // For fallback we may need a fallback buffer, we know we're not default fallback
- int byteCount = 0;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- Debug.Assert(Char.IsHighSurrogate(charLeftOver), "[ASCIIEncoding.GetByteCount]leftover character should be high surrogate");
- Debug.Assert(encoder != null, "[ASCIIEncoding.GetByteCount]Expected encoder");
-
- // Since left over char was a surrogate, it'll have to be fallen back.
- // Get Fallback
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, false);
-
- // This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- }
-
- // Now we may have fallback char[] already from the encoder
-
- // Go ahead and do it, including the fallback.
- char ch;
- while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
- chars < charEnd)
- {
-
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // Check for fallback, this'll catch surrogate pairs too.
- // no chars >= 0x80 are allowed.
- if (ch > 0x7f)
- {
- if (fallbackBuffer == null)
- {
- // Initialize the buffer
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, false);
- }
-
- // Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
- continue;
- }
-
- // We'll use this one
- byteCount++;
- }
-
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[ASCIIEncoding.GetByteCount]Expected Empty fallback buffer");
-
- return byteCount;
- }
-
- internal override unsafe int GetBytes(char* chars, int charCount,
- byte* bytes, int byteCount, EncoderNLS encoder)
- {
- // Just need to ASSERT, this is called by something else internal that checked parameters already
- Debug.Assert(bytes != null, "[ASCIIEncoding.GetBytes]bytes is null");
- Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetBytes]byteCount is negative");
- Debug.Assert(chars != null, "[ASCIIEncoding.GetBytes]chars is null");
- Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetBytes]charCount is negative");
-
- // Assert because we shouldn't be able to have a null encoder.
- Debug.Assert(encoderFallback != null, "[ASCIIEncoding.GetBytes]Attempting to use null encoder fallback");
-
- // Get any left over characters
- char charLeftOver = (char)0;
- EncoderReplacementFallback fallback = null;
-
- // For fallback we may need a fallback buffer, we know we aren't default fallback.
- EncoderFallbackBuffer fallbackBuffer = null;
-
- // prepare our end
- char* charEnd = chars + charCount;
- byte* byteStart = bytes;
- char* charStart = chars;
-
- if (encoder != null)
- {
- charLeftOver = encoder.charLeftOver;
- fallback = encoder.Fallback as EncoderReplacementFallback;
-
- // We mustn't have left over fallback data when counting
- if (encoder.InternalHasFallbackBuffer)
- {
- // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
- fallbackBuffer = encoder.FallbackBuffer;
- if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
- }
-
- Debug.Assert(charLeftOver == 0 || Char.IsHighSurrogate(charLeftOver),
- "[ASCIIEncoding.GetBytes]leftover character should be high surrogate");
-
- // Verify that we have no fallbackbuffer, for ASCII its always empty, so just assert
- Debug.Assert(!encoder.m_throwOnOverflow || !encoder.InternalHasFallbackBuffer ||
- encoder.FallbackBuffer.Remaining == 0,
- "[ASCIICodePageEncoding.GetBytes]Expected empty fallback buffer");
-// if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
-// encoder.FallbackBuffer.Remaining > 0)
-// throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
-// this.EncodingName, encoder.Fallback.GetType()));
- }
- else
- {
- fallback = this.EncoderFallback as EncoderReplacementFallback;
- }
-
-
- // See if we do the fast default or slightly slower fallback
- if (fallback != null && fallback.MaxCharCount == 1)
- {
- // Fast version
- char cReplacement = fallback.DefaultString[0];
-
- // Check for replacements in range, otherwise fall back to slow version.
- if (cReplacement <= (char)0x7f)
- {
- // We should have exactly as many output bytes as input bytes, unless there's a left
- // over character, in which case we may need one more.
- // If we had a left over character will have to add a ? (This happens if they had a funky
- // fallback last time, but not this time.) (We can't spit any out though
- // because with fallback encoder each surrogate is treated as a seperate code point)
- if (charLeftOver > 0)
- {
- // Have to have room
- // Throw even if doing no throw version because this is just 1 char,
- // so buffer will never be big enough
- if (byteCount == 0)
- ThrowBytesOverflow(encoder, true);
-
- // This'll make sure we still have more room and also make sure our return value is correct.
- *(bytes++) = (byte)cReplacement;
- byteCount--; // We used one of the ones we were counting.
- }
-
- // This keeps us from overrunning our output buffer
- if (byteCount < charCount)
- {
- // Throw or make buffer smaller?
- ThrowBytesOverflow(encoder, byteCount < 1);
-
- // Just use what we can
- charEnd = chars + byteCount;
- }
-
- // We just do a quick copy
- while (chars < charEnd)
- {
- char ch2 = *(chars++);
- if (ch2 >= 0x0080) *(bytes++) = (byte)cReplacement;
- else *(bytes++) = unchecked((byte)(ch2));
- }
-
- // Clear encoder
- if (encoder != null)
- {
- encoder.charLeftOver = (char)0;
- encoder.m_charsUsed = (int)(chars-charStart);
- }
-
- return (int)(bytes - byteStart);
- }
- }
-
- // Slower version, have to do real fallback.
-
- // prepare our end
- byte* byteEnd = bytes + byteCount;
-
- // We may have a left over character from last time, try and process it.
- if (charLeftOver > 0)
- {
- // Initialize the buffer
- Debug.Assert(encoder != null,
- "[ASCIIEncoding.GetBytes]Expected non null encoder if we have surrogate left over");
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(chars, charEnd, encoder, true);
-
- // Since left over char was a surrogate, it'll have to be fallen back.
- // Get Fallback
- // This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- }
-
- // Now we may have fallback char[] already from the encoder
-
- // Go ahead and do it, including the fallback.
- char ch;
- while ((ch = (fallbackBuffer == null) ? '\0' : fallbackBuffer.InternalGetNextChar()) != 0 ||
- chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // Check for fallback, this'll catch surrogate pairs too.
- // All characters >= 0x80 must fall back.
- if (ch > 0x7f)
- {
- // Initialize the buffer
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(charEnd - charCount, charEnd, encoder, true);
- }
-
- // Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
-
- // Go ahead & continue (& do the fallback)
- continue;
- }
-
- // We'll use this one
- // Bounds check
- if (bytes >= byteEnd)
- {
- // didn't use this char, we'll throw or use buffer
- if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
- {
- Debug.Assert(chars > charStart || bytes == byteStart,
- "[ASCIIEncoding.GetBytes]Expected chars to have advanced already.");
- chars--; // don't use last char
- }
- else
- fallbackBuffer.MovePrevious();
-
- // Are we throwing or using buffer?
- ThrowBytesOverflow(encoder, bytes == byteStart); // throw?
- break; // don't throw, stop
- }
-
- // Go ahead and add it
- *bytes = unchecked((byte)ch);
- bytes++;
- }
-
- // Need to do encoder stuff
- if (encoder != null)
- {
- // Fallback stuck it in encoder if necessary, but we have to clear MustFlush cases
- if (fallbackBuffer != null && !fallbackBuffer.bUsedEncoder)
- // Clear it in case of MustFlush
- encoder.charLeftOver = (char)0;
-
- // Set our chars used count
- encoder.m_charsUsed = (int)(chars - charStart);
- }
-
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
- (encoder != null && !encoder.m_throwOnOverflow ),
- "[ASCIIEncoding.GetBytes]Expected Empty fallback buffer at end");
-
- return (int)(bytes - byteStart);
- }
-
- // This is internal and called by something else,
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
- {
- // Just assert, we're called internally so these should be safe, checked already
- Debug.Assert(bytes != null, "[ASCIIEncoding.GetCharCount]bytes is null");
- Debug.Assert(count >= 0, "[ASCIIEncoding.GetCharCount]byteCount is negative");
-
- // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
- DecoderReplacementFallback fallback = null;
-
- if (decoder == null)
- fallback = this.DecoderFallback as DecoderReplacementFallback;
- else
- {
- fallback = decoder.Fallback as DecoderReplacementFallback;
- Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
- decoder.FallbackBuffer.Remaining == 0,
- "[ASCIICodePageEncoding.GetCharCount]Expected empty fallback buffer");
- }
-
- if (fallback != null && fallback.MaxCharCount == 1)
- {
- // Just return length, SBCS stay the same length because they don't map to surrogate
- // pairs and we don't have a decoder fallback.
-
- return count;
- }
-
- // Only need decoder fallback buffer if not using default replacement fallback, no best fit for ASCII
- DecoderFallbackBuffer fallbackBuffer = null;
-
- // Have to do it the hard way.
- // Assume charCount will be == count
- int charCount = count;
- byte[] byteBuffer = new byte[1];
-
- // Do it our fast way
- byte* byteEnd = bytes + count;
-
- // Quick loop
- while (bytes < byteEnd)
- {
- // Faster if don't use *bytes++;
- byte b = *bytes;
- bytes++;
-
- // If unknown we have to do fallback count
- if (b >= 0x80)
- {
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - count, null);
- }
-
- // Use fallback buffer
- byteBuffer[0] = b;
- charCount--; // Have to unreserve the one we already allocated for b
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
- }
- }
-
- // Fallback buffer must be empty
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[ASCIIEncoding.GetCharCount]Expected Empty fallback buffer");
-
- // Converted sequence is same length as input
- return charCount;
- }
-
- internal override unsafe int GetChars(byte* bytes, int byteCount,
- char* chars, int charCount, DecoderNLS decoder)
- {
- // Just need to ASSERT, this is called by something else internal that checked parameters already
- Debug.Assert(bytes != null, "[ASCIIEncoding.GetChars]bytes is null");
- Debug.Assert(byteCount >= 0, "[ASCIIEncoding.GetChars]byteCount is negative");
- Debug.Assert(chars != null, "[ASCIIEncoding.GetChars]chars is null");
- Debug.Assert(charCount >= 0, "[ASCIIEncoding.GetChars]charCount is negative");
-
- // Do it fast way if using ? replacement fallback
- byte* byteEnd = bytes + byteCount;
- byte* byteStart = bytes;
- char* charStart = chars;
-
- // Note: ASCII doesn't do best fit, but we have to fallback if they use something > 0x7f
- // Only need decoder fallback buffer if not using ? fallback.
- // ASCII doesn't do best fit, so don't have to check for it, find out which decoder fallback we're using
- DecoderReplacementFallback fallback = null;
-
- if (decoder == null)
- fallback = this.DecoderFallback as DecoderReplacementFallback;
- else
- {
- fallback = decoder.Fallback as DecoderReplacementFallback;
- Debug.Assert(!decoder.m_throwOnOverflow || !decoder.InternalHasFallbackBuffer ||
- decoder.FallbackBuffer.Remaining == 0,
- "[ASCIICodePageEncoding.GetChars]Expected empty fallback buffer");
- }
-
- if (fallback != null && fallback.MaxCharCount == 1)
- {
- // Try it the fast way
- char replacementChar = fallback.DefaultString[0];
-
- // Need byteCount chars, otherwise too small buffer
- if (charCount < byteCount)
- {
- // Need at least 1 output byte, throw if must throw
- ThrowCharsOverflow(decoder, charCount < 1);
-
- // Not throwing, use what we can
- byteEnd = bytes + charCount;
- }
-
- // Quick loop, just do '?' replacement because we don't have fallbacks for decodings.
- while (bytes < byteEnd)
- {
- byte b = *(bytes++);
- if (b >= 0x80)
- // This is an invalid byte in the ASCII encoding.
- *(chars++) = replacementChar;
- else
- *(chars++) = unchecked((char)b);
- }
-
- // bytes & chars used are the same
- if (decoder != null)
- decoder.m_bytesUsed = (int)(bytes - byteStart);
- return (int)(chars - charStart);
- }
-
- // Slower way's going to need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
- byte[] byteBuffer = new byte[1];
- char* charEnd = chars + charCount;
-
- // Not quite so fast loop
- while (bytes < byteEnd)
- {
- // Faster if don't use *bytes++;
- byte b = *(bytes);
- bytes++;
-
- if (b >= 0x80)
- {
- // This is an invalid byte in the ASCII encoding.
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.DecoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
- fallbackBuffer.InternalInitialize(byteEnd - byteCount, charEnd);
- }
-
- // Use fallback buffer
- byteBuffer[0] = b;
-
- // Note that chars won't get updated unless this succeeds
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // May or may not throw, but we didn't get this byte
- Debug.Assert(bytes > byteStart || chars == charStart,
- "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (fallback case)");
- bytes--; // unused byte
- fallbackBuffer.InternalReset(); // Didn't fall this back
- ThrowCharsOverflow(decoder, chars == charStart); // throw?
- break; // don't throw, but stop loop
- }
- }
- else
- {
- // Make sure we have buffer space
- if (chars >= charEnd)
- {
- Debug.Assert(bytes > byteStart || chars == charStart,
- "[ASCIIEncoding.GetChars]Expected bytes to have advanced already (normal case)");
- bytes--; // unused byte
- ThrowCharsOverflow(decoder, chars == charStart); // throw?
- break; // don't throw, but stop loop
- }
-
- *(chars) = unchecked((char)b);
- chars++;
- }
- }
-
- // Might have had decoder fallback stuff.
- if (decoder != null)
- decoder.m_bytesUsed = (int)(bytes - byteStart);
-
- // Expect Empty fallback buffer for GetChars
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[ASCIIEncoding.GetChars]Expected Empty fallback buffer");
-
- return (int)(chars - charStart);
- }
-
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // 1 to 1 for most characters. Only surrogates with fallbacks have less.
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
- return (int)byteCount;
- }
-
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Just return length, SBCS stay the same length because they don't map to surrogate
- long charCount = (long)byteCount;
-
- // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer.
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
- // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc)
-
- public override bool IsSingleByte
- {
- get
- {
- return true;
- }
- }
-
- public override Decoder GetDecoder()
- {
- return new DecoderNLS(this);
- }
-
-
- public override Encoder GetEncoder()
- {
- return new EncoderNLS(this);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/Decoder.cs b/src/mscorlib/src/System/Text/Decoder.cs
deleted file mode 100644
index a9fea82a39..0000000000
--- a/src/mscorlib/src/System/Text/Decoder.cs
+++ /dev/null
@@ -1,338 +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.
-
-namespace System.Text
-{
- using System.Runtime.Serialization;
- using System.Text;
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- // A Decoder is used to decode a sequence of blocks of bytes into a
- // sequence of blocks of characters. Following instantiation of a decoder,
- // sequential blocks of bytes are converted into blocks of characters through
- // calls to the GetChars method. The decoder maintains state between the
- // conversions, allowing it to correctly decode byte sequences that span
- // adjacent blocks.
- //
- // Instances of specific implementations of the Decoder abstract base
- // class are typically obtained through calls to the GetDecoder method
- // of Encoding objects.
- //
- [Serializable]
- public abstract class Decoder
- {
- internal DecoderFallback m_fallback = null;
-
- [NonSerialized]
- internal DecoderFallbackBuffer m_fallbackBuffer = null;
-
- internal void SerializeDecoder(SerializationInfo info)
- {
- info.AddValue("m_fallback", this.m_fallback);
- }
-
- protected Decoder( )
- {
- // We don't call default reset because default reset probably isn't good if we aren't initialized.
- }
-
- public DecoderFallback Fallback
- {
- get
- {
- return m_fallback;
- }
-
- set
- {
- if (value == null)
- throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
-
- // Can't change fallback if buffer is wrong
- if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
- throw new ArgumentException(
- Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value));
-
- m_fallback = value;
- m_fallbackBuffer = null;
- }
- }
-
- // Note: we don't test for threading here because async access to Encoders and Decoders
- // doesn't work anyway.
- public DecoderFallbackBuffer FallbackBuffer
- {
- get
- {
- if (m_fallbackBuffer == null)
- {
- if (m_fallback != null)
- m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
- else
- m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer();
- }
-
- return m_fallbackBuffer;
- }
- }
-
- internal bool InternalHasFallbackBuffer
- {
- get
- {
- return m_fallbackBuffer != null;
- }
- }
-
- // Reset the Decoder
- //
- // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This
- // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
- //
- // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset().
- //
- // Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string
- // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big.
- public virtual void Reset()
- {
- byte[] byteTemp = Array.Empty<byte>();
- char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)];
- GetChars(byteTemp, 0, 0, charTemp, 0, true);
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Returns the number of characters the next call to GetChars will
- // produce if presented with the given range of bytes. The returned value
- // takes into account the state in which the decoder was left following the
- // last call to GetChars. The state of the decoder is not affected
- // by a call to this method.
- //
- public abstract int GetCharCount(byte[] bytes, int index, int count);
-
- public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush)
- {
- return GetCharCount(bytes, index, count);
- }
-
- // We expect this to be the workhorse for NLS Encodings, but for existing
- // ones we need a working (if slow) default implimentation)
- [CLSCompliant(false)]
- public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush)
- {
- // Validate input parameters
- if (bytes == null)
- throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- byte[] arrbyte = new byte[count];
- int index;
-
- for (index = 0; index < count; index++)
- arrbyte[index] = bytes[index];
-
- return GetCharCount(arrbyte, 0, count);
- }
-
- // 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
- // characters in chars starting at index charIndex. The
- // decoding takes into account the state in which the decoder was left
- // following the last call to this method.
- //
- // An exception occurs if the character array is not large enough to
- // hold the complete decoding of the bytes. The GetCharCount method
- // can be used to determine the exact number of characters that will be
- // produced for a given range of bytes. Alternatively, the
- // GetMaxCharCount method of the Encoding that produced this
- // decoder can be used to determine the maximum number of characters that
- // will be produced for a given number of bytes, regardless of the actual
- // byte values.
- //
- public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex);
-
- public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex, bool flush)
- {
- return GetChars(bytes, byteIndex, byteCount, chars, charIndex);
- }
-
- // We expect this to be the workhorse for NLS Encodings, but for existing
- // ones we need a working (if slow) default implimentation)
- //
- // WARNING WARNING WARNING
- //
- // WARNING: If this breaks it could be a security threat. Obviously we
- // call this internally, so you need to make sure that your pointers, counts
- // and indexes are correct when you call this method.
- //
- // In addition, we have internal code, which will be marked as "safe" calling
- // this code. However this code is dependent upon the implimentation of an
- // external GetChars() method, which could be overridden by a third party and
- // the results of which cannot be guaranteed. We use that result to copy
- // the char[] to our char* output buffer. If the result count was wrong, we
- // could easily overflow our output buffer. Therefore we do an extra test
- // when we copy the buffer so that we don't overflow charCount either.
- [CLSCompliant(false)]
- public virtual unsafe int GetChars(byte* bytes, int byteCount,
- char* chars, int charCount, bool flush)
- {
- // Validate input parameters
- if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Get the byte array to convert
- byte[] arrByte = new byte[byteCount];
-
- int index;
- for (index = 0; index < byteCount; index++)
- arrByte[index] = bytes[index];
-
- // Get the char array to fill
- char[] arrChar = new char[charCount];
-
- // Do the work
- int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush);
-
- Debug.Assert(result <= charCount, "Returned more chars than we have space for");
-
- // Copy the char array
- // WARNING: We MUST make sure that we don't copy too many chars. We can't
- // rely on result because it could be a 3rd party implimentation. We need
- // to make sure we never copy more than charCount chars no matter the value
- // of result
- if (result < charCount)
- charCount = result;
-
- // We check both result and charCount so that we don't accidentally overrun
- // our pointer buffer just because of an issue in GetChars
- for (index = 0; index < charCount; index++)
- chars[index] = arrChar[index];
-
- return charCount;
- }
-
- // 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
- // will also return the number of converted bytes and output characters used.
- // It will only throw a buffer overflow exception if the entire lenght of chars[] is
- // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings)
- // We're done processing this buffer only if completed returns true.
- //
- // Might consider checking Max...Count to avoid the extra counting step.
- //
- // Note that if all of the input bytes are not consumed, then we'll do a /2, which means
- // that its likely that we didn't consume as many bytes as we could have. For some
- // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
- public virtual void Convert(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex, int charCount, bool flush,
- out int bytesUsed, out int charsUsed, out bool completed)
- {
- // Validate parameters
- if (bytes == null || chars == null)
- throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
-
- if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
-
- if (bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException(nameof(bytes),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
-
- if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException(nameof(chars),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- Contract.EndContractBlock();
-
- bytesUsed = byteCount;
-
- // Its easy to do if it won't overrun our buffer.
- while (bytesUsed > 0)
- {
- if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount)
- {
- charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush);
- completed = (bytesUsed == byteCount &&
- (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
- return;
- }
-
- // Try again with 1/2 the count, won't flush then 'cause won't read it all
- flush = false;
- bytesUsed /= 2;
- }
-
- // Oops, we didn't have anything, we'll have to throw an overflow
- throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
- }
-
- // This is the version that uses *.
- // We're done processing this buffer only if completed returns true.
- //
- // Might consider checking Max...Count to avoid the extra counting step.
- //
- // Note that if all of the input bytes are not consumed, then we'll do a /2, which means
- // that its likely that we didn't consume as many bytes as we could have. For some
- // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
- [CLSCompliant(false)]
- public virtual unsafe void Convert(byte* bytes, int byteCount,
- char* chars, int charCount, bool flush,
- out int bytesUsed, out int charsUsed, out bool completed)
- {
- // Validate input parameters
- if (chars == null || bytes == null)
- throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Get ready to do it
- bytesUsed = byteCount;
-
- // Its easy to do if it won't overrun our buffer.
- while (bytesUsed > 0)
- {
- if (GetCharCount(bytes, bytesUsed, flush) <= charCount)
- {
- charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush);
- completed = (bytesUsed == byteCount &&
- (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
- return;
- }
-
- // Try again with 1/2 the count, won't flush then 'cause won't read it all
- flush = false;
- bytesUsed /= 2;
- }
-
- // Oops, we didn't have anything, we'll have to throw an overflow
- throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
index 6389b4b141..ad88ef4400 100644
--- a/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderBestFitFallback.cs
@@ -5,21 +5,22 @@
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
+
+using System;
+using System.Text;
+using System.Threading;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System;
- using System.Text;
- using System.Threading;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
[Serializable]
internal sealed class InternalDecoderBestFitFallback : DecoderFallback
{
// Our variables
internal Encoding encoding = null;
- internal char[] arrayBestFit = null;
- internal char cReplacement = '?';
+ internal char[] arrayBestFit = null;
+ internal char cReplacement = '?';
internal InternalDecoderBestFitFallback(Encoding encoding)
{
@@ -61,10 +62,10 @@ namespace System.Text
internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
{
// Our variables
- internal char cBestFit = '\0';
- internal int iCount = -1;
- internal int iSize;
- private InternalDecoderBestFitFallback oFallback;
+ internal char cBestFit = '\0';
+ internal int iCount = -1;
+ internal int iSize;
+ private InternalDecoderBestFitFallback oFallback;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
@@ -84,12 +85,12 @@ namespace System.Text
// Constructor
public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback)
{
- this.oFallback = fallback;
+ oFallback = fallback;
if (oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
- lock(InternalSyncObject)
+ lock (InternalSyncObject)
{
// Double check before we do it again.
if (oFallback.arrayBestFit == null)
@@ -119,7 +120,7 @@ namespace System.Text
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
-
+
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
@@ -228,7 +229,7 @@ namespace System.Text
}
for (index = lowBound; index < highBound; index += 2)
- {
+ {
if (oFallback.arrayBestFit[index] == cCheck)
{
// We found it
diff --git a/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs b/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs
index 7a0478de20..b98ef74ed2 100644
--- a/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderExceptionFallback.cs
@@ -2,12 +2,12 @@
// 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;
+using System.Globalization;
+
namespace System.Text
{
- using System;
- using System.Runtime.Serialization;
- using System.Globalization;
-
[Serializable]
public sealed class DecoderExceptionFallback : DecoderFallback
{
@@ -87,42 +87,40 @@ namespace System.Text
strBytes.Append(bytesUnknown[i].ToString("X2", CultureInfo.InvariantCulture));
strBytes.Append("]");
}
-
+
// In case the string's really long
if (i == 20)
strBytes.Append(" ...");
// Known index
throw new DecoderFallbackException(
- Environment.GetResourceString("Argument_InvalidCodePageBytesIndex",
- strBytes, index), bytesUnknown, index);
+ SR.Format(SR.Argument_InvalidCodePageBytesIndex, strBytes, index), bytesUnknown, index);
}
-
}
// Exception for decoding unknown byte sequences.
[Serializable]
public sealed class DecoderFallbackException : ArgumentException
{
- byte[] bytesUnknown = null;
- int index = 0;
+ private byte[] bytesUnknown = null;
+ private int index = 0;
public DecoderFallbackException()
- : base(Environment.GetResourceString("Arg_ArgumentException"))
+ : base(SR.Arg_ArgumentException)
{
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ HResult = __HResults.COR_E_ARGUMENT;
}
public DecoderFallbackException(String message)
: base(message)
{
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ HResult = __HResults.COR_E_ARGUMENT;
}
public DecoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ HResult = __HResults.COR_E_ARGUMENT;
}
internal DecoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
@@ -148,7 +146,7 @@ namespace System.Text
{
get
{
- return this.index;
+ return index;
}
}
}
diff --git a/src/mscorlib/src/System/Text/DecoderFallback.cs b/src/mscorlib/src/System/Text/DecoderFallback.cs
index bfd4a2852d..9311cda585 100644
--- a/src/mscorlib/src/System/Text/DecoderFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderFallback.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
//
+
using System;
using System.Security;
using System.Threading;
@@ -15,7 +16,7 @@ namespace System.Text
[Serializable]
public abstract class DecoderFallback
{
- internal bool bIsMicrosoftBestFitFallback = false;
+ internal bool bIsMicrosoftBestFitFallback = false;
private static volatile DecoderFallback replacementFallback; // Default fallback, uses no best fit & "?"
private static volatile DecoderFallback exceptionFallback;
@@ -42,7 +43,7 @@ namespace System.Text
get
{
if (replacementFallback == null)
- lock(InternalSyncObject)
+ lock (InternalSyncObject)
if (replacementFallback == null)
replacementFallback = new DecoderReplacementFallback();
@@ -56,7 +57,7 @@ namespace System.Text
get
{
if (exceptionFallback == null)
- lock(InternalSyncObject)
+ lock (InternalSyncObject)
if (exceptionFallback == null)
exceptionFallback = new DecoderExceptionFallback();
@@ -103,13 +104,13 @@ namespace System.Text
public virtual void Reset()
{
- while (GetNextChar() != (char)0);
+ while (GetNextChar() != (char)0) ;
}
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
- internal unsafe byte* byteStart;
- internal unsafe char* charEnd;
+ internal unsafe byte* byteStart;
+ internal unsafe char* charEnd;
// Internal Reset
internal unsafe void InternalReset()
@@ -137,9 +138,9 @@ namespace System.Text
internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
{
// Copy bytes to array (slow, but right now that's what we get to do.
- // byte[] bytesUnknown = new byte[count];
-// for (int i = 0; i < count; i++)
-// bytesUnknown[i] = *(bytes++);
+ // byte[] bytesUnknown = new byte[count];
+ // for (int i = 0; i < count; i++)
+ // bytesUnknown[i] = *(bytes++);
Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
@@ -159,14 +160,14 @@ namespace System.Text
{
// High Surrogate
if (bHighSurrogate)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = true;
}
else
{
// Low surrogate
if (bHighSurrogate == false)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = false;
}
}
@@ -182,7 +183,7 @@ namespace System.Text
// Need to make sure that bHighSurrogate isn't true
if (bHighSurrogate)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
// Now we aren't going to be false, so its OK to update chars
chars = charTemp;
@@ -197,9 +198,9 @@ namespace System.Text
// array, and we might need the index, hence the byte*
{
// Copy bytes to array (slow, but right now that's what we get to do.
-// byte[] bytesUnknown = new byte[count];
-// for (int i = 0; i < count; i++)
- // bytesUnknown[i] = *(bytes++);
+ // byte[] bytesUnknown = new byte[count];
+ // for (int i = 0; i < count; i++)
+ // bytesUnknown[i] = *(bytes++);
Debug.Assert(byteStart != null, "[DecoderFallback.InternalFallback]Used InternalFallback without calling InternalInitialize");
@@ -219,14 +220,14 @@ namespace System.Text
{
// High Surrogate
if (bHighSurrogate)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = true;
}
else
{
// Low surrogate
if (bHighSurrogate == false)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
bHighSurrogate = false;
}
}
@@ -236,7 +237,7 @@ namespace System.Text
// Need to make sure that bHighSurrogate isn't true
if (bHighSurrogate)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
return count;
}
@@ -263,9 +264,7 @@ namespace System.Text
// Throw it, using our complete bytes
throw new ArgumentException(
- Environment.GetResourceString("Argument_RecursiveFallbackBytes",
- strBytes.ToString()), nameof(bytesUnknown));
+ SR.Format(SR.Argument_RecursiveFallbackBytes, strBytes.ToString()), nameof(bytesUnknown));
}
-
}
}
diff --git a/src/mscorlib/src/System/Text/DecoderNLS.cs b/src/mscorlib/src/System/Text/DecoderNLS.cs
index 79474f8d8c..6fcfc79140 100644
--- a/src/mscorlib/src/System/Text/DecoderNLS.cs
+++ b/src/mscorlib/src/System/Text/DecoderNLS.cs
@@ -2,12 +2,13 @@
// 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;
+using System.Text;
+using System;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System.Runtime.Serialization;
- using System.Text;
- using System;
- using System.Diagnostics.Contracts;
// A Decoder is used to decode a sequence of blocks of bytes into a
// sequence of blocks of characters. Following instantiation of a decoder,
// sequential blocks of bytes are converted into blocks of characters through
@@ -24,20 +25,20 @@ namespace System.Text
internal class DecoderNLS : Decoder, ISerializable
{
// Remember our encoding
- protected Encoding m_encoding;
- [NonSerialized] protected bool m_mustFlush;
- [NonSerialized] internal bool m_throwOnOverflow;
- [NonSerialized] internal int m_bytesUsed;
+ protected Encoding m_encoding;
+ [NonSerialized] protected bool m_mustFlush;
+ [NonSerialized] internal bool m_throwOnOverflow;
+ [NonSerialized] internal int m_bytesUsed;
-#region Serialization
+ #region Serialization
// Constructor called by serialization. called during deserialization.
internal DecoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
- System.Globalization.CultureInfo.CurrentCulture,
- Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
+ System.Globalization.CultureInfo.CurrentCulture,
+ SR.NotSupported_TypeCannotDeserialized, this.GetType()));
}
// ISerializable implementation. called during serialization.
@@ -48,9 +49,9 @@ namespace System.Text
info.SetType(typeof(Encoding.DefaultDecoder));
}
-#endregion Serialization
+ #endregion Serialization
- internal DecoderNLS( Encoding encoding )
+ internal DecoderNLS(Encoding encoding)
{
this.m_encoding = encoding;
this.m_fallback = this.m_encoding.DecoderFallback;
@@ -58,7 +59,7 @@ namespace System.Text
}
// This is used by our child deserializers
- internal DecoderNLS( )
+ internal DecoderNLS()
{
this.m_encoding = null;
this.Reset();
@@ -80,15 +81,15 @@ namespace System.Text
// Validate Parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(bytes),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
@@ -106,11 +107,11 @@ namespace System.Text
// Validate parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember the flush
@@ -133,19 +134,19 @@ namespace System.Text
// Validate Parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
- if ( bytes.Length - byteIndex < byteCount)
+ if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
if (charIndex < 0 || charIndex > chars.Length)
throw new ArgumentOutOfRangeException(nameof(charIndex),
- Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
@@ -159,10 +160,10 @@ namespace System.Text
// Just call pointer version
fixed (byte* pBytes = &bytes[0])
- fixed (char* pChars = &chars[0])
- // Remember that charCount is # to decode, not size of array
- return GetChars(pBytes + byteIndex, byteCount,
- pChars + charIndex, charCount, flush);
+ fixed (char* pChars = &chars[0])
+ // Remember that charCount is # to decode, not size of array
+ return GetChars(pBytes + byteIndex, byteCount,
+ pChars + charIndex, charCount, flush);
}
public unsafe override int GetChars(byte* bytes, int byteCount,
@@ -171,11 +172,11 @@ namespace System.Text
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Remember our flush
@@ -195,23 +196,23 @@ namespace System.Text
// Validate parameters
if (bytes == null || chars == null)
throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
@@ -241,11 +242,11 @@ namespace System.Text
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
diff --git a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
index 77c856046d..b27469156d 100644
--- a/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/DecoderReplacementFallback.cs
@@ -2,12 +2,12 @@
// 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;
+
namespace System.Text
{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
[Serializable]
public sealed class DecoderReplacementFallback : DecoderFallback
{
@@ -26,11 +26,11 @@ namespace System.Text
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
- bool bFoundHigh=false;
+ bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
- if (Char.IsSurrogate(replacement,i))
+ if (Char.IsSurrogate(replacement, i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
@@ -59,17 +59,17 @@ namespace System.Text
break;
}
if (bFoundHigh)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement)));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement)));
strDefault = replacement;
}
public String DefaultString
{
- get
- {
+ get
+ {
return strDefault;
- }
+ }
}
public override DecoderFallbackBuffer CreateFallbackBuffer()
@@ -91,7 +91,7 @@ namespace System.Text
DecoderReplacementFallback that = value as DecoderReplacementFallback;
if (that != null)
{
- return (this.strDefault == that.strDefault);
+ return (strDefault == that.strDefault);
}
return (false);
}
@@ -108,13 +108,13 @@ namespace System.Text
{
// Store our default string
private String strDefault;
- int fallbackCount = -1;
- int fallbackIndex = -1;
+ private int fallbackCount = -1;
+ private int fallbackIndex = -1;
// Construction
public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback)
{
- this.strDefault = fallback.DefaultString;
+ strDefault = fallback.DefaultString;
}
// Fallback Methods
@@ -160,7 +160,7 @@ namespace System.Text
Debug.Assert(fallbackIndex < strDefault.Length && fallbackIndex >= 0,
"Index exceeds buffer range");
- return strDefault[fallbackIndex];
+ return strDefault[fallbackIndex];
}
public override bool MovePrevious()
diff --git a/src/mscorlib/src/System/Text/Encoder.cs b/src/mscorlib/src/System/Text/Encoder.cs
deleted file mode 100644
index f766f98142..0000000000
--- a/src/mscorlib/src/System/Text/Encoder.cs
+++ /dev/null
@@ -1,332 +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.
-
-namespace System.Text
-{
- using System.Runtime.Serialization;
- using System.Text;
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- // An Encoder is used to encode a sequence of blocks of characters into
- // a sequence of blocks of bytes. Following instantiation of an encoder,
- // sequential blocks of characters are converted into blocks of bytes through
- // calls to the GetBytes method. The encoder maintains state between the
- // conversions, allowing it to correctly encode character sequences that span
- // adjacent blocks.
- //
- // Instances of specific implementations of the Encoder abstract base
- // class are typically obtained through calls to the GetEncoder method
- // of Encoding objects.
- //
- [Serializable]
- public abstract class Encoder
- {
- internal EncoderFallback m_fallback = null;
-
- [NonSerialized]
- internal EncoderFallbackBuffer m_fallbackBuffer = null;
-
- internal void SerializeEncoder(SerializationInfo info)
- {
- info.AddValue("m_fallback", this.m_fallback);
- }
-
- protected Encoder()
- {
- // We don't call default reset because default reset probably isn't good if we aren't initialized.
- }
-
- public EncoderFallback Fallback
- {
- get
- {
- return m_fallback;
- }
-
- set
- {
- if (value == null)
- throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
-
- // Can't change fallback if buffer is wrong
- if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0)
- throw new ArgumentException(
- Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), nameof(value));
-
- m_fallback = value;
- m_fallbackBuffer = null;
- }
- }
-
- // Note: we don't test for threading here because async access to Encoders and Decoders
- // doesn't work anyway.
- public EncoderFallbackBuffer FallbackBuffer
- {
- get
- {
- if (m_fallbackBuffer == null)
- {
- if (m_fallback != null)
- m_fallbackBuffer = m_fallback.CreateFallbackBuffer();
- else
- m_fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer();
- }
-
- return m_fallbackBuffer;
- }
- }
-
- internal bool InternalHasFallbackBuffer
- {
- get
- {
- return m_fallbackBuffer != null;
- }
- }
-
- // Reset the Encoder
- //
- // Normally if we call GetBytes() and an error is thrown we don't change the state of the encoder. This
- // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.)
- //
- // If the caller doesn't want to try again after GetBytes() throws an error, then they need to call Reset().
- //
- // Virtual implimentation has to call GetBytes with flush and a big enough buffer to clear a 0 char string
- // We avoid GetMaxByteCount() because a) we can't call the base encoder and b) it might be really big.
- public virtual void Reset()
- {
- char[] charTemp = {};
- byte[] byteTemp = new byte[GetByteCount(charTemp, 0, 0, true)];
- GetBytes(charTemp, 0, 0, byteTemp, 0, true);
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Returns the number of bytes the next call to GetBytes will
- // produce if presented with the given range of characters and the given
- // value of the flush parameter. The returned value takes into
- // account the state in which the encoder was left following the last call
- // to GetBytes. The state of the encoder is not affected by a call
- // to this method.
- //
- public abstract int GetByteCount(char[] chars, int index, int count, bool flush);
-
- // We expect this to be the workhorse for NLS encodings
- // unfortunately for existing overrides, it has to call the [] version,
- // which is really slow, so avoid this method if you might be calling external encodings.
- [CLSCompliant(false)]
- public virtual unsafe int GetByteCount(char* chars, int count, bool flush)
- {
- // Validate input parameters
- if (chars == null)
- throw new ArgumentNullException(nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (count < 0)
- throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- char[] arrChar = new char[count];
- int index;
-
- for (index = 0; index < count; index++)
- arrChar[index] = chars[index];
-
- return GetByteCount(arrChar, 0, count, 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
- // bytes in bytes starting at index byteIndex. The encoding
- // takes into account the state in which the encoder was left following the
- // last call to this method. The flush parameter indicates whether
- // the encoder should flush any shift-states and partial characters at the
- // end of the conversion. To ensure correct termination of a sequence of
- // blocks of encoded bytes, the last call to GetBytes should specify
- // a value of true for the flush parameter.
- //
- // An exception occurs if the byte array is not large enough to hold the
- // complete encoding of the characters. The GetByteCount method can
- // be used to determine the exact number of bytes that will be produced for
- // a given range of characters. Alternatively, the GetMaxByteCount
- // method of the Encoding that produced this encoder can be used to
- // determine the maximum number of bytes that will be produced for a given
- // number of characters, regardless of the actual character values.
- //
- public abstract int GetBytes(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex, bool flush);
-
- // We expect this to be the workhorse for NLS Encodings, but for existing
- // ones we need a working (if slow) default implimentation)
- //
- // WARNING WARNING WARNING
- //
- // WARNING: If this breaks it could be a security threat. Obviously we
- // call this internally, so you need to make sure that your pointers, counts
- // and indexes are correct when you call this method.
- //
- // In addition, we have internal code, which will be marked as "safe" calling
- // this code. However this code is dependent upon the implimentation of an
- // external GetBytes() method, which could be overridden by a third party and
- // the results of which cannot be guaranteed. We use that result to copy
- // the byte[] to our byte* output buffer. If the result count was wrong, we
- // could easily overflow our output buffer. Therefore we do an extra test
- // when we copy the buffer so that we don't overflow byteCount either.
- [CLSCompliant(false)]
- public virtual unsafe int GetBytes(char* chars, int charCount,
- byte* bytes, int byteCount, bool flush)
- {
- // Validate input parameters
- if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Get the char array to convert
- char[] arrChar = new char[charCount];
-
- int index;
- for (index = 0; index < charCount; index++)
- arrChar[index] = chars[index];
-
- // Get the byte array to fill
- byte[] arrByte = new byte[byteCount];
-
- // Do the work
- int result = GetBytes(arrChar, 0, charCount, arrByte, 0, flush);
-
- Debug.Assert(result <= byteCount, "Returned more bytes than we have space for");
-
- // Copy the byte array
- // WARNING: We MUST make sure that we don't copy too many bytes. We can't
- // rely on result because it could be a 3rd party implimentation. We need
- // to make sure we never copy more than byteCount bytes no matter the value
- // of result
- if (result < byteCount)
- byteCount = result;
-
- // Don't copy too many bytes!
- for (index = 0; index < byteCount; index++)
- bytes[index] = arrByte[index];
-
- return byteCount;
- }
-
- // 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
- // will also return the number of converted chars and output bytes used.
- // It will only throw a buffer overflow exception if the entire lenght of bytes[] is
- // too small to store the next byte. (like 0 or maybe 1 or 4 for some encodings)
- // We're done processing this buffer only if completed returns true.
- //
- // Might consider checking Max...Count to avoid the extra counting step.
- //
- // Note that if all of the input chars are not consumed, then we'll do a /2, which means
- // that its likely that we didn't consume as many chars as we could have. For some
- // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
- public virtual void Convert(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex, int byteCount, bool flush,
- out int charsUsed, out int bytesUsed, out bool completed)
- {
- // Validate parameters
- if (chars == null || bytes == null)
- throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
- Environment.GetResourceString("ArgumentNull_Array"));
-
- if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
-
- if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
-
- if (chars.Length - charIndex < charCount)
- throw new ArgumentOutOfRangeException(nameof(chars),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
-
- if (bytes.Length - byteIndex < byteCount)
- throw new ArgumentOutOfRangeException(nameof(bytes),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- Contract.EndContractBlock();
-
- charsUsed = charCount;
-
- // Its easy to do if it won't overrun our buffer.
- // Note: We don't want to call unsafe version because that might be an untrusted version
- // which could be really unsafe and we don't want to mix it up.
- while (charsUsed > 0)
- {
- if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount)
- {
- bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush);
- completed = (charsUsed == charCount &&
- (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
- return;
- }
-
- // Try again with 1/2 the count, won't flush then 'cause won't read it all
- flush = false;
- charsUsed /= 2;
- }
-
- // Oops, we didn't have anything, we'll have to throw an overflow
- throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
- }
-
- // Same thing, but using pointers
- //
- // Might consider checking Max...Count to avoid the extra counting step.
- //
- // Note that if all of the input chars are not consumed, then we'll do a /2, which means
- // that its likely that we didn't consume as many chars as we could have. For some
- // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream)
- [CLSCompliant(false)]
- public virtual unsafe void Convert(char* chars, int charCount,
- byte* bytes, int byteCount, bool flush,
- out int charsUsed, out int bytesUsed, out bool completed)
- {
- // Validate input parameters
- if (bytes == null || chars == null)
- throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
- if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Get ready to do it
- charsUsed = charCount;
-
- // Its easy to do if it won't overrun our buffer.
- while (charsUsed > 0)
- {
- if (GetByteCount(chars, charsUsed, flush) <= byteCount)
- {
- bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush);
- completed = (charsUsed == charCount &&
- (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0));
- return;
- }
-
- // Try again with 1/2 the count, won't flush then 'cause won't read it all
- flush = false;
- charsUsed /= 2;
- }
-
- // Oops, we didn't have anything, we'll have to throw an overflow
- throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow"));
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
index 9be095bbd8..eb3165526b 100644
--- a/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderBestFitFallback.cs
@@ -5,21 +5,22 @@
//
// This is used internally to create best fit behavior as per the original windows best fit behavior.
//
+
+using System;
+using System.Globalization;
+using System.Text;
+using System.Threading;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System;
- using System.Globalization;
- using System.Text;
- using System.Threading;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
[Serializable]
- internal class InternalEncoderBestFitFallback : EncoderFallback
+ internal sealed class InternalEncoderBestFitFallback : EncoderFallback
{
// Our variables
internal Encoding encoding = null;
- internal char[] arrayBestFit = null;
+ internal char[] arrayBestFit = null;
internal InternalEncoderBestFitFallback(Encoding encoding)
{
@@ -61,10 +62,10 @@ namespace System.Text
internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
{
// Our variables
- private char cBestFit = '\0';
- private InternalEncoderBestFitFallback oFallback;
- private int iCount = -1;
- private int iSize;
+ private char cBestFit = '\0';
+ private InternalEncoderBestFitFallback oFallback;
+ private int iCount = -1;
+ private int iSize;
// Private object for locking instead of locking on a public type for SQL reliability work.
private static Object s_InternalSyncObject;
@@ -84,12 +85,12 @@ namespace System.Text
// Constructor
public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
{
- this.oFallback = fallback;
+ oFallback = fallback;
if (oFallback.arrayBestFit == null)
{
// Lock so we don't confuse ourselves.
- lock(InternalSyncObject)
+ lock (InternalSyncObject)
{
// Double check before we do it again.
if (oFallback.arrayBestFit == null)
@@ -119,13 +120,11 @@ namespace System.Text
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xD800, 0xDBFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xDC00, 0xDFFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
Contract.EndContractBlock();
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
@@ -146,7 +145,7 @@ namespace System.Text
// We want it to get < 0 because == 0 means that the current/last character is a fallback
// and we need to detect recursion. We could have a flag but we already have this counter.
iCount--;
-
+
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (iCount < 0)
return '\0';
diff --git a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
index 6735e7a5f8..b75847d1e7 100644
--- a/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderExceptionFallback.cs
@@ -2,12 +2,12 @@
// 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;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
-
[Serializable]
public sealed class EncoderExceptionFallback : EncoderFallback
{
@@ -49,13 +49,12 @@ namespace System.Text
public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer
{
- public EncoderExceptionFallbackBuffer(){}
+ public EncoderExceptionFallbackBuffer() { }
public override bool Fallback(char charUnknown, int index)
{
// Fall back our char
throw new EncoderFallbackException(
- Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
- (int)charUnknown, index), charUnknown, index);
+ SR.Format(SR.Argument_InvalidCodePageConversionIndex, (int)charUnknown, index), charUnknown, index);
}
public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
@@ -63,14 +62,12 @@ namespace System.Text
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xD800, 0xDBFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xDC00, 0xDFFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
@@ -78,8 +75,7 @@ namespace System.Text
// Fall back our char
throw new EncoderFallbackException(
- Environment.GetResourceString("Argument_InvalidCodePageConversionIndex",
- iTemp, index), charUnknownHigh, charUnknownLow, index);
+ SR.Format(SR.Argument_InvalidCodePageConversionIndex, iTemp, index), charUnknownHigh, charUnknownLow, index);
}
public override char GetNextChar()
@@ -106,27 +102,27 @@ namespace System.Text
[Serializable]
public sealed class EncoderFallbackException : ArgumentException
{
- char charUnknown;
- char charUnknownHigh;
- char charUnknownLow;
- int index;
+ private char charUnknown;
+ private char charUnknownHigh;
+ private char charUnknownLow;
+ private int index;
public EncoderFallbackException()
- : base(Environment.GetResourceString("Arg_ArgumentException"))
+ : base(SR.Arg_ArgumentException)
{
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ HResult = __HResults.COR_E_ARGUMENT;
}
public EncoderFallbackException(String message)
: base(message)
{
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ HResult = __HResults.COR_E_ARGUMENT;
}
public EncoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
- SetErrorCode(__HResults.COR_E_ARGUMENT);
+ HResult = __HResults.COR_E_ARGUMENT;
}
internal EncoderFallbackException(SerializationInfo info, StreamingContext context) : base(info, context)
@@ -146,14 +142,12 @@ namespace System.Text
if (!Char.IsHighSurrogate(charUnknownHigh))
{
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xD800, 0xDBFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
}
if (!Char.IsLowSurrogate(charUnknownLow))
{
throw new ArgumentOutOfRangeException(nameof(CharUnknownLow),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xDC00, 0xDFFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
}
Contract.EndContractBlock();
@@ -197,7 +191,7 @@ namespace System.Text
// Return true if the unknown character is a surrogate pair.
public bool IsUnknownSurrogate()
{
- return (this.charUnknownHigh != '\0');
+ return (charUnknownHigh != '\0');
}
}
}
diff --git a/src/mscorlib/src/System/Text/EncoderFallback.cs b/src/mscorlib/src/System/Text/EncoderFallback.cs
index db2bf93bdd..410b6f5016 100644
--- a/src/mscorlib/src/System/Text/EncoderFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderFallback.cs
@@ -13,9 +13,9 @@ namespace System.Text
[Serializable]
public abstract class EncoderFallback
{
-// disable csharp compiler warning #0414: field assigned unused value
+ // disable csharp compiler warning #0414: field assigned unused value
#pragma warning disable 0414
- internal bool bIsMicrosoftBestFitFallback = false;
+ internal bool bIsMicrosoftBestFitFallback = false;
#pragma warning restore 0414
private static volatile EncoderFallback replacementFallback; // Default fallback, uses no best fit & "?"
@@ -43,7 +43,7 @@ namespace System.Text
get
{
if (replacementFallback == null)
- lock(InternalSyncObject)
+ lock (InternalSyncObject)
if (replacementFallback == null)
replacementFallback = new EncoderReplacementFallback();
@@ -57,7 +57,7 @@ namespace System.Text
get
{
if (exceptionFallback == null)
- lock(InternalSyncObject)
+ lock (InternalSyncObject)
if (exceptionFallback == null)
exceptionFallback = new EncoderExceptionFallback();
@@ -107,19 +107,19 @@ namespace System.Text
public virtual void Reset()
{
- while (GetNextChar() != (char)0);
+ while (GetNextChar() != (char)0) ;
}
// Internal items to help us figure out what we're doing as far as error messages, etc.
// These help us with our performance and messages internally
- internal unsafe char* charStart;
- internal unsafe char* charEnd;
- internal EncoderNLS encoder;
- internal bool setEncoder;
- internal bool bUsedEncoder;
- internal bool bFallingBack = false;
- internal int iRecursionCount = 0;
- private const int iMaxRecursion = 250;
+ internal unsafe char* charStart;
+ internal unsafe char* charEnd;
+ internal EncoderNLS encoder;
+ internal bool setEncoder;
+ internal bool bUsedEncoder;
+ internal bool bFallingBack = false;
+ internal int iRecursionCount = 0;
+ private const int iMaxRecursion = 250;
// Internal Reset
// For example, what if someone fails a conversion and wants to reset one of our fallback buffers?
@@ -224,9 +224,7 @@ namespace System.Text
{
// Throw it, using our complete character
throw new ArgumentException(
- Environment.GetResourceString("Argument_RecursiveFallback",
- charRecursive), "chars");
+ SR.Format(SR.Argument_RecursiveFallback, charRecursive), "chars");
}
-
}
}
diff --git a/src/mscorlib/src/System/Text/EncoderNLS.cs b/src/mscorlib/src/System/Text/EncoderNLS.cs
index 95901e01f4..99a26ca575 100644
--- a/src/mscorlib/src/System/Text/EncoderNLS.cs
+++ b/src/mscorlib/src/System/Text/EncoderNLS.cs
@@ -2,12 +2,13 @@
// 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;
+using System.Text;
+using System;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System.Runtime.Serialization;
- using System.Text;
- using System;
- using System.Diagnostics.Contracts;
// An Encoder is used to encode a sequence of blocks of characters into
// a sequence of blocks of bytes. Following instantiation of an encoder,
// sequential blocks of characters are converted into blocks of bytes through
@@ -24,23 +25,23 @@ namespace System.Text
internal class EncoderNLS : Encoder, ISerializable
{
// Need a place for the last left over character, most of our encodings use this
- internal char charLeftOver;
-
+ internal char charLeftOver;
+
protected Encoding m_encoding;
-
- [NonSerialized] protected bool m_mustFlush;
- [NonSerialized] internal bool m_throwOnOverflow;
- [NonSerialized] internal int m_charsUsed;
-#region Serialization
+ [NonSerialized] protected bool m_mustFlush;
+ [NonSerialized] internal bool m_throwOnOverflow;
+ [NonSerialized] internal int m_charsUsed;
+
+ #region Serialization
// Constructor called by serialization. called during deserialization.
internal EncoderNLS(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(
String.Format(
- System.Globalization.CultureInfo.CurrentCulture,
- Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType()));
+ System.Globalization.CultureInfo.CurrentCulture,
+ SR.NotSupported_TypeCannotDeserialized, this.GetType()));
}
// ISerializable implementation. called during serialization.
@@ -52,7 +53,7 @@ namespace System.Text
info.SetType(typeof(Encoding.DefaultEncoder));
}
-#endregion Serialization
+ #endregion Serialization
internal EncoderNLS(Encoding encoding)
{
@@ -80,15 +81,15 @@ namespace System.Text
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (index < 0 || count < 0)
- throw new ArgumentOutOfRangeException((index<0 ? nameof(index) : nameof(count)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - index < count)
throw new ArgumentOutOfRangeException(nameof(chars),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
// Avoid empty input problem
@@ -109,11 +110,11 @@ namespace System.Text
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
@@ -127,19 +128,19 @@ namespace System.Text
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
if (byteIndex < 0 || byteIndex > bytes.Length)
throw new ArgumentOutOfRangeException(nameof(byteIndex),
- Environment.GetResourceString("ArgumentOutOfRange_Index"));
+ SR.ArgumentOutOfRange_Index);
Contract.EndContractBlock();
if (chars.Length == 0)
@@ -151,11 +152,11 @@ namespace System.Text
// Just call pointer version
fixed (char* pChars = &chars[0])
- fixed (byte* pBytes = &bytes[0])
+ fixed (byte* pBytes = &bytes[0])
- // Remember that charCount is # to decode, not size of array.
- return GetBytes(pChars + charIndex, charCount,
- pBytes + byteIndex, byteCount, flush);
+ // Remember that charCount is # to decode, not size of array.
+ return GetBytes(pChars + charIndex, charCount,
+ pBytes + byteIndex, byteCount, flush);
}
public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
@@ -163,11 +164,11 @@ namespace System.Text
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
this.m_mustFlush = flush;
@@ -184,23 +185,23 @@ namespace System.Text
// Validate parameters
if (chars == null || bytes == null)
throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (charIndex < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((charIndex<0 ? nameof(charIndex) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (byteIndex < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((byteIndex<0 ? nameof(byteIndex) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (chars.Length - charIndex < charCount)
throw new ArgumentOutOfRangeException(nameof(chars),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
if (bytes.Length - byteIndex < byteCount)
throw new ArgumentOutOfRangeException(nameof(bytes),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
+ SR.ArgumentOutOfRange_IndexCountBuffer);
Contract.EndContractBlock();
@@ -230,10 +231,10 @@ namespace System.Text
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// We don't want to throw
@@ -283,6 +284,5 @@ namespace System.Text
{
m_mustFlush = false;
}
-
}
}
diff --git a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
index b0657ff18d..65b807c1bd 100644
--- a/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
+++ b/src/mscorlib/src/System/Text/EncoderReplacementFallback.cs
@@ -2,13 +2,13 @@
// 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;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System;
- using System.Runtime;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
[Serializable]
public sealed class EncoderReplacementFallback : EncoderFallback
{
@@ -28,11 +28,11 @@ namespace System.Text
Contract.EndContractBlock();
// Make sure it doesn't have bad surrogate pairs
- bool bFoundHigh=false;
+ bool bFoundHigh = false;
for (int i = 0; i < replacement.Length; i++)
{
// Found a surrogate?
- if (Char.IsSurrogate(replacement,i))
+ if (Char.IsSurrogate(replacement, i))
{
// High or Low?
if (Char.IsHighSurrogate(replacement, i))
@@ -61,17 +61,17 @@ namespace System.Text
break;
}
if (bFoundHigh)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex", nameof(replacement)));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, nameof(replacement)));
strDefault = replacement;
}
public String DefaultString
{
- get
- {
+ get
+ {
return strDefault;
- }
+ }
}
public override EncoderFallbackBuffer CreateFallbackBuffer()
@@ -93,7 +93,7 @@ namespace System.Text
EncoderReplacementFallback that = value as EncoderReplacementFallback;
if (that != null)
{
- return (this.strDefault == that.strDefault);
+ return (strDefault == that.strDefault);
}
return (false);
}
@@ -110,14 +110,14 @@ namespace System.Text
{
// Store our default string
private String strDefault;
- int fallbackCount = -1;
- int fallbackIndex = -1;
+ private int fallbackCount = -1;
+ private int fallbackIndex = -1;
// Construction
public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback)
{
// 2X in case we're a surrogate pair
- this.strDefault = fallback.DefaultString + fallback.DefaultString;
+ strDefault = fallback.DefaultString + fallback.DefaultString;
}
// Fallback Methods
@@ -129,8 +129,8 @@ namespace System.Text
{
// If we're recursive we may still have something in our buffer that makes this a surrogate
if (char.IsHighSurrogate(charUnknown) && fallbackCount >= 0 &&
- char.IsLowSurrogate(strDefault[fallbackIndex+1]))
- ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknown, strDefault[fallbackIndex+1]));
+ char.IsLowSurrogate(strDefault[fallbackIndex + 1]))
+ ThrowLastCharRecursive(Char.ConvertToUtf32(charUnknown, strDefault[fallbackIndex + 1]));
// Nope, just one character
ThrowLastCharRecursive(unchecked((int)charUnknown));
@@ -138,7 +138,7 @@ namespace System.Text
// Go ahead and get our fallback
// Divide by 2 because we aren't a surrogate pair
- fallbackCount = strDefault.Length/2;
+ fallbackCount = strDefault.Length / 2;
fallbackIndex = -1;
return fallbackCount != 0;
@@ -149,13 +149,11 @@ namespace System.Text
// Double check input surrogate pair
if (!Char.IsHighSurrogate(charUnknownHigh))
throw new ArgumentOutOfRangeException(nameof(charUnknownHigh),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xD800, 0xDBFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xD800, 0xDBFF));
if (!Char.IsLowSurrogate(charUnknownLow))
throw new ArgumentOutOfRangeException(nameof(charUnknownLow),
- Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0xDC00, 0xDFFF));
+ SR.Format(SR.ArgumentOutOfRange_Range, 0xDC00, 0xDFFF));
Contract.EndContractBlock();
// If we had a buffer already we're being recursive, throw, it's probably at the suspect
@@ -176,7 +174,7 @@ namespace System.Text
// and we need to detect recursion. We could have a flag but we already have this counter.
fallbackCount--;
fallbackIndex++;
-
+
// Do we have anything left? 0 is now last fallback char, negative is nothing left
if (fallbackCount < 0)
return '\0';
diff --git a/src/mscorlib/src/System/Text/Encoding.cs b/src/mscorlib/src/System/Text/Encoding.cs
index 8cb01e41fa..159123495b 100644
--- a/src/mscorlib/src/System/Text/Encoding.cs
+++ b/src/mscorlib/src/System/Text/Encoding.cs
@@ -85,79 +85,83 @@ namespace System.Text
[Serializable]
public abstract class Encoding : ICloneable
{
- private static Encoding defaultEncoding;
+ // For netcore we use UTF8 as default encoding since ANSI isn't available
+ private static readonly UTF8Encoding.UTF8EncodingSealed s_defaultEncoding = new UTF8Encoding.UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: false);
+
+ // Returns an encoding for the system's current ANSI code page.
+ public static Encoding Default => s_defaultEncoding;
//
// The following values are from mlang.idl. These values
// should be in sync with those in mlang.idl.
//
- internal const int MIMECONTF_MAILNEWS = 0x00000001;
- internal const int MIMECONTF_BROWSER = 0x00000002;
- internal const int MIMECONTF_SAVABLE_MAILNEWS = 0x00000100;
- internal const int MIMECONTF_SAVABLE_BROWSER = 0x00000200;
+ internal const int MIMECONTF_MAILNEWS = 0x00000001;
+ internal const int MIMECONTF_BROWSER = 0x00000002;
+ internal const int MIMECONTF_SAVABLE_MAILNEWS = 0x00000100;
+ internal const int MIMECONTF_SAVABLE_BROWSER = 0x00000200;
// Special Case Code Pages
- private const int CodePageDefault = 0;
- private const int CodePageNoOEM = 1; // OEM Code page not supported
- private const int CodePageNoMac = 2; // MAC code page not supported
- private const int CodePageNoThread = 3; // Thread code page not supported
- private const int CodePageNoSymbol = 42; // Symbol code page not supported
- private const int CodePageUnicode = 1200; // Unicode
- private const int CodePageBigEndian = 1201; // Big Endian Unicode
- private const int CodePageWindows1252 = 1252; // Windows 1252 code page
+ private const int CodePageDefault = 0;
+ private const int CodePageNoOEM = 1; // OEM Code page not supported
+ private const int CodePageNoMac = 2; // MAC code page not supported
+ private const int CodePageNoThread = 3; // Thread code page not supported
+ private const int CodePageNoSymbol = 42; // Symbol code page not supported
+ private const int CodePageUnicode = 1200; // Unicode
+ private const int CodePageBigEndian = 1201; // Big Endian Unicode
+ private const int CodePageWindows1252 = 1252; // Windows 1252 code page
// 20936 has same code page as 10008, so we'll special case it
private const int CodePageMacGB2312 = 10008;
- private const int CodePageGB2312 = 20936;
+ private const int CodePageGB2312 = 20936;
private const int CodePageMacKorean = 10003;
private const int CodePageDLLKorean = 20949;
// ISO 2022 Code Pages
- private const int ISO2022JP = 50220;
- private const int ISO2022JPESC = 50221;
- private const int ISO2022JPSISO = 50222;
- private const int ISOKorean = 50225;
- private const int ISOSimplifiedCN = 50227;
- private const int EUCJP = 51932;
- private const int ChineseHZ = 52936; // HZ has ~}~{~~ sequences
+ private const int ISO2022JP = 50220;
+ private const int ISO2022JPESC = 50221;
+ private const int ISO2022JPSISO = 50222;
+ private const int ISOKorean = 50225;
+ private const int ISOSimplifiedCN = 50227;
+ private const int EUCJP = 51932;
+ private const int ChineseHZ = 52936; // HZ has ~}~{~~ sequences
// 51936 is the same as 936
- private const int DuplicateEUCCN = 51936;
- private const int EUCCN = 936;
+ private const int DuplicateEUCCN = 51936;
+ private const int EUCCN = 936;
- private const int EUCKR = 51949;
+ private const int EUCKR = 51949;
// Latin 1 & ASCII Code Pages
- internal const int CodePageASCII = 20127; // ASCII
- internal const int ISO_8859_1 = 28591; // Latin1
+ internal const int CodePageASCII = 20127; // ASCII
+ internal const int ISO_8859_1 = 28591; // Latin1
// ISCII
- private const int ISCIIAssemese = 57006;
- private const int ISCIIBengali = 57003;
- private const int ISCIIDevanagari = 57002;
- private const int ISCIIGujarathi = 57010;
- private const int ISCIIKannada = 57008;
- private const int ISCIIMalayalam = 57009;
- private const int ISCIIOriya = 57007;
- private const int ISCIIPanjabi = 57011;
- private const int ISCIITamil = 57004;
- private const int ISCIITelugu = 57005;
+ private const int ISCIIAssemese = 57006;
+ private const int ISCIIBengali = 57003;
+ private const int ISCIIDevanagari = 57002;
+ private const int ISCIIGujarathi = 57010;
+ private const int ISCIIKannada = 57008;
+ private const int ISCIIMalayalam = 57009;
+ private const int ISCIIOriya = 57007;
+ private const int ISCIIPanjabi = 57011;
+ private const int ISCIITamil = 57004;
+ private const int ISCIITelugu = 57005;
// GB18030
- private const int GB18030 = 54936;
+ private const int GB18030 = 54936;
// Other
- private const int ISO_8859_8I = 38598;
+ private const int ISO_8859_8I = 38598;
private const int ISO_8859_8_Visual = 28598;
// 50229 is currently unsupported // "Chinese Traditional (ISO-2022)"
- private const int ENC50229 = 50229;
+ private const int ENC50229 = 50229;
// Special code pages
- private const int CodePageUTF7 = 65000;
- private const int CodePageUTF8 = 65001;
- private const int CodePageUTF32 = 12000;
- private const int CodePageUTF32BE = 12001;
+ private const int CodePageUTF7 = 65000;
+ private const int CodePageUTF8 = 65001;
+ private const int CodePageUTF32 = 12000;
+ private const int CodePageUTF32BE = 12001;
internal int m_codePage = 0;
@@ -228,13 +232,13 @@ namespace System.Text
}
-#region Serialization
+ #region Serialization
internal void OnDeserializing()
{
// intialize the optional Whidbey fields
encoderFallback = null;
decoderFallback = null;
- m_isReadOnly = true;
+ m_isReadOnly = true;
}
internal void OnDeserialized()
@@ -246,7 +250,7 @@ namespace System.Text
}
// dataItem is always recalculated from the code page #
- dataItem = null;
+ dataItem = null;
}
[OnDeserializing]
@@ -274,7 +278,7 @@ namespace System.Text
internal void DeserializeEncoding(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All versions have a code page
@@ -282,7 +286,7 @@ namespace System.Text
// We can get dataItem on the fly if needed, and the index is different between versions
// so ignore whatever dataItem data we get from Everett.
- this.dataItem = null;
+ this.dataItem = null;
// See if we have a code page
try
@@ -291,7 +295,7 @@ namespace System.Text
// Try Whidbey V2.0 Fields
//
- this.m_isReadOnly = (bool)info.GetValue("m_isReadOnly", typeof(bool));
+ m_isReadOnly = (bool)info.GetValue("m_isReadOnly", typeof(bool));
this.encoderFallback = (EncoderFallback)info.GetValue("encoderFallback", typeof(EncoderFallback));
this.decoderFallback = (DecoderFallback)info.GetValue("decoderFallback", typeof(DecoderFallback));
@@ -304,7 +308,7 @@ namespace System.Text
this.m_deserializedFromEverett = true;
// May as well be read only
- this.m_isReadOnly = true;
+ m_isReadOnly = true;
SetDefaultFallbacks();
}
}
@@ -313,11 +317,11 @@ namespace System.Text
internal void SerializeEncoding(SerializationInfo info, StreamingContext context)
{
// Any Info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// These are new V2.0 Whidbey stuff
- info.AddValue("m_isReadOnly", this.m_isReadOnly);
+ info.AddValue("m_isReadOnly", m_isReadOnly);
info.AddValue("encoderFallback", this.EncoderFallback);
info.AddValue("decoderFallback", this.DecoderFallback);
@@ -332,7 +336,7 @@ namespace System.Text
info.AddValue("Encoding+dataItem", null);
}
-#endregion Serialization
+ #endregion Serialization
// Converts a byte array from one encoding to another. The bytes in the
// bytes array are converted from srcEncoding to
@@ -341,11 +345,12 @@ namespace System.Text
//
[Pure]
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding,
- byte[] bytes) {
- if (bytes==null)
+ byte[] bytes)
+ {
+ if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
Contract.Ensures(Contract.Result<byte[]>() != null);
-
+
return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length);
}
@@ -356,22 +361,25 @@ namespace System.Text
//
[Pure]
public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding,
- byte[] bytes, int index, int count) {
- if (srcEncoding == null || dstEncoding == null) {
+ byte[] bytes, int index, int count)
+ {
+ if (srcEncoding == null || dstEncoding == null)
+ {
throw new ArgumentNullException((srcEncoding == null ? nameof(srcEncoding) : nameof(dstEncoding)),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
}
- if (bytes == null) {
+ if (bytes == null)
+ {
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
}
Contract.Ensures(Contract.Result<byte[]>() != null);
-
+
return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count));
}
- public static void RegisterProvider(EncodingProvider provider)
+ public static void RegisterProvider(EncodingProvider provider)
{
// Parameters validated inside EncodingProvider
EncodingProvider.AddProvider(provider);
@@ -390,10 +398,10 @@ namespace System.Text
// Otherwise, the code below will throw exception when trying to call
// EncodingTable.GetDataItem().
//
- if (codepage < 0 || codepage > 65535) {
+ if (codepage < 0 || codepage > 65535)
+ {
throw new ArgumentOutOfRangeException(
- nameof(codepage), Environment.GetResourceString("ArgumentOutOfRange_Range",
- 0, 65535));
+ nameof(codepage), SR.Format(SR.ArgumentOutOfRange_Range, 0, 65535));
}
Contract.EndContractBlock();
@@ -418,15 +426,14 @@ namespace System.Text
case CodePageNoMac: // 2 CP_MACCP
case CodePageNoThread: // 3 CP_THREAD_ACP
case CodePageNoSymbol: // 42 CP_SYMBOL
- throw new ArgumentException(Environment.GetResourceString(
- "Argument_CodepageNotSupported", codepage), nameof(codepage));
+ throw new ArgumentException(SR.Format(SR.Argument_CodepageNotSupported, codepage), nameof(codepage));
}
// Is it a valid code page?
if (EncodingTable.GetCodePageDataItem(codepage) == null)
{
throw new NotSupportedException(
- Environment.GetResourceString("NotSupported_NoCodepageData", codepage));
+ SR.Format(SR.NotSupported_NoCodepageData, codepage));
}
return UTF8;
@@ -498,15 +505,18 @@ namespace System.Text
[Pure]
public virtual byte[] GetPreamble()
{
- return EmptyArray<Byte>.Value;
+ return Array.Empty<Byte>();
}
- private void GetDataItem() {
- if (dataItem==null) {
+ private void GetDataItem()
+ {
+ if (dataItem == null)
+ {
dataItem = EncodingTable.GetCodePageDataItem(m_codePage);
- if(dataItem==null) {
+ if (dataItem == null)
+ {
throw new NotSupportedException(
- Environment.GetResourceString("NotSupported_NoCodepageData", m_codePage));
+ SR.Format(SR.NotSupported_NoCodepageData, m_codePage));
}
}
}
@@ -518,7 +528,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.BodyName);
@@ -531,7 +542,7 @@ namespace System.Text
{
get
{
- return Environment.GetResourceString("Globalization.cp_" + m_codePage.ToString());
+ return SR.GetResourceString("Globalization_cp_" + m_codePage.ToString());
}
}
@@ -542,7 +553,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.HeaderName);
@@ -556,7 +568,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.WebName);
@@ -569,7 +582,8 @@ namespace System.Text
{
get
{
- if (dataItem==null) {
+ if (dataItem == null)
+ {
GetDataItem();
}
return (dataItem.UIFamilyCodePage);
@@ -579,9 +593,12 @@ namespace System.Text
// True if and only if the encoding is used for display by browsers clients.
- public virtual bool IsBrowserDisplay {
- get {
- if (dataItem==null) {
+ public virtual bool IsBrowserDisplay
+ {
+ get
+ {
+ if (dataItem == null)
+ {
GetDataItem();
}
return ((dataItem.Flags & MIMECONTF_BROWSER) != 0);
@@ -590,9 +607,12 @@ namespace System.Text
// True if and only if the encoding is used for saving by browsers clients.
- public virtual bool IsBrowserSave {
- get {
- if (dataItem==null) {
+ public virtual bool IsBrowserSave
+ {
+ get
+ {
+ if (dataItem == null)
+ {
GetDataItem();
}
return ((dataItem.Flags & MIMECONTF_SAVABLE_BROWSER) != 0);
@@ -601,9 +621,12 @@ namespace System.Text
// True if and only if the encoding is used for display by mail and news clients.
- public virtual bool IsMailNewsDisplay {
- get {
- if (dataItem==null) {
+ public virtual bool IsMailNewsDisplay
+ {
+ get
+ {
+ if (dataItem == null)
+ {
GetDataItem();
}
return ((dataItem.Flags & MIMECONTF_MAILNEWS) != 0);
@@ -614,9 +637,12 @@ namespace System.Text
// True if and only if the encoding is used for saving documents by mail and
// news clients
- public virtual bool IsMailNewsSave {
- get {
- if (dataItem==null) {
+ public virtual bool IsMailNewsSave
+ {
+ get
+ {
+ if (dataItem == null)
+ {
GetDataItem();
}
return ((dataItem.Flags & MIMECONTF_SAVABLE_MAILNEWS) != 0);
@@ -644,7 +670,7 @@ namespace System.Text
set
{
if (this.IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
if (value == null)
throw new ArgumentNullException(nameof(value));
@@ -665,7 +691,7 @@ namespace System.Text
set
{
if (this.IsReadOnly)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
+ throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
if (value == null)
throw new ArgumentNullException(nameof(value));
@@ -715,7 +741,7 @@ namespace System.Text
if (chars == null)
{
throw new ArgumentNullException(nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
}
Contract.EndContractBlock();
@@ -731,7 +757,6 @@ namespace System.Text
char[] chars = s.ToCharArray();
return GetByteCount(chars, 0, chars.Length);
-
}
// Returns the number of bytes required to encode a range of characters in
@@ -746,17 +771,17 @@ namespace System.Text
public int GetByteCount(string s, int index, int count)
{
if (s == null)
- throw new ArgumentNullException(nameof(s),
- Environment.GetResourceString("ArgumentNull_String"));
+ throw new ArgumentNullException(nameof(s),
+ SR.ArgumentNull_String);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (index > s.Length - count)
throw new ArgumentOutOfRangeException(nameof(index),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ SR.ArgumentOutOfRange_IndexCount);
Contract.EndContractBlock();
unsafe
@@ -779,11 +804,11 @@ namespace System.Text
// Validate input parameters
if (chars == null)
throw new ArgumentNullException(nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
char[] arrChar = new char[count];
@@ -814,7 +839,7 @@ namespace System.Text
if (chars == null)
{
throw new ArgumentNullException(nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
}
Contract.EndContractBlock();
return GetBytes(chars, 0, chars.Length);
@@ -851,7 +876,7 @@ namespace System.Text
{
if (s == null)
throw new ArgumentNullException(nameof(s),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
Contract.EndContractBlock();
int byteCount = GetByteCount(s);
@@ -869,16 +894,16 @@ namespace System.Text
{
if (s == null)
throw new ArgumentNullException(nameof(s),
- Environment.GetResourceString("ArgumentNull_String"));
+ SR.ArgumentNull_String);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
if (index > s.Length - count)
throw new ArgumentOutOfRangeException(nameof(index),
- Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
+ SR.ArgumentOutOfRange_IndexCount);
Contract.EndContractBlock();
unsafe
@@ -941,11 +966,11 @@ namespace System.Text
// Validate input parameters
if (bytes == null || chars == null)
throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (charCount < 0 || byteCount < 0)
- throw new ArgumentOutOfRangeException((charCount<0 ? nameof(charCount) : nameof(byteCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Get the char array to convert
@@ -987,7 +1012,7 @@ namespace System.Text
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
}
Contract.EndContractBlock();
return GetCharCount(bytes, 0, bytes.Length);
@@ -1008,11 +1033,11 @@ namespace System.Text
// Validate input parameters
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
byte[] arrbyte = new byte[count];
@@ -1040,7 +1065,7 @@ namespace System.Text
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
}
Contract.EndContractBlock();
return GetChars(bytes, 0, bytes.Length);
@@ -1095,11 +1120,11 @@ namespace System.Text
// Validate input parameters
if (chars == null || bytes == null)
throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
if (byteCount < 0 || charCount < 0)
- throw new ArgumentOutOfRangeException((byteCount<0 ? nameof(byteCount) : nameof(charCount)),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Get the byte array to convert
@@ -1146,10 +1171,10 @@ namespace System.Text
public unsafe string GetString(byte* bytes, int byteCount)
{
if (bytes == null)
- throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
+ throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array);
if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
return String.CreateStringFromEncoding(bytes, byteCount, this);
@@ -1202,26 +1227,6 @@ namespace System.Text
return new DefaultDecoder(this);
}
- private static Encoding CreateDefaultEncoding()
- {
- // defaultEncoding should be null if we get here, but we can't
- // assert that in case another thread beat us to the initialization
-
- Encoding enc;
-
-
- // For silverlight we use UTF8 since ANSI isn't available
- enc = UTF8;
-
-
- // This method should only ever return one Encoding instance
- return Interlocked.CompareExchange(ref defaultEncoding, enc, null) ?? enc;
- }
-
- // Returns an encoding for the system's current ANSI code page.
-
- public static Encoding Default => defaultEncoding ?? CreateDefaultEncoding();
-
// Returns an Encoder object for this encoding. The returned object
// can be used to encode a sequence of characters into a sequence of bytes.
// Contrary to the GetBytes family of methods, an Encoder can
@@ -1274,7 +1279,7 @@ namespace System.Text
{
if (bytes == null)
throw new ArgumentNullException(nameof(bytes),
- Environment.GetResourceString("ArgumentNull_Array"));
+ SR.ArgumentNull_Array);
Contract.EndContractBlock();
return GetString(bytes, 0, bytes.Length);
@@ -1311,7 +1316,7 @@ namespace System.Text
// an instance of the UTF7Encoding class.
public static Encoding UTF7 => UTF7Encoding.s_default;
-
+
// Returns an encoding for the UTF-8 format. The returned encoding will be
// an instance of the UTF8Encoding class.
@@ -1329,7 +1334,8 @@ namespace System.Text
private static Encoding BigEndianUTF32 => UTF32Encoding.s_bigEndianDefault;
- public override bool Equals(Object value) {
+ public override bool Equals(Object value)
+ {
Encoding that = value as Encoding;
if (that != null)
return (m_codePage == that.m_codePage) &&
@@ -1339,20 +1345,21 @@ namespace System.Text
}
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return m_codePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
}
internal virtual char[] GetBestFitUnicodeToBytesData()
{
// Normally we don't have any best fit data.
- return EmptyArray<Char>.Value;
+ return Array.Empty<Char>();
}
internal virtual char[] GetBestFitBytesToUnicodeData()
{
// Normally we don't have any best fit data.
- return EmptyArray<Char>.Value;
+ return Array.Empty<Char>();
}
internal void ThrowBytesOverflow()
@@ -1360,8 +1367,7 @@ namespace System.Text
// Special message to include fallback type in case fallback's GetMaxCharCount is broken
// This happens if user has implimented an encoder fallback with a broken GetMaxCharCount
throw new ArgumentException(
- Environment.GetResourceString("Argument_EncodingConversionOverflowBytes",
- EncodingName, EncoderFallback.GetType()), "bytes");
+ SR.Format(SR.Argument_EncodingConversionOverflowBytes, EncodingName, EncoderFallback.GetType()), "bytes");
}
internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded)
@@ -1384,8 +1390,7 @@ namespace System.Text
// Special message to include fallback type in case fallback's GetMaxCharCount is broken
// This happens if user has implimented a decoder fallback with a broken GetMaxCharCount
throw new ArgumentException(
- Environment.GetResourceString("Argument_EncodingConversionOverflowChars",
- EncodingName, DecoderFallback.GetType()), "chars");
+ SR.Format(SR.Argument_EncodingConversionOverflowChars, EncodingName, DecoderFallback.GetType()), "chars");
}
internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded)
@@ -1405,7 +1410,7 @@ namespace System.Text
}
[Serializable]
- internal class DefaultEncoder : Encoder, IObjectReference, ISerializable
+ internal sealed class DefaultEncoder : Encoder, IObjectReference, ISerializable
{
private Encoding m_encoding;
[NonSerialized] private bool m_hasInitializedEncoding;
@@ -1421,16 +1426,16 @@ namespace System.Text
// Constructor called by serialization, have to handle deserializing from Everett
internal DefaultEncoder(SerializationInfo info, StreamingContext context)
{
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
+ m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
- try
+ try
{
- this.m_fallback = (EncoderFallback) info.GetValue("m_fallback", typeof(EncoderFallback));
- this.charLeftOver = (Char) info.GetValue("charLeftOver", typeof(Char));
+ this.m_fallback = (EncoderFallback)info.GetValue("m_fallback", typeof(EncoderFallback));
+ this.charLeftOver = (Char)info.GetValue("charLeftOver", typeof(Char));
}
catch (SerializationException)
{
@@ -1453,7 +1458,7 @@ namespace System.Text
Encoder encoder = m_encoding.GetEncoder();
if (m_fallback != null)
encoder.m_fallback = m_fallback;
- if (charLeftOver != (char) 0)
+ if (charLeftOver != (char)0)
{
EncoderNLS encoderNls = encoder as EncoderNLS;
if (encoderNls != null)
@@ -1466,11 +1471,11 @@ namespace System.Text
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
- info.AddValue("encoding", this.m_encoding);
+ info.AddValue("encoding", m_encoding);
}
// Returns the number of bytes the next call to GetBytes will
@@ -1527,7 +1532,7 @@ namespace System.Text
}
[Serializable]
- internal class DefaultDecoder : Decoder, IObjectReference, ISerializable
+ internal sealed class DefaultDecoder : Decoder, IObjectReference, ISerializable
{
private Encoding m_encoding;
[NonSerialized]
@@ -1537,21 +1542,21 @@ namespace System.Text
{
m_encoding = encoding;
m_hasInitializedEncoding = true;
- }
+ }
// Constructor called by serialization, have to handle deserializing from Everett
internal DefaultDecoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- try
+ m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
+
+ try
{
- this.m_fallback = (DecoderFallback) info.GetValue("m_fallback", typeof(DecoderFallback));
+ this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
}
catch (SerializationException)
{
@@ -1583,11 +1588,11 @@ namespace System.Text
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// All we have is our encoding
- info.AddValue("encoding", this.m_encoding);
+ info.AddValue("encoding", m_encoding);
}
// Returns the number of characters the next call to GetChars will
@@ -1654,16 +1659,16 @@ namespace System.Text
internal class EncodingCharBuffer
{
- unsafe char* chars;
- unsafe char* charStart;
- unsafe char* charEnd;
- int charCountResult = 0;
- Encoding enc;
- DecoderNLS decoder;
- unsafe byte* byteStart;
- unsafe byte* byteEnd;
- unsafe byte* bytes;
- DecoderFallbackBuffer fallbackBuffer;
+ private unsafe char* chars;
+ private unsafe char* charStart;
+ private unsafe char* charEnd;
+ private int charCountResult = 0;
+ private Encoding enc;
+ private DecoderNLS decoder;
+ private unsafe byte* byteStart;
+ private unsafe byte* byteEnd;
+ private unsafe byte* bytes;
+ private DecoderFallbackBuffer fallbackBuffer;
internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount,
byte* byteStart, int byteCount)
@@ -1671,18 +1676,18 @@ namespace System.Text
this.enc = enc;
this.decoder = decoder;
- this.chars = charStart;
+ chars = charStart;
this.charStart = charStart;
- this.charEnd = charStart + charCount;
+ charEnd = charStart + charCount;
this.byteStart = byteStart;
- this.bytes = byteStart;
- this.byteEnd = byteStart + byteCount;
+ bytes = byteStart;
+ byteEnd = byteStart + byteCount;
if (this.decoder == null)
- this.fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer();
+ fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer();
else
- this.fallbackBuffer = this.decoder.FallbackBuffer;
+ fallbackBuffer = this.decoder.FallbackBuffer;
// If we're getting chars or getting char count we don't expect to have
// to remember fallbacks between calls (so it should be empty)
@@ -1698,7 +1703,7 @@ namespace System.Text
if (chars >= charEnd)
{
// Throw maybe
- bytes-=numBytes; // Didn't encode these bytes
+ bytes -= numBytes; // Didn't encode these bytes
enc.ThrowCharsOverflow(decoder, bytes <= byteStart); // Throw?
return false; // No throw, but no store either
}
@@ -1711,7 +1716,7 @@ namespace System.Text
internal unsafe bool AddChar(char ch)
{
- return AddChar(ch,1);
+ return AddChar(ch, 1);
}
internal unsafe void AdjustBytes(int count)
@@ -1789,41 +1794,40 @@ namespace System.Text
internal class EncodingByteBuffer
{
- unsafe byte* bytes;
- unsafe byte* byteStart;
- unsafe byte* byteEnd;
- unsafe char* chars;
- unsafe char* charStart;
- unsafe char* charEnd;
- int byteCountResult = 0;
- Encoding enc;
- EncoderNLS encoder;
+ private unsafe byte* bytes;
+ private unsafe byte* byteStart;
+ private unsafe byte* byteEnd;
+ private unsafe char* chars;
+ private unsafe char* charStart;
+ private unsafe char* charEnd;
+ private int byteCountResult = 0;
+ private Encoding enc;
+ private EncoderNLS encoder;
internal EncoderFallbackBuffer fallbackBuffer;
internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder,
byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount)
{
- this.enc = inEncoding;
- this.encoder = inEncoder;
+ enc = inEncoding;
+ encoder = inEncoder;
- this.charStart = inCharStart;
- this.chars = inCharStart;
- this.charEnd = inCharStart + inCharCount;
+ charStart = inCharStart;
+ chars = inCharStart;
+ charEnd = inCharStart + inCharCount;
- this.bytes = inByteStart;
- this.byteStart = inByteStart;
- this.byteEnd = inByteStart + inByteCount;
+ bytes = inByteStart;
+ byteStart = inByteStart;
+ byteEnd = inByteStart + inByteCount;
- if (this.encoder == null)
+ if (encoder == null)
this.fallbackBuffer = enc.EncoderFallback.CreateFallbackBuffer();
else
{
- this.fallbackBuffer = this.encoder.FallbackBuffer;
+ this.fallbackBuffer = encoder.FallbackBuffer;
// If we're not converting we must not have data in our fallback buffer
if (encoder.m_throwOnOverflow && encoder.InternalHasFallbackBuffer &&
this.fallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- encoder.Encoding.EncodingName, encoder.Fallback.GetType()));
+ throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, encoder.Encoding.EncodingName, encoder.Fallback.GetType()));
}
fallbackBuffer.InternalInitialize(chars, charEnd, encoder, bytes != null);
}
@@ -1867,8 +1871,8 @@ namespace System.Text
fallbackBuffer.MovePrevious(); // don't use last fallback
else
{
- Debug.Assert(chars > charStart ||
- ((bThrow == true) && (bytes == byteStart)),
+ Debug.Assert(chars > charStart ||
+ ((bThrow == true) && (bytes == byteStart)),
"[EncodingByteBuffer.MovePrevious]expected previous data or throw");
if (chars > charStart)
chars--; // don't use last char
@@ -1889,7 +1893,7 @@ namespace System.Text
internal unsafe char GetNextChar()
{
- // See if there's something in our fallback buffer
+ // See if there's something in our fallback buffer
char cReturn = fallbackBuffer.InternalGetNextChar();
// Nothing in the fallback buffer, return our normal data.
@@ -1898,9 +1902,9 @@ namespace System.Text
if (chars < charEnd)
cReturn = *(chars++);
}
-
+
return cReturn;
- }
+ }
internal unsafe int CharsUsed
{
diff --git a/src/mscorlib/src/System/Text/EncodingForwarder.cs b/src/mscorlib/src/System/Text/EncodingForwarder.cs
deleted file mode 100644
index 50ccbd9333..0000000000
--- a/src/mscorlib/src/System/Text/EncodingForwarder.cs
+++ /dev/null
@@ -1,329 +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.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Security;
-
-namespace System.Text
-{
- // Shared implementations for commonly overriden Encoding methods
-
- internal static class EncodingForwarder
- {
- // We normally have to duplicate a lot of code between UTF8Encoding,
- // UTF7Encoding, EncodingNLS, etc. because we want to override many
- // of the methods in all of those classes to just forward to the unsafe
- // version. (e.g. GetBytes(char[]))
- // Ideally, everything would just derive from EncodingNLS, but that's
- // not exposed in the public API, and C# prohibits a public class from
- // inheriting from an internal one. So, we have to override each of the
- // methods in question and repeat the argument validation/logic.
-
- // These set of methods exist so instead of duplicating code, we can
- // simply have those overriden methods call here to do the actual work.
-
- // NOTE: This class should ONLY be called from Encodings that override
- // the internal methods which accept an Encoder/DecoderNLS. The reason
- // for this is that by default, those methods just call the same overload
- // except without the encoder/decoder parameter. If an overriden method
- // without that parameter calls this class, which calls the overload with
- // the parameter, it will call the same method again, which will eventually
- // lead to a StackOverflowException.
-
- public unsafe static int GetByteCount(Encoding encoding, char[] chars, int index, int count)
- {
- // Validate parameters
-
- Debug.Assert(encoding != null); // this parameter should only be affected internally, so just do a debug check here
- if (chars == null)
- {
- throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (index < 0 || count < 0)
- {
- throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- if (chars.Length - index < count)
- {
- throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- }
- Contract.EndContractBlock();
-
- // If no input, return 0, avoid fixed empty array problem
- if (count == 0)
- return 0;
-
- // Just call the (internal) pointer version
- fixed (char* pChars = chars)
- return encoding.GetByteCount(pChars + index, count, encoder: null);
- }
-
- public unsafe static int GetByteCount(Encoding encoding, string s)
- {
- Debug.Assert(encoding != null);
- if (s == null)
- {
- string paramName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the string chars
- // UTF8Encoding does this as well, but it originally threw an ArgumentNull for "s" so don't check for that
- throw new ArgumentNullException(paramName);
- }
- Contract.EndContractBlock();
-
- // NOTE: The behavior of fixed *is* defined by
- // the spec for empty strings, although not for
- // null strings/empty char arrays. See
- // http://stackoverflow.com/q/37757751/4077294
- // Regardless, we may still want to check
- // for if (s.Length == 0) in the future
- // and short-circuit as an optimization (TODO).
-
- fixed (char* pChars = s)
- return encoding.GetByteCount(pChars, s.Length, encoder: null);
- }
-
- public unsafe static int GetByteCount(Encoding encoding, char* chars, int count)
- {
- Debug.Assert(encoding != null);
- if (chars == null)
- {
- throw new ArgumentNullException(nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- // Call the internal version, with an empty encoder
- return encoding.GetByteCount(chars, count, encoder: null);
- }
-
- public unsafe static int GetBytes(Encoding encoding, string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
- {
- Debug.Assert(encoding != null);
- if (s == null || bytes == null)
- {
- string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
- throw new ArgumentNullException(s == null ? stringName : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (charIndex < 0 || charCount < 0)
- {
- throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- if (s.Length - charIndex < charCount)
- {
- string stringName = encoding is ASCIIEncoding ? "chars" : nameof(s); // ASCIIEncoding calls the first parameter chars
- // Duplicate the above check since we don't want the overhead of a type check on the general path
- throw new ArgumentOutOfRangeException(stringName, Environment.GetResourceString("ArgumentOutOfRange_IndexCount"));
- }
- if (byteIndex < 0 || byteIndex > bytes.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.EndContractBlock();
-
- int byteCount = bytes.Length - byteIndex;
-
- // Fixed doesn't like empty arrays
- if (bytes.Length == 0)
- bytes = new byte[1];
-
- fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0])
- {
- return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null);
- }
- }
-
- public unsafe static int GetBytes(Encoding encoding, char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
- {
- Debug.Assert(encoding != null);
- if (chars == null || bytes == null)
- {
- throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (charIndex < 0 || charCount < 0)
- {
- throw new ArgumentOutOfRangeException(charIndex < 0 ? nameof(charIndex) : nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- if (chars.Length - charIndex < charCount)
- {
- throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- }
- if (byteIndex < 0 || byteIndex > bytes.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(byteIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.EndContractBlock();
-
- // If nothing to encode return 0, avoid fixed problem
- if (charCount == 0)
- return 0;
-
- // Note that this is the # of bytes to decode,
- // not the size of the array
- int byteCount = bytes.Length - byteIndex;
-
- // Fixed doesn't like 0 length arrays.
- if (bytes.Length == 0)
- bytes = new byte[1];
-
- // Just call the (internal) pointer version
- fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0])
- {
- return encoding.GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, encoder: null);
- }
- }
-
- public unsafe static int GetBytes(Encoding encoding, char* chars, int charCount, byte* bytes, int byteCount)
- {
- Debug.Assert(encoding != null);
- if (bytes == null || chars == null)
- {
- throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (charCount < 0 || byteCount < 0)
- {
- throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- return encoding.GetBytes(chars, charCount, bytes, byteCount, encoder: null);
- }
-
- public unsafe static int GetCharCount(Encoding encoding, byte[] bytes, int index, int count)
- {
- Debug.Assert(encoding != null);
- if (bytes == null)
- {
- throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (index < 0 || count < 0)
- {
- throw new ArgumentOutOfRangeException(index < 0 ? nameof(index) : nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- if (bytes.Length - index < count)
- {
- throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- }
- Contract.EndContractBlock();
-
- // If no input just return 0, fixed doesn't like 0 length arrays.
- if (count == 0)
- return 0;
-
- // Just call pointer version
- fixed (byte* pBytes = bytes)
- return encoding.GetCharCount(pBytes + index, count, decoder: null);
- }
-
- public unsafe static int GetCharCount(Encoding encoding, byte* bytes, int count)
- {
- Debug.Assert(encoding != null);
- if (bytes == null)
- {
- throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- return encoding.GetCharCount(bytes, count, decoder: null);
- }
-
- public unsafe static int GetChars(Encoding encoding, byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
- {
- Debug.Assert(encoding != null);
- if (bytes == null || chars == null)
- {
- throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (byteIndex < 0 || byteCount < 0)
- {
- throw new ArgumentOutOfRangeException(byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- if (bytes.Length - byteIndex < byteCount)
- {
- throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- }
- if (charIndex < 0 || charIndex > chars.Length)
- {
- throw new ArgumentOutOfRangeException(nameof(charIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.EndContractBlock();
-
- if (byteCount == 0)
- return 0;
-
- // NOTE: This is the # of chars we can decode,
- // not the size of the array
- int charCount = chars.Length - charIndex;
-
- // Fixed doesn't like 0 length arrays.
- if (chars.Length == 0)
- chars = new char[1];
-
- fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0])
- {
- return encoding.GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, decoder: null);
- }
- }
-
- public unsafe static int GetChars(Encoding encoding, byte* bytes, int byteCount, char* chars, int charCount)
- {
- Debug.Assert(encoding != null);
- if (bytes == null || chars == null)
- {
- throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (charCount < 0 || byteCount < 0)
- {
- throw new ArgumentOutOfRangeException(charCount < 0 ? nameof(charCount) : nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.EndContractBlock();
-
- return encoding.GetChars(bytes, byteCount, chars, charCount, decoder: null);
- }
-
- public unsafe static string GetString(Encoding encoding, byte[] bytes, int index, int count)
- {
- Debug.Assert(encoding != null);
- if (bytes == null)
- {
- throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array"));
- }
- if (index < 0 || count < 0)
- {
- // ASCIIEncoding has different names for its parameters here (byteIndex, byteCount)
- bool ascii = encoding is ASCIIEncoding;
- string indexName = ascii ? "byteIndex" : nameof(index);
- string countName = ascii ? "byteCount" : nameof(count);
- throw new ArgumentOutOfRangeException(index < 0 ? indexName : countName, Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- if (bytes.Length - index < count)
- {
- throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer"));
- }
- Contract.EndContractBlock();
-
- // Avoid problems with empty input buffer
- if (count == 0)
- return string.Empty;
-
- // Call string.CreateStringFromEncoding here, which
- // allocates a string and lets the Encoding modify
- // it in place. This way, we don't have to allocate
- // an intermediary char[] to decode into and then
- // call the string constructor; instead we decode
- // directly into the string.
-
- fixed (byte* pBytes = bytes)
- {
- return string.CreateStringFromEncoding(pBytes + index, count, encoding);
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/EncodingInfo.cs b/src/mscorlib/src/System/Text/EncodingInfo.cs
deleted file mode 100644
index 26ad3344c6..0000000000
--- a/src/mscorlib/src/System/Text/EncodingInfo.cs
+++ /dev/null
@@ -1,74 +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.
-
-namespace System.Text
-{
- using System;
- using System.Text;
-
-
- [Serializable]
- public sealed class EncodingInfo
- {
- int iCodePage; // Code Page #
- String strEncodingName; // Short name (web name)
- String strDisplayName; // Full localized name
-
- internal EncodingInfo(int codePage, string name, string displayName)
- {
- this.iCodePage = codePage;
- this.strEncodingName = name;
- this.strDisplayName = displayName;
- }
-
-
- public int CodePage
- {
- get
- {
- return iCodePage;
- }
- }
-
-
- public String Name
- {
- get
- {
- return strEncodingName;
- }
- }
-
-
- public String DisplayName
- {
- get
- {
- return strDisplayName;
- }
- }
-
-
- public Encoding GetEncoding()
- {
- return Encoding.GetEncoding(this.iCodePage);
- }
-
- public override bool Equals(Object value)
- {
- EncodingInfo that = value as EncodingInfo;
- if (that != null)
- {
- return (this.CodePage == that.CodePage);
- }
- return (false);
- }
-
- public override int GetHashCode()
- {
- return this.CodePage;
- }
-
- }
-}
diff --git a/src/mscorlib/src/System/Text/EncodingNLS.cs b/src/mscorlib/src/System/Text/EncodingNLS.cs
deleted file mode 100644
index cb6ed8a52c..0000000000
--- a/src/mscorlib/src/System/Text/EncodingNLS.cs
+++ /dev/null
@@ -1,125 +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.
-
-namespace System.Text
-{
-
- using System;
- using System.Diagnostics.Contracts;
- using System.Collections;
- using System.Runtime.Remoting;
- using System.Globalization;
- using System.Threading;
- using Win32Native = Microsoft.Win32.Win32Native;
-
- // This class overrides Encoding with the things we need for our NLS Encodings
-
- [Serializable]
- internal abstract class EncodingNLS : Encoding
- {
- protected EncodingNLS(int codePage) : base(codePage)
- {
- }
-
- // NOTE: Many methods in this class forward to EncodingForwarder for
- // validating arguments/wrapping the unsafe methods in this class
- // which do the actual work. That class contains
- // shared logic for doing this which is used by
- // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
- // UTF7Encoding, and UTF8Encoding.
- // The reason the code is separated out into a static class, rather
- // than a base class which overrides all of these methods for us
- // (which is what EncodingNLS is for internal Encodings) is because
- // that's really more of an implementation detail so it's internal.
- // At the same time, C# doesn't allow a public class subclassing an
- // internal/private one, so we end up having to re-override these
- // methods in all of the public Encodings + EncodingNLS.
-
- // Returns the number of bytes required to encode a range of characters in
- // a character array.
-
- public override int GetByteCount(char[] chars, int index, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, index, count);
- }
-
- public override int GetByteCount(String s)
- {
- return EncodingForwarder.GetByteCount(this, s);
- }
-
- public override unsafe int GetByteCount(char* chars, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, count);
- }
-
- public override int GetBytes(String s, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
- }
-
- // Encodes a range of characters in a character array into a range of bytes
- // in a byte array. An exception occurs if the byte array is not large
- // enough to hold the complete encoding of the characters. The
- // GetByteCount method can be used to determine the exact number of
- // bytes that will be produced for a given range of characters.
- // Alternatively, the GetMaxByteCount method can be used to
- // determine the maximum number of bytes that will be produced for a given
- // number of characters, regardless of the actual character values.
-
- public override int GetBytes(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
- }
-
- public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
- {
- return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
- }
-
- // Returns the number of characters produced by decoding a range of bytes
- // in a byte array.
-
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, index, count);
- }
-
- public override unsafe int GetCharCount(byte* bytes, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, count);
- }
-
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex)
- {
- return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
- }
-
- public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
- {
- return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
- }
-
- // Returns a string containing the decoded representation of a range of
- // bytes in a byte array.
-
- public override String GetString(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetString(this, bytes, index, count);
- }
-
- public override Decoder GetDecoder()
- {
- return new DecoderNLS(this);
- }
-
- public override Encoder GetEncoder()
- {
- return new EncoderNLS(this);
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/EncodingProvider.cs b/src/mscorlib/src/System/Text/EncodingProvider.cs
deleted file mode 100644
index 734d1ac761..0000000000
--- a/src/mscorlib/src/System/Text/EncodingProvider.cs
+++ /dev/null
@@ -1,136 +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.
-
-namespace System.Text
-{
- using System;
- using System.Collections;
- using System.Collections.Generic;
-
- public abstract class EncodingProvider
- {
- public EncodingProvider() { }
- public abstract Encoding GetEncoding(string name);
- public abstract Encoding GetEncoding(int codepage);
-
- // GetEncoding should return either valid encoding or null. shouldn't throw any exception except on null name
- public virtual Encoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
- {
- Encoding enc = GetEncoding(name);
- if (enc != null)
- {
- enc = (Encoding)GetEncoding(name).Clone();
- enc.EncoderFallback = encoderFallback;
- enc.DecoderFallback = decoderFallback;
- }
-
- return enc;
- }
-
- public virtual Encoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback)
- {
- Encoding enc = GetEncoding(codepage);
- if (enc != null)
- {
- enc = (Encoding)GetEncoding(codepage).Clone();
- enc.EncoderFallback = encoderFallback;
- enc.DecoderFallback = decoderFallback;
- }
-
- return enc;
- }
-
- internal static void AddProvider(EncodingProvider provider)
- {
- if (provider == null)
- throw new ArgumentNullException(nameof(provider));
-
- lock (s_InternalSyncObject)
- {
- if (s_providers == null)
- {
- s_providers = new EncodingProvider[1] { provider };
- return;
- }
-
- if (Array.IndexOf(s_providers, provider) >= 0)
- {
- return;
- }
-
- var providers = new EncodingProvider[s_providers.Length + 1];
- Array.Copy(s_providers, providers, s_providers.Length);
- providers[providers.Length - 1] = provider;
- s_providers = providers;
- }
- }
-
- internal static Encoding GetEncodingFromProvider(int codepage)
- {
- if (s_providers == null)
- return null;
-
- var providers = s_providers;
- foreach (EncodingProvider provider in providers)
- {
- Encoding enc = provider.GetEncoding(codepage);
- if (enc != null)
- return enc;
- }
-
- return null;
- }
-
- internal static Encoding GetEncodingFromProvider(string encodingName)
- {
- if (s_providers == null)
- return null;
-
- var providers = s_providers;
- foreach (EncodingProvider provider in providers)
- {
- Encoding enc = provider.GetEncoding(encodingName);
- if (enc != null)
- return enc;
- }
-
- return null;
- }
-
- internal static Encoding GetEncodingFromProvider(int codepage, EncoderFallback enc, DecoderFallback dec)
- {
- if (s_providers == null)
- return null;
-
- var providers = s_providers;
- foreach (EncodingProvider provider in providers)
- {
- Encoding encing = provider.GetEncoding(codepage, enc, dec);
- if (encing != null)
- return encing;
- }
-
- return null;
- }
-
- internal static Encoding GetEncodingFromProvider(string encodingName, EncoderFallback enc, DecoderFallback dec)
- {
- if (s_providers == null)
- return null;
-
- var providers = s_providers;
- foreach (EncodingProvider provider in providers)
- {
- Encoding encoding = provider.GetEncoding(encodingName, enc, dec);
- if (encoding != null)
- return encoding;
- }
-
- return null;
- }
-
- private static Object s_InternalSyncObject = new Object();
- private static volatile EncodingProvider[] s_providers;
- }
-}
diff --git a/src/mscorlib/src/System/Text/Latin1Encoding.cs b/src/mscorlib/src/System/Text/Latin1Encoding.cs
index 26009bf6c0..e456b8533d 100644
--- a/src/mscorlib/src/System/Text/Latin1Encoding.cs
+++ b/src/mscorlib/src/System/Text/Latin1Encoding.cs
@@ -2,19 +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.
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Collections;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+
namespace System.Text
{
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- using System.Runtime.InteropServices;
- using System.Security;
- using System.Collections;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
-
-
//
// Latin1Encoding is a simple override to optimize the GetString version of Latin1Encoding.
// because of the best fit cases we can't do this when encoding the string, only when decoding
@@ -47,7 +46,7 @@ namespace System.Text
{
// Make sure to get the base stuff too This throws if info is null
SerializeEncoding(info, context);
- Debug.Assert(info!=null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
+ Debug.Assert(info != null, "[Latin1Encoding.GetObjectData] Expected null info to throw");
// In Everett this is a CodePageEncoding, so it needs maxCharSize
info.AddValue("CodePageEncoding+maxCharSize", 1);
@@ -115,6 +114,7 @@ namespace System.Text
// For fallback we may need a fallback buffer, we know we aren't default fallback.
EncoderFallbackBuffer fallbackBuffer = null;
+ char* charsForFallback;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
@@ -128,7 +128,9 @@ namespace System.Text
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
// This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
+ charsForFallback = chars;
+ fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
+ chars = charsForFallback;
}
// Now we may have fallback char[] already from the encoder
@@ -161,7 +163,9 @@ namespace System.Text
}
// Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
+ charsForFallback = chars;
+ fallbackBuffer.InternalFallback(ch, ref charsForFallback);
+ chars = charsForFallback;
continue;
}
@@ -216,7 +220,7 @@ namespace System.Text
if (fallback != null && fallback.MaxCharCount == 1)
{
// Fast version
- char cReplacement=fallback.DefaultString[0];
+ char cReplacement = fallback.DefaultString[0];
// Check for replacements in range, otherwise fall back to slow version.
if (cReplacement <= (char)0xff)
@@ -262,7 +266,7 @@ namespace System.Text
if (encoder != null)
{
encoder.charLeftOver = (char)0;
- encoder.m_charsUsed = (int)(chars-charStart);
+ encoder.m_charsUsed = (int)(chars - charStart);
}
return (int)(bytes - byteStart);
}
@@ -275,6 +279,7 @@ namespace System.Text
// For fallback we may need a fallback buffer, we know we aren't default fallback, create & init it
EncoderFallbackBuffer fallbackBuffer = null;
+ char* charsForFallback;
// We may have a left over character from last time, try and process it.
if (charLeftOver > 0)
@@ -289,7 +294,10 @@ namespace System.Text
// Since left over char was a surrogate, it'll have to be fallen back.
// Get Fallback
// This will fallback a pair if *chars is a low surrogate
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
+ charsForFallback = chars;
+ fallbackBuffer.InternalFallback(charLeftOver, ref charsForFallback);
+ chars = charsForFallback;
+
if (fallbackBuffer.Remaining > byteEnd - bytes)
{
// Throw it, if we don't have enough for this we never will
@@ -327,7 +335,9 @@ namespace System.Text
}
// Get Fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
+ charsForFallback = chars;
+ fallbackBuffer.InternalFallback(ch, ref charsForFallback);
+ chars = charsForFallback;
// Make sure we have enough room. Each fallback char will be 1 output char
// (or else cause a recursion exception)
@@ -335,7 +345,7 @@ namespace System.Text
{
// Didn't use this char, throw it. Chars should've advanced by now
// If we had encoder fallback data it would've thrown before the loop
- Debug.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
chars--;
fallbackBuffer.InternalReset();
@@ -357,7 +367,7 @@ namespace System.Text
"[Latin1Encoding.GetBytes]Expected fallback to have throw initially if insufficient space");
if (fallbackBuffer == null || fallbackBuffer.bFallingBack == false)
{
- Debug.Assert(chars > charStart,
+ Debug.Assert(chars > charStart,
"[Latin1Encoding.GetBytes]Expected chars to have advanced (fallback case)");
chars--; // don't use last char
}
@@ -441,8 +451,8 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(charCount),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Characters would be # of characters + 1 in case high surrogate is ? * max fallback
@@ -454,15 +464,15 @@ namespace System.Text
// 1 to 1 for most characters. Only surrogates with fallbacks have less.
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Just return length, SBCS stay the same length because they don't map to surrogate
@@ -473,7 +483,7 @@ namespace System.Text
charCount *= DecoderFallback.MaxCharCount;
if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow);
return (int)charCount;
}
diff --git a/src/mscorlib/src/System/Text/Normalization.Unix.cs b/src/mscorlib/src/System/Text/Normalization.Unix.cs
index d49bdc6c21..2a10d062f2 100644
--- a/src/mscorlib/src/System/Text/Normalization.Unix.cs
+++ b/src/mscorlib/src/System/Text/Normalization.Unix.cs
@@ -4,6 +4,7 @@
using System.Security;
using System.Text;
+using System.Globalization;
namespace System.Text
{
@@ -13,11 +14,18 @@ namespace System.Text
{
ValidateArguments(strInput, normalizationForm);
+ if (GlobalizationMode.Invariant)
+ {
+ // In Invariant mode we assume all characters are normalized.
+ // This is because we don't support any linguistic operation on the strings
+ return true;
+ }
+
int ret = Interop.GlobalizationInterop.IsNormalized(normalizationForm, strInput, strInput.Length);
if (ret == -1)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
}
return ret == 1;
@@ -27,6 +35,13 @@ namespace System.Text
{
ValidateArguments(strInput, normalizationForm);
+ if (GlobalizationMode.Invariant)
+ {
+ // In Invariant mode we assume all characters are normalized.
+ // This is because we don't support any linguistic operation on the strings
+ return strInput;
+ }
+
char[] buf = new char[strInput.Length];
for (int attempts = 2; attempts > 0; attempts--)
@@ -35,7 +50,7 @@ namespace System.Text
if (realLen == -1)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
}
if (realLen <= buf.Length)
@@ -46,7 +61,7 @@ namespace System.Text
buf = new char[realLen];
}
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
}
// -----------------------------
@@ -63,12 +78,12 @@ namespace System.Text
if (normalizationForm != NormalizationForm.FormC && normalizationForm != NormalizationForm.FormD &&
normalizationForm != NormalizationForm.FormKC && normalizationForm != NormalizationForm.FormKD)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidNormalizationForm"), nameof(normalizationForm));
+ throw new ArgumentException(SR.Argument_InvalidNormalizationForm, nameof(normalizationForm));
}
if (HasInvalidUnicodeSequence(strInput))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"), nameof(strInput));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
}
}
diff --git a/src/mscorlib/src/System/Text/Normalization.Windows.cs b/src/mscorlib/src/System/Text/Normalization.Windows.cs
index 3bcba08934..389dba743d 100644
--- a/src/mscorlib/src/System/Text/Normalization.Windows.cs
+++ b/src/mscorlib/src/System/Text/Normalization.Windows.cs
@@ -2,176 +2,53 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+using System;
+using System.Security;
+using System.Globalization;
+using System.Text;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System;
- using System.Security;
- using System.Globalization;
- using System.Text;
- using System.Runtime.CompilerServices;
- using System.Runtime.InteropServices;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
// This internal class wraps up our normalization behavior
internal class Normalization
{
- //
- // Flags that track whether given normalization form was initialized
- //
- private static volatile bool NFC;
- private static volatile bool NFD;
- private static volatile bool NFKC;
- private static volatile bool NFKD;
- private static volatile bool IDNA;
- private static volatile bool NFCDisallowUnassigned;
- private static volatile bool NFDDisallowUnassigned;
- private static volatile bool NFKCDisallowUnassigned;
- private static volatile bool NFKDDisallowUnassigned;
- private static volatile bool IDNADisallowUnassigned;
- private static volatile bool Other;
-
- // These are error codes we get back from the Normalization DLL
- private const int ERROR_SUCCESS = 0;
- private const int ERROR_NOT_ENOUGH_MEMORY = 8;
- private const int ERROR_INVALID_PARAMETER = 87;
- private const int ERROR_INSUFFICIENT_BUFFER = 122;
- private const int ERROR_NO_UNICODE_TRANSLATION = 1113;
-
- static private unsafe void InitializeForm(NormalizationForm form, String strDataFile)
+ internal static bool IsNormalized(String strInput, NormalizationForm normForm)
{
- byte* pTables = null;
-
- // Normalization uses OS on Win8
- if (!Environment.IsWindows8OrAbove)
+ if (GlobalizationMode.Invariant)
{
- if (strDataFile == null)
- {
- // They were supposed to have a form that we know about!
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidNormalizationForm"));
- }
-
- // Tell the DLL where to find our data
- pTables = GlobalizationAssembly.GetGlobalizationResourceBytePtr(
- typeof(Normalization).Assembly, strDataFile);
- if (pTables == null)
- {
- // Unable to load the specified normalizationForm,
- // tables not loaded from file
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidNormalizationForm"));
- }
+ // In Invariant mode we assume all characters are normalized.
+ // This is because we don't support any linguistic operation on the strings
+ return true;
}
- nativeNormalizationInitNormalization(form, pTables);
- }
-
- static private void EnsureInitialized(NormalizationForm form)
- {
- switch ((ExtendedNormalizationForms)form)
- {
- case ExtendedNormalizationForms.FormC:
- if (NFC) return;
- InitializeForm(form, "normnfc.nlp");
- NFC = true;
- break;
-
- case ExtendedNormalizationForms.FormD:
- if (NFD) return;
- InitializeForm(form, "normnfd.nlp");
- NFD = true;
- break;
-
- case ExtendedNormalizationForms.FormKC:
- if (NFKC) return;
- InitializeForm(form, "normnfkc.nlp");
- NFKC = true;
- break;
-
- case ExtendedNormalizationForms.FormKD:
- if (NFKD) return;
- InitializeForm(form, "normnfkd.nlp");
- NFKD = true;
- break;
-
- case ExtendedNormalizationForms.FormIdna:
- if (IDNA) return;
- InitializeForm(form, "normidna.nlp");
- IDNA = true;
- break;
-
- case ExtendedNormalizationForms.FormCDisallowUnassigned:
- if (NFCDisallowUnassigned) return;
- InitializeForm(form, "normnfc.nlp");
- NFCDisallowUnassigned = true;
- break;
+ Debug.Assert(strInput != null);
- case ExtendedNormalizationForms.FormDDisallowUnassigned:
- if (NFDDisallowUnassigned) return;
- InitializeForm(form, "normnfd.nlp");
- NFDDisallowUnassigned = true;
- break;
+ // The only way to know if IsNormalizedString failed is through checking the Win32 last error
+ // IsNormalizedString pinvoke has SetLastError attribute property which will set the last error
+ // to 0 (ERROR_SUCCESS) before executing the calls.
+ bool result = Interop.Normaliz.IsNormalizedString((int)normForm, strInput, strInput.Length);
- case ExtendedNormalizationForms.FormKCDisallowUnassigned:
- if (NFKCDisallowUnassigned) return;
- InitializeForm(form, "normnfkc.nlp");
- NFKCDisallowUnassigned = true;
+ int lastError = Marshal.GetLastWin32Error();
+ switch (lastError)
+ {
+ case Interop.Errors.ERROR_SUCCESS:
break;
- case ExtendedNormalizationForms.FormKDDisallowUnassigned:
- if (NFKDDisallowUnassigned) return;
- InitializeForm(form, "normnfkd.nlp");
- NFKDDisallowUnassigned = true;
- break;
+ case Interop.Errors.ERROR_INVALID_PARAMETER:
+ case Interop.Errors.ERROR_NO_UNICODE_TRANSLATION:
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
- case ExtendedNormalizationForms.FormIdnaDisallowUnassigned:
- if (IDNADisallowUnassigned) return;
- InitializeForm(form, "normidna.nlp");
- IDNADisallowUnassigned = true;
- break;
+ case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY:
+ throw new OutOfMemoryException();
default:
- if (Other) return;
- InitializeForm(form, null);
- Other = true;
- break;
- }
- }
-
- internal static bool IsNormalized(String strInput, NormalizationForm normForm)
- {
- Contract.Requires(strInput != null);
-
- EnsureInitialized(normForm);
-
- int iError = ERROR_SUCCESS;
- bool result = nativeNormalizationIsNormalizedString(
- normForm,
- ref iError,
- strInput,
- strInput.Length);
-
- switch(iError)
- {
- // Success doesn't need to do anything
- case ERROR_SUCCESS:
- break;
-
- // Do appropriate stuff for the individual errors:
- case ERROR_INVALID_PARAMETER:
- case ERROR_NO_UNICODE_TRANSLATION:
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
- nameof(strInput));
- case ERROR_NOT_ENOUGH_MEMORY:
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
- default:
- throw new InvalidOperationException(
- Environment.GetResourceString("UnknownError_Num", iError));
+ throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
}
return result;
@@ -179,37 +56,41 @@ namespace System.Text
internal static String Normalize(String strInput, NormalizationForm normForm)
{
- Contract.Requires(strInput != null);
+ if (GlobalizationMode.Invariant)
+ {
+ // In Invariant mode we assume all characters are normalized.
+ // This is because we don't support any linguistic operation on the strings
+ return strInput;
+ }
- EnsureInitialized(normForm);
+ Debug.Assert(strInput != null);
- int iError = ERROR_SUCCESS;
+ // we depend on Win32 last error when calling NormalizeString
+ // NormalizeString pinvoke has SetLastError attribute property which will set the last error
+ // to 0 (ERROR_SUCCESS) before executing the calls.
// Guess our buffer size first
- int iLength = nativeNormalizationNormalizeString(normForm, ref iError, strInput, strInput.Length, null, 0);
+ int iLength = Interop.Normaliz.NormalizeString((int)normForm, strInput, strInput.Length, null, 0);
+ int lastError = Marshal.GetLastWin32Error();
// Could have an error (actually it'd be quite hard to have an error here)
- if (iError != ERROR_SUCCESS)
+ if ((lastError != Interop.Errors.ERROR_SUCCESS) || iLength < 0)
{
- if (iError == ERROR_INVALID_PARAMETER)
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex" ),
- nameof(strInput));
+ if (lastError == Interop.Errors.ERROR_INVALID_PARAMETER)
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
// We shouldn't really be able to get here..., guessing length is
// a trivial math function...
// Can't really be Out of Memory, but just in case:
- if (iError == ERROR_NOT_ENOUGH_MEMORY)
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
+ if (lastError == Interop.Errors.ERROR_NOT_ENOUGH_MEMORY)
+ throw new OutOfMemoryException();
// Who knows what happened? Not us!
- throw new InvalidOperationException(
- Environment.GetResourceString("UnknownError_Num", iError));
+ throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
}
// Don't break for empty strings (only possible for D & KD and not really possible at that)
- if (iLength == 0) return String.Empty;
+ if (iLength == 0) return string.Empty;
// Someplace to stick our buffer
char[] cBuffer = null;
@@ -219,60 +100,39 @@ namespace System.Text
// (re)allocation buffer and normalize string
cBuffer = new char[iLength];
- iLength = nativeNormalizationNormalizeString(
- normForm,
- ref iError,
- strInput,
- strInput.Length,
- cBuffer,
- cBuffer.Length);
-
- if (iError == ERROR_SUCCESS)
+ // NormalizeString pinvoke has SetLastError attribute property which will set the last error
+ // to 0 (ERROR_SUCCESS) before executing the calls.
+ iLength = Interop.Normaliz.NormalizeString((int)normForm, strInput, strInput.Length, cBuffer, cBuffer.Length);
+ lastError = Marshal.GetLastWin32Error();
+
+ if (lastError == Interop.Errors.ERROR_SUCCESS)
break;
// Could have an error (actually it'd be quite hard to have an error here)
- switch(iError)
+ switch (lastError)
{
// Do appropriate stuff for the individual errors:
- case ERROR_INSUFFICIENT_BUFFER:
+ case Interop.Errors.ERROR_INSUFFICIENT_BUFFER:
+ iLength = Math.Abs(iLength);
Debug.Assert(iLength > cBuffer.Length, "Buffer overflow should have iLength > cBuffer.Length");
continue;
- case ERROR_INVALID_PARAMETER:
- case ERROR_NO_UNICODE_TRANSLATION:
+ case Interop.Errors.ERROR_INVALID_PARAMETER:
+ case Interop.Errors.ERROR_NO_UNICODE_TRANSLATION:
// Illegal code point or order found. Ie: FFFE or D800 D800, etc.
- throw new ArgumentException(
- Environment.GetResourceString("Argument_InvalidCharSequence", iLength ),
- nameof(strInput));
- case ERROR_NOT_ENOUGH_MEMORY:
- throw new OutOfMemoryException(
- Environment.GetResourceString("Arg_OutOfMemoryException"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, nameof(strInput));
+
+ case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY:
+ throw new OutOfMemoryException();
default:
// We shouldn't get here...
- throw new InvalidOperationException(
- Environment.GetResourceString("UnknownError_Num", iError));
+ throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastError));
}
}
// Copy our buffer into our new string, which will be the appropriate size
- return new String(cBuffer, 0, iLength);
+ return new string(cBuffer, 0, iLength);
}
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe private static extern int nativeNormalizationNormalizeString(
- NormalizationForm normForm, ref int iError,
- String lpSrcString, int cwSrcLength,
- char[] lpDstString, int cwDstLength);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe private static extern bool nativeNormalizationIsNormalizedString(
- NormalizationForm normForm, ref int iError,
- String lpString, int cwLength);
-
- [SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- unsafe private static extern void nativeNormalizationInitNormalization(
- NormalizationForm normForm, byte* pTableData);
}
}
diff --git a/src/mscorlib/src/System/Text/Normalization.cs b/src/mscorlib/src/System/Text/Normalization.cs
deleted file mode 100644
index c81149d59a..0000000000
--- a/src/mscorlib/src/System/Text/Normalization.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.
-
-namespace System.Text
-{
- // This is the enumeration for Normalization Forms
- public enum NormalizationForm
- {
- FormC = 1,
- FormD = 2,
- 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/src/System/Text/StringBuilder.CoreCLR.cs b/src/mscorlib/src/System/Text/StringBuilder.CoreCLR.cs
new file mode 100644
index 0000000000..db3895f161
--- /dev/null
+++ b/src/mscorlib/src/System/Text/StringBuilder.CoreCLR.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.Runtime.CompilerServices;
+
+namespace System.Text
+{
+ public partial class StringBuilder
+ {
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength);
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength);
+
+ // Copies the source StringBuilder to the destination IntPtr memory allocated with len bytes.
+ internal unsafe void InternalCopy(IntPtr dest, int len)
+ {
+ if (len == 0)
+ return;
+
+ bool isLastChunk = true;
+ byte* dstPtr = (byte*)dest.ToPointer();
+ StringBuilder currentSrc = FindChunkForByte(len);
+
+ do
+ {
+ int chunkOffsetInBytes = currentSrc.m_ChunkOffset * sizeof(char);
+ int chunkLengthInBytes = currentSrc.m_ChunkLength * sizeof(char);
+ fixed (char* charPtr = &currentSrc.m_ChunkChars[0])
+ {
+ byte* srcPtr = (byte*)charPtr;
+ if (isLastChunk)
+ {
+ isLastChunk = false;
+ Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, len - chunkOffsetInBytes);
+ }
+ else
+ {
+ Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, chunkLengthInBytes);
+ }
+ }
+ currentSrc = currentSrc.m_ChunkPrevious;
+ } while (currentSrc != null);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Text/StringBuilder.cs b/src/mscorlib/src/System/Text/StringBuilder.cs
deleted file mode 100644
index 72247c333e..0000000000
--- a/src/mscorlib/src/System/Text/StringBuilder.cs
+++ /dev/null
@@ -1,2286 +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: implementation of the StringBuilder
-** class.
-**
-===========================================================*/
-namespace System.Text {
- using System.Text;
- using System.Runtime;
- using System.Runtime.Serialization;
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Threading;
- using System.Globalization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Collections.Generic;
-
- // This class represents a mutable string. It is convenient for situations in
- // which it is desirable to modify a string, perhaps by removing, replacing, or
- // inserting characters, without creating a new String subsequent to
- // each modification.
- //
- // The methods contained within this class do not return a new StringBuilder
- // object unless specified otherwise. This class may be used in conjunction with the String
- // class to carry out modifications upon strings.
- //
- // When passing null into a constructor in VJ and VC, the null
- // should be explicitly type cast.
- // For Example:
- // StringBuilder sb1 = new StringBuilder((StringBuilder)null);
- // StringBuilder sb2 = new StringBuilder((String)null);
- // Console.WriteLine(sb1);
- // Console.WriteLine(sb2);
- //
- [Serializable]
- public sealed class StringBuilder : ISerializable
- {
- // A StringBuilder is internally represented as a linked list of blocks each of which holds
- // a chunk of the string. It turns out string as a whole can also be represented as just a chunk,
- // so that is what we do.
-
- //
- //
- // CLASS VARIABLES
- //
- //
- internal char[] m_ChunkChars; // The characters in this block
- internal StringBuilder m_ChunkPrevious; // Link to the block logically before this block
- internal int m_ChunkLength; // The index in m_ChunkChars that represent the end of the block
- internal int m_ChunkOffset; // The logical offset (sum of all characters in previous blocks)
- internal int m_MaxCapacity = 0;
-
- //
- //
- // STATIC CONSTANTS
- //
- //
- internal const int DefaultCapacity = 16;
- private const String CapacityField = "Capacity";
- private const String MaxCapacityField = "m_MaxCapacity";
- private const String StringValueField = "m_StringValue";
- private const String ThreadIDField = "m_currentThread";
- // We want to keep chunk arrays out of large object heap (< 85K bytes ~ 40K chars) to be sure.
- // Making the maximum chunk size big means less allocation code called, but also more waste
- // in unused characters and slower inserts / replaces (since you do need to slide characters over
- // within a buffer).
- internal const int MaxChunkSize = 8000;
-
- //
- //
- //CONSTRUCTORS
- //
- //
-
- // Creates a new empty string builder (i.e., it represents String.Empty)
- // with the default capacity (16 characters).
- public StringBuilder()
- {
- m_MaxCapacity = int.MaxValue;
- m_ChunkChars = new char[DefaultCapacity];
- }
-
- // Create a new empty string builder (i.e., it represents String.Empty)
- // with the specified capacity.
- public StringBuilder(int capacity)
- : this(capacity, int.MaxValue)
- {
- }
-
- // Creates a new string builder from the specified string. If value
- // is a null String (i.e., if it represents String.NullString)
- // then the new string builder will also be null (i.e., it will also represent
- // String.NullString).
- //
- public StringBuilder(String value)
- : this(value, DefaultCapacity) {
- }
-
- // Creates a new string builder from the specified string with the specified
- // capacity. If value is a null String (i.e., if it represents
- // String.NullString) then the new string builder will also be null
- // (i.e., it will also represent String.NullString).
- // The maximum number of characters this string may contain is set by capacity.
- //
- public StringBuilder(String value, int capacity)
- : this(value, 0, ((value != null) ? value.Length : 0), capacity) {
- }
-
- // Creates a new string builder from the specifed substring with the specified
- // capacity. The maximum number of characters is set by capacity.
- //
- public StringBuilder(String value, int startIndex, int length, int capacity) {
- if (capacity<0) {
- throw new ArgumentOutOfRangeException(nameof(capacity),
- Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity)));
- }
- if (length<0) {
- throw new ArgumentOutOfRangeException(nameof(length),
- Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(length)));
- }
- if (startIndex<0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- }
- Contract.EndContractBlock();
-
- if (value == null) {
- value = String.Empty;
- }
- if (startIndex > value.Length - length) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
- }
- m_MaxCapacity = Int32.MaxValue;
- if (capacity == 0) {
- capacity = DefaultCapacity;
- }
- if (capacity < length)
- capacity = length;
-
- m_ChunkChars = new char[capacity];
- m_ChunkLength = length;
-
- unsafe {
- fixed (char* sourcePtr = value)
- ThreadSafeCopy(sourcePtr + startIndex, m_ChunkChars, 0, length);
- }
- }
-
- // Creates an empty StringBuilder with a minimum capacity of capacity
- // and a maximum capacity of maxCapacity.
- public StringBuilder(int capacity, int maxCapacity) {
- if (capacity>maxCapacity) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
- }
- if (maxCapacity<1) {
- throw new ArgumentOutOfRangeException(nameof(maxCapacity), Environment.GetResourceString("ArgumentOutOfRange_SmallMaxCapacity"));
- }
- if (capacity<0) {
- throw new ArgumentOutOfRangeException(nameof(capacity),
- Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", nameof(capacity)));
- }
- Contract.EndContractBlock();
-
- if (capacity == 0) {
- capacity = Math.Min(DefaultCapacity, maxCapacity);
- }
-
- m_MaxCapacity = maxCapacity;
- m_ChunkChars = new char[capacity];
- }
-
- private StringBuilder(SerializationInfo info, StreamingContext context) {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- int persistedCapacity = 0;
- string persistedString = null;
- int persistedMaxCapacity = Int32.MaxValue;
- bool capacityPresent = false;
-
- // Get the data
- SerializationInfoEnumerator enumerator = info.GetEnumerator();
- while (enumerator.MoveNext()) {
- switch (enumerator.Name) {
- case MaxCapacityField:
- persistedMaxCapacity = info.GetInt32(MaxCapacityField);
- break;
- case StringValueField:
- persistedString = info.GetString(StringValueField);
- break;
- case CapacityField:
- persistedCapacity = info.GetInt32(CapacityField);
- capacityPresent = true;
- break;
- default:
- // Ignore other fields for forward compatibility.
- break;
- }
-
- }
-
- // Check values and set defaults
- if (persistedString == null) {
- persistedString = String.Empty;
- }
- if (persistedMaxCapacity < 1 || persistedString.Length > persistedMaxCapacity) {
- throw new SerializationException(Environment.GetResourceString("Serialization_StringBuilderMaxCapacity"));
- }
-
- if (!capacityPresent) {
- // StringBuilder in V1.X did not persist the Capacity, so this is a valid legacy code path.
- persistedCapacity = DefaultCapacity;
- if (persistedCapacity < persistedString.Length) {
- persistedCapacity = persistedString.Length;
- }
- if (persistedCapacity > persistedMaxCapacity) {
- persistedCapacity = persistedMaxCapacity;
- }
- }
- if (persistedCapacity < 0 || persistedCapacity < persistedString.Length || persistedCapacity > persistedMaxCapacity) {
- throw new SerializationException(Environment.GetResourceString("Serialization_StringBuilderCapacity"));
- }
-
- // Assign
- m_MaxCapacity = persistedMaxCapacity;
- m_ChunkChars = new char[persistedCapacity];
- persistedString.CopyTo(0, m_ChunkChars, 0, persistedString.Length);
- m_ChunkLength = persistedString.Length;
- m_ChunkPrevious = null;
- VerifyClassInvariant();
- }
-
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info==null) {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
-
- VerifyClassInvariant();
- info.AddValue(MaxCapacityField, m_MaxCapacity);
- info.AddValue(CapacityField, Capacity);
- info.AddValue(StringValueField, ToString());
- // Note: persist "m_currentThread" to be compatible with old versions
- info.AddValue(ThreadIDField, 0);
- }
-
- [System.Diagnostics.Conditional("_DEBUG")]
- private void VerifyClassInvariant() {
- BCLDebug.Correctness((uint)(m_ChunkOffset + m_ChunkChars.Length) >= m_ChunkOffset, "Integer Overflow");
- StringBuilder currentBlock = this;
- int maxCapacity = this.m_MaxCapacity;
- for (; ; )
- {
- // All blocks have copy of the maxCapacity.
- Debug.Assert(currentBlock.m_MaxCapacity == maxCapacity, "Bad maxCapacity");
- Debug.Assert(currentBlock.m_ChunkChars != null, "Empty Buffer");
-
- Debug.Assert(currentBlock.m_ChunkLength <= currentBlock.m_ChunkChars.Length, "Out of range length");
- Debug.Assert(currentBlock.m_ChunkLength >= 0, "Negative length");
- Debug.Assert(currentBlock.m_ChunkOffset >= 0, "Negative offset");
-
- StringBuilder prevBlock = currentBlock.m_ChunkPrevious;
- if (prevBlock == null)
- {
- Debug.Assert(currentBlock.m_ChunkOffset == 0, "First chunk's offset is not 0");
- break;
- }
- // There are no gaps in the blocks.
- Debug.Assert(currentBlock.m_ChunkOffset == prevBlock.m_ChunkOffset + prevBlock.m_ChunkLength, "There is a gap between chunks!");
- currentBlock = prevBlock;
- }
- }
-
- public int Capacity {
- get { return m_ChunkChars.Length + m_ChunkOffset; }
- set {
- if (value < 0) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
- }
- if (value > MaxCapacity) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_Capacity"));
- }
- if (value < Length) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
- }
- Contract.EndContractBlock();
-
- if (Capacity != value) {
- int newLen = value - m_ChunkOffset;
- char[] newArray = new char[newLen];
- Array.Copy(m_ChunkChars, newArray, m_ChunkLength);
- m_ChunkChars = newArray;
- }
- }
- }
-
- public int MaxCapacity {
- get { return m_MaxCapacity; }
- }
-
- // Read-Only Property
- // Ensures that the capacity of this string builder is at least the specified value.
- // If capacity is greater than the capacity of this string builder, then the capacity
- // is set to capacity; otherwise the capacity is unchanged.
- //
- public int EnsureCapacity(int capacity) {
- if (capacity < 0) {
- throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
- }
- Contract.EndContractBlock();
-
- if (Capacity < capacity)
- Capacity = capacity;
- return Capacity;
- }
-
- public override String ToString() {
- Contract.Ensures(Contract.Result<String>() != null);
-
- VerifyClassInvariant();
-
- if (Length == 0)
- return String.Empty;
-
- string ret = string.FastAllocateString(Length);
- StringBuilder chunk = this;
- unsafe {
- fixed (char* destinationPtr = ret)
- {
- do
- {
- if (chunk.m_ChunkLength > 0)
- {
- // Copy these into local variables so that they are stable even in the presence of race conditions
- char[] sourceArray = chunk.m_ChunkChars;
- int chunkOffset = chunk.m_ChunkOffset;
- int chunkLength = chunk.m_ChunkLength;
-
- // Check that we will not overrun our boundaries.
- if ((uint)(chunkLength + chunkOffset) <= (uint)ret.Length && (uint)chunkLength <= (uint)sourceArray.Length)
- {
- fixed (char* sourcePtr = &sourceArray[0])
- string.wstrcpy(destinationPtr + chunkOffset, sourcePtr, chunkLength);
- }
- else
- {
- throw new ArgumentOutOfRangeException(nameof(chunkLength), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- }
- chunk = chunk.m_ChunkPrevious;
- } while (chunk != null);
-
- return ret;
- }
- }
- }
-
-
- // Converts a substring of this string builder to a String.
- public String ToString(int startIndex, int length) {
- Contract.Ensures(Contract.Result<String>() != null);
-
- int currentLength = this.Length;
- if (startIndex < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- }
- if (startIndex > currentLength)
- {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"));
- }
- if (length < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
- }
- if (startIndex > (currentLength - length))
- {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_IndexLength"));
- }
-
- VerifyClassInvariant();
-
- StringBuilder chunk = this;
- int sourceEndIndex = startIndex + length;
-
- string ret = string.FastAllocateString(length);
- int curDestIndex = length;
- unsafe {
- fixed (char* destinationPtr = ret)
- {
- while (curDestIndex > 0)
- {
- int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
- if (chunkEndIndex >= 0)
- {
- if (chunkEndIndex > chunk.m_ChunkLength)
- chunkEndIndex = chunk.m_ChunkLength;
-
- int countLeft = curDestIndex;
- int chunkCount = countLeft;
- int chunkStartIndex = chunkEndIndex - countLeft;
- if (chunkStartIndex < 0)
- {
- chunkCount += chunkStartIndex;
- chunkStartIndex = 0;
- }
- curDestIndex -= chunkCount;
-
- if (chunkCount > 0)
- {
- // work off of local variables so that they are stable even in the presence of race conditions
- char[] sourceArray = chunk.m_ChunkChars;
-
- // Check that we will not overrun our boundaries.
- if ((uint)(chunkCount + curDestIndex) <= (uint)length && (uint)(chunkCount + chunkStartIndex) <= (uint)sourceArray.Length)
- {
- fixed (char* sourcePtr = &sourceArray[chunkStartIndex])
- string.wstrcpy(destinationPtr + curDestIndex, sourcePtr, chunkCount);
- }
- else
- {
- throw new ArgumentOutOfRangeException(nameof(chunkCount), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- }
- }
- chunk = chunk.m_ChunkPrevious;
- }
-
- return ret;
- }
- }
- }
-
- // Convenience method for sb.Length=0;
- public StringBuilder Clear() {
- this.Length = 0;
- return this;
- }
-
- // Sets the length of the String in this buffer. If length is less than the current
- // instance, the StringBuilder is truncated. If length is greater than the current
- // instance, nulls are appended. The capacity is adjusted to be the same as the length.
-
- public int Length {
- get {
- Contract.Ensures(Contract.Result<int>() >= 0);
- return m_ChunkOffset + m_ChunkLength;
- }
- set {
- //If the new length is less than 0 or greater than our Maximum capacity, bail.
- if (value<0) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
- }
-
- if (value>MaxCapacity) {
- throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
- }
- Contract.EndContractBlock();
-
- int originalCapacity = Capacity;
-
- if (value == 0 && m_ChunkPrevious == null)
- {
- m_ChunkLength = 0;
- m_ChunkOffset = 0;
- Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
- return;
- }
-
- int delta = value - Length;
- // if the specified length is greater than the current length
- if (delta > 0)
- {
- // the end of the string value of the current StringBuilder object is padded with the Unicode NULL character
- Append('\0', delta); // We could improve on this, but who does this anyway?
- }
- // if the specified length is less than or equal to the current length
- else
- {
- StringBuilder chunk = FindChunkForIndex(value);
- if (chunk != this)
- {
- // we crossed a chunk boundary when reducing the Length, we must replace this middle-chunk with a new
- // larger chunk to ensure the original capacity is preserved
- int newLen = originalCapacity - chunk.m_ChunkOffset;
- char[] newArray = new char[newLen];
-
- Debug.Assert(newLen > chunk.m_ChunkChars.Length, "the new chunk should be larger than the one it is replacing");
- Array.Copy(chunk.m_ChunkChars, newArray, chunk.m_ChunkLength);
-
- m_ChunkChars = newArray;
- m_ChunkPrevious = chunk.m_ChunkPrevious;
- m_ChunkOffset = chunk.m_ChunkOffset;
- }
- m_ChunkLength = value - chunk.m_ChunkOffset;
- VerifyClassInvariant();
- }
- Debug.Assert(Capacity >= originalCapacity, "setting the Length should never decrease the Capacity");
- }
- }
-
- [System.Runtime.CompilerServices.IndexerName("Chars")]
- public char this[int index] {
- get {
- StringBuilder chunk = this;
- for (; ; )
- {
- int indexInBlock = index - chunk.m_ChunkOffset;
- if (indexInBlock >= 0)
- {
- if (indexInBlock >= chunk.m_ChunkLength)
- throw new IndexOutOfRangeException();
- return chunk.m_ChunkChars[indexInBlock];
- }
- chunk = chunk.m_ChunkPrevious;
- if (chunk == null)
- throw new IndexOutOfRangeException();
- }
- }
- set {
- StringBuilder chunk = this;
- for (; ; )
- {
- int indexInBlock = index - chunk.m_ChunkOffset;
- if (indexInBlock >= 0)
- {
- if (indexInBlock >= chunk.m_ChunkLength)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- chunk.m_ChunkChars[indexInBlock] = value;
- return;
- }
- chunk = chunk.m_ChunkPrevious;
- if (chunk == null)
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- }
- }
-
- // Appends a character at the end of this string builder. The capacity is adjusted as needed.
- public StringBuilder Append(char value, int repeatCount) {
- if (repeatCount<0) {
- throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- if (repeatCount==0) {
- return this;
- }
-
- // this is where we can check if the repeatCount will put us over m_MaxCapacity
- // We are doing the check here to prevent the corruption of the StringBuilder.
- int newLength = Length + repeatCount;
- if (newLength > m_MaxCapacity || newLength < repeatCount) {
- throw new ArgumentOutOfRangeException(nameof(repeatCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
- }
-
- int idx = m_ChunkLength;
- while (repeatCount > 0)
- {
- if (idx < m_ChunkChars.Length)
- {
- m_ChunkChars[idx++] = value;
- --repeatCount;
- }
- else
- {
- m_ChunkLength = idx;
- ExpandByABlock(repeatCount);
- Debug.Assert(m_ChunkLength == 0, "Expand should create a new block");
- idx = 0;
- }
- }
- m_ChunkLength = idx;
- VerifyClassInvariant();
- return this;
- }
-
- // Appends an array of characters at the end of this string builder. The capacity is adjusted as needed.
- public StringBuilder Append(char[] value, int startIndex, int charCount) {
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- }
- if (charCount<0) {
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- if (value == null) {
- if (startIndex == 0 && charCount == 0) {
- return this;
- }
- throw new ArgumentNullException(nameof(value));
- }
- if (charCount > value.Length - startIndex) {
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (charCount==0) {
- return this;
- }
- unsafe
- {
- fixed (char* valueChars = &value[startIndex])
- {
- Append(valueChars, charCount);
-
- return this;
- }
- }
- }
-
-
- // Appends a copy of this string at the end of this string builder.
- public StringBuilder Append(String value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- if (value != null) {
- // This is a hand specialization of the 'AppendHelper' code below.
- // We could have just called AppendHelper.
- char[] chunkChars = m_ChunkChars;
- int chunkLength = m_ChunkLength;
- int valueLen = value.Length;
- int newCurrentIndex = chunkLength + valueLen;
- if (newCurrentIndex < chunkChars.Length) // Use strictly < to avoid issue if count == 0, newIndex == length
- {
- if (valueLen <= 2)
- {
- if (valueLen > 0)
- chunkChars[chunkLength] = value[0];
- if (valueLen > 1)
- chunkChars[chunkLength + 1] = value[1];
- }
- else
- {
- unsafe {
- fixed (char* valuePtr = value)
- fixed (char* destPtr = &chunkChars[chunkLength])
- string.wstrcpy(destPtr, valuePtr, valueLen);
- }
- }
- m_ChunkLength = newCurrentIndex;
- }
- else
- AppendHelper(value);
- }
- return this;
- }
-
-
- // We put this fixed in its own helper to avoid the cost zero initing valueChars in the
- // case we don't actually use it.
- private void AppendHelper(string value) {
- unsafe {
- fixed (char* valueChars = value)
- Append(valueChars, value.Length);
- }
- }
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal unsafe extern void ReplaceBufferInternal(char* newBuffer, int newLength);
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal unsafe extern void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength);
-
- // Appends a copy of the characters in value from startIndex to startIndex +
- // count at the end of this string builder.
- public StringBuilder Append(String value, int startIndex, int count) {
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- //If the value being added is null, eat the null
- //and return.
- if (value == null) {
- if (startIndex == 0 && count == 0) {
- return this;
- }
- throw new ArgumentNullException(nameof(value));
- }
-
- if (count == 0) {
- return this;
- }
-
- if (startIndex > value.Length - count) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- unsafe
- {
- fixed (char* valueChars = value)
- {
- Append(valueChars + startIndex, count);
-
- return this;
- }
- }
- }
-
- public StringBuilder AppendLine() {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(Environment.NewLine);
- }
-
- public StringBuilder AppendLine(string value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Append(value);
- return Append(Environment.NewLine);
- }
-
- public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) {
- if (destination == null) {
- throw new ArgumentNullException(nameof(destination));
- }
-
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("Arg_NegativeArgCount"));
- }
-
- if (destinationIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(destinationIndex),
- Environment.GetResourceString("ArgumentOutOfRange_MustBeNonNegNum", nameof(destinationIndex)));
- }
-
- if (destinationIndex > destination.Length - count) {
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_OffsetOut"));
- }
-
- if ((uint)sourceIndex > (uint)Length) {
- throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (sourceIndex > Length - count) {
- throw new ArgumentException(Environment.GetResourceString("Arg_LongerThanSrcString"));
- }
- Contract.EndContractBlock();
-
- VerifyClassInvariant();
-
- StringBuilder chunk = this;
- int sourceEndIndex = sourceIndex + count;
- int curDestIndex = destinationIndex + count;
- while (count > 0)
- {
- int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
- if (chunkEndIndex >= 0)
- {
- if (chunkEndIndex > chunk.m_ChunkLength)
- chunkEndIndex = chunk.m_ChunkLength;
-
- int chunkCount = count;
- int chunkStartIndex = chunkEndIndex - count;
- if (chunkStartIndex < 0)
- {
- chunkCount += chunkStartIndex;
- chunkStartIndex = 0;
- }
- curDestIndex -= chunkCount;
- count -= chunkCount;
-
- // SafeCritical: we ensure that chunkStartIndex + chunkCount are within range of m_chunkChars
- // as well as ensuring that curDestIndex + chunkCount are within range of destination
- ThreadSafeCopy(chunk.m_ChunkChars, chunkStartIndex, destination, curDestIndex, chunkCount);
- }
- chunk = chunk.m_ChunkPrevious;
- }
- }
-
- // Inserts multiple copies of a string into this string builder at the specified position.
- // Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, this
- // string builder is not changed.
- //
- public StringBuilder Insert(int index, String value, int count) {
- if (count < 0) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- //Range check the index.
- int currentLength = Length;
- if ((uint)index > (uint)currentLength) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- //If value is null, empty or count is 0, do nothing. This is ECMA standard.
- if (value == null || value.Length == 0 || count == 0) {
- return this;
- }
-
- //Ensure we don't insert more chars than we can hold, and we don't
- //have any integer overflow in our inserted characters.
- long insertingChars = (long) value.Length * count;
- if (insertingChars > MaxCapacity - this.Length) {
- throw new OutOfMemoryException();
- }
- Debug.Assert(insertingChars + this.Length < Int32.MaxValue);
-
- StringBuilder chunk;
- int indexInChunk;
- MakeRoom(index, (int) insertingChars, out chunk, out indexInChunk, false);
- unsafe {
- fixed (char* valuePtr = value) {
- while (count > 0)
- {
- ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, valuePtr, value.Length);
- --count;
- }
-
- return this;
- }
- }
- }
-
- // Removes the specified characters from this string builder.
- // The length of this string builder is reduced by
- // length, but the capacity is unaffected.
- //
- public StringBuilder Remove(int startIndex, int length) {
- if (length<0) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_NegativeLength"));
- }
-
- if (startIndex<0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- }
-
- if (length > Length - startIndex) {
- throw new ArgumentOutOfRangeException(nameof(length), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- if (Length == length && startIndex == 0) {
- // Optimization. If we are deleting everything
- Length = 0;
- return this;
- }
-
- if (length > 0)
- {
- StringBuilder chunk;
- int indexInChunk;
- Remove(startIndex, length, out chunk, out indexInChunk);
- }
- return this;
- }
-
- //
- // PUBLIC INSTANCE FUNCTIONS
- //
- //
-
- /*====================================Append====================================
- **
- ==============================================================================*/
- // Appends a boolean to the end of this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(bool value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString());
- }
-
- // Appends an sbyte to this string builder.
- // The capacity is adjusted as needed.
- [CLSCompliant(false)]
- public StringBuilder Append(sbyte value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends a ubyte to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(byte value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends a character at the end of this string builder. The capacity is adjusted as needed.
- public StringBuilder Append(char value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- if (m_ChunkLength < m_ChunkChars.Length)
- m_ChunkChars[m_ChunkLength++] = value;
- else
- Append(value, 1);
- return this;
- }
-
- // Appends a short to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(short value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends an int to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(int value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends a long to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(long value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends a float to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(float value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends a double to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(double value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- public StringBuilder Append(decimal value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends an ushort to this string builder.
- // The capacity is adjusted as needed.
- [CLSCompliant(false)]
- public StringBuilder Append(ushort value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends an uint to this string builder.
- // The capacity is adjusted as needed.
- [CLSCompliant(false)]
- public StringBuilder Append(uint value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends an unsigned long to this string builder.
- // The capacity is adjusted as needed.
- [CLSCompliant(false)]
- public StringBuilder Append(ulong value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Append(value.ToString(CultureInfo.CurrentCulture));
- }
-
- // Appends an Object to this string builder.
- // The capacity is adjusted as needed.
- public StringBuilder Append(Object value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- if (null==value) {
- //Appending null is now a no-op.
- return this;
- }
- return Append(value.ToString());
- }
-
- // Appends all of the characters in value to the current instance.
- public StringBuilder Append(char[] value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- if (null != value && value.Length > 0)
- {
- unsafe {
- fixed (char* valueChars = &value[0])
- Append(valueChars, value.Length);
- }
- }
- return this;
- }
-
- // Append joined values with a separator between each value.
- public unsafe StringBuilder AppendJoin<T>(char separator, params T[] values)
- {
- // Defer argument validation to the internal function
- return AppendJoinCore(&separator, 1, values);
- }
-
- public unsafe StringBuilder AppendJoin<T>(string separator, params T[] values)
- {
- separator = separator ?? string.Empty;
- fixed (char* pSeparator = separator)
- {
- // Defer argument validation to the internal function
- return AppendJoinCore(pSeparator, separator.Length, values);
- }
- }
-
- public unsafe StringBuilder AppendJoin<T>(char separator, IEnumerable<T> values)
- {
- // Defer argument validation to the internal function
- return AppendJoinCore(&separator, 1, values);
- }
-
- public unsafe StringBuilder AppendJoin<T>(string separator, IEnumerable<T> values)
- {
- separator = separator ?? string.Empty;
- fixed (char* pSeparator = separator)
- {
- // Defer argument validation to the internal function
- return AppendJoinCore(pSeparator, separator.Length, values);
- }
- }
-
- private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, params T[] values)
- {
- if (values == null)
- throw new ArgumentNullException(nameof(values));
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- if (values.Length == 0)
- return this;
-
- var value = values[0];
- if (value != null)
- Append(value.ToString());
-
- for (var i = 1; i < values.Length; i++)
- {
- Append(separator, separatorLength);
- value = values[i];
- if (value != null)
- Append(value.ToString());
- }
- return this;
- }
-
- private unsafe StringBuilder AppendJoinCore<T>(char* separator, int separatorLength, IEnumerable<T> values)
- {
- if (values == null)
- throw new ArgumentNullException(nameof(values));
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- using (var en = values.GetEnumerator())
- {
- if (!en.MoveNext())
- return this;
-
- var value = en.Current;
- if (value != null)
- Append(value.ToString());
-
- while (en.MoveNext())
- {
- Append(separator, separatorLength);
- value = en.Current;
- if (value != null)
- Append(value.ToString());
- }
- }
- return this;
- }
-
- /*====================================Insert====================================
- **
- ==============================================================================*/
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, String value) {
- if ((uint)index > (uint)Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- if (value != null)
- {
- unsafe {
- fixed (char* sourcePtr = value)
- Insert(index, sourcePtr, value.Length);
- }
- }
- return this;
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert( int index, bool value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- [CLSCompliant(false)]
- public StringBuilder Insert(int index, sbyte value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, byte value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, short value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- public StringBuilder Insert(int index, char value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- unsafe {
- Insert(index, &value, 1);
- }
- return this;
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, char[] value) {
- if ((uint)index > (uint)Length) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- if (value != null)
- Insert(index, value, 0, value.Length);
- return this;
- }
-
- // Returns a reference to the StringBuilder with charCount characters from
- // value inserted into the buffer at index. Existing characters are shifted
- // to make room for the new text and capacity is adjusted as required. If value is null, the StringBuilder
- // is unchanged. Characters are taken from value starting at position startIndex.
- public StringBuilder Insert(int index, char[] value, int startIndex, int charCount) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- int currentLength = Length;
- if ((uint)index > (uint)currentLength) {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- //If they passed in a null char array, just jump out quickly.
- if (value == null) {
- if (startIndex == 0 && charCount == 0)
- {
- return this;
- }
- throw new ArgumentNullException(nameof(value), Environment.GetResourceString("ArgumentNull_String"));
- }
-
- //Range check the array.
- if (startIndex < 0) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_StartIndex"));
- }
-
- if (charCount < 0) {
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GenericPositive"));
- }
-
- if (startIndex > value.Length - charCount) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (charCount > 0)
- {
- unsafe {
- fixed (char* sourcePtr = &value[startIndex])
- Insert(index, sourcePtr, charCount);
- }
- }
- return this;
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, int value){
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, long value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, float value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with ; value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed.
- //
- public StringBuilder Insert(int index, double value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- public StringBuilder Insert(int index, decimal value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed.
- //
- [CLSCompliant(false)]
- public StringBuilder Insert(int index, ushort value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed.
- //
- [CLSCompliant(false)]
- public StringBuilder Insert(int index, uint value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to the StringBuilder with value inserted into
- // the buffer at index. Existing characters are shifted to make room for the new text.
- // The capacity is adjusted as needed.
- //
- [CLSCompliant(false)]
- public StringBuilder Insert(int index, ulong value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Insert(index, value.ToString(CultureInfo.CurrentCulture), 1);
- }
-
- // Returns a reference to this string builder with value inserted into
- // the buffer at index. Existing characters are shifted to make room for the
- // new text. The capacity is adjusted as needed. If value equals String.Empty, the
- // StringBuilder is not changed. No changes are made if value is null.
- //
- public StringBuilder Insert(int index, Object value) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- if (null == value) {
- return this;
- }
- return Insert(index, value.ToString(), 1);
- }
-
- public StringBuilder AppendFormat(String format, Object arg0) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return AppendFormatHelper(null, format, new ParamsArray(arg0));
- }
-
- public StringBuilder AppendFormat(String format, Object arg0, Object arg1) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return AppendFormatHelper(null, format, new ParamsArray(arg0, arg1));
- }
-
- public StringBuilder AppendFormat(String format, Object arg0, Object arg1, Object arg2) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2));
- }
-
- public StringBuilder AppendFormat(String format, params Object[] args) {
- if (args == null)
- {
- // To preserve the original exception behavior, throw an exception about format if both
- // args and format are null. The actual null check for format is in AppendFormatHelper.
- throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args));
- }
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
-
- return AppendFormatHelper(null, format, new ParamsArray(args));
- }
-
- public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return AppendFormatHelper(provider, format, new ParamsArray(arg0));
- }
-
- public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0, Object arg1) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1));
- }
-
- public StringBuilder AppendFormat(IFormatProvider provider, String format, Object arg0, Object arg1, Object arg2) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2));
- }
-
- public StringBuilder AppendFormat(IFormatProvider provider, String format, params Object[] args) {
- if (args == null)
- {
- // To preserve the original exception behavior, throw an exception about format if both
- // args and format are null. The actual null check for format is in AppendFormatHelper.
- throw new ArgumentNullException((format == null) ? nameof(format) : nameof(args));
- }
- Contract.Ensures(Contract.Result<String>() != null);
- Contract.EndContractBlock();
-
- return AppendFormatHelper(provider, format, new ParamsArray(args));
- }
-
- private static void FormatError() {
- throw new FormatException(Environment.GetResourceString("Format_InvalidString"));
- }
-
- // undocumented exclusive limits on the range for Argument Hole Index and Argument Hole Alignment.
- private const int Index_Limit = 1000000; // Note: 0 <= ArgIndex < Index_Limit
- private const int Width_Limit = 1000000; // Note: -Width_Limit < ArgAlign < Width_Limit
-
- internal StringBuilder AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args) {
- if (format == null) {
- throw new ArgumentNullException(nameof(format));
- }
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- Contract.EndContractBlock();
-
- int pos = 0;
- int len = format.Length;
- char ch = '\x0';
- StringBuilder unescapedItemFormat = null;
-
- ICustomFormatter cf = null;
- if (provider != null) {
- cf = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
- }
-
- while (true) {
- while (pos < len) {
- ch = format[pos];
-
- pos++;
- // Is it a closing brace?
- if (ch == '}')
- {
- // Check next character (if there is one) to see if it is escaped. eg }}
- if (pos < len && format[pos] == '}')
- pos++;
- else
- // Otherwise treat it as an error (Mismatched closing brace)
- FormatError();
- }
- // Is it a opening brace?
- if (ch == '{')
- {
- // Check next character (if there is one) to see if it is escaped. eg {{
- if (pos < len && format[pos] == '{')
- pos++;
- else
- {
- // Otherwise treat it as the opening brace of an Argument Hole.
- pos--;
- break;
- }
- }
- // If it neither then treat the character as just text.
- Append(ch);
- }
-
- //
- // Start of parsing of Argument Hole.
- // Argument Hole ::= { Index (, WS* Alignment WS*)? (: Formatting)? }
- //
- if (pos == len) break;
-
- //
- // Start of parsing required Index parameter.
- // Index ::= ('0'-'9')+ WS*
- //
- pos++;
- // If reached end of text then error (Unexpected end of text)
- // or character is not a digit then error (Unexpected Character)
- if (pos == len || (ch = format[pos]) < '0' || ch > '9') FormatError();
- int index = 0;
- do {
- index = index * 10 + ch - '0';
- pos++;
- // If reached end of text then error (Unexpected end of text)
- if (pos == len) FormatError();
- ch = format[pos];
- // so long as character is digit and value of the index is less than 1000000 ( index limit )
- } while (ch >= '0' && ch <= '9' && index < Index_Limit);
-
- // If value of index is not within the range of the arguments passed in then error (Index out of range)
- if (index >= args.Length) throw new FormatException(Environment.GetResourceString("Format_IndexOutOfRange"));
-
- // Consume optional whitespace.
- while (pos < len && (ch = format[pos]) == ' ') pos++;
- // End of parsing index parameter.
-
- //
- // Start of parsing of optional Alignment
- // Alignment ::= comma WS* minus? ('0'-'9')+ WS*
- //
- bool leftJustify = false;
- int width = 0;
- // Is the character a comma, which indicates the start of alignment parameter.
- if (ch == ',') {
- pos++;
-
- // Consume Optional whitespace
- while (pos < len && format[pos] == ' ') pos++;
-
- // If reached the end of the text then error (Unexpected end of text)
- if (pos == len) FormatError();
-
- // Is there a minus sign?
- ch = format[pos];
- if (ch == '-') {
- // Yes, then alignment is left justified.
- leftJustify = true;
- pos++;
- // If reached end of text then error (Unexpected end of text)
- if (pos == len) FormatError();
- ch = format[pos];
- }
-
- // If current character is not a digit then error (Unexpected character)
- if (ch < '0' || ch > '9') FormatError();
- // Parse alignment digits.
- do {
- width = width * 10 + ch - '0';
- pos++;
- // If reached end of text then error. (Unexpected end of text)
- if (pos == len) FormatError();
- ch = format[pos];
- // So long a current character is a digit and the value of width is less than 100000 ( width limit )
- } while (ch >= '0' && ch <= '9' && width < Width_Limit);
- // end of parsing Argument Alignment
- }
-
- // Consume optional whitespace
- while (pos < len && (ch = format[pos]) == ' ') pos++;
-
- //
- // Start of parsing of optional formatting parameter.
- //
- Object arg = args[index];
- String itemFormat = null;
- // Is current character a colon? which indicates start of formatting parameter.
- if (ch == ':') {
- pos++;
- int startPos = pos;
-
- while (true) {
- // If reached end of text then error. (Unexpected end of text)
- if (pos == len) FormatError();
- ch = format[pos];
- pos++;
-
- // Is character a opening or closing brace?
- if (ch == '}' || ch == '{')
- {
- if (ch == '{')
- {
- // Yes, is next character also a opening brace, then treat as escaped. eg {{
- if (pos < len && format[pos] == '{')
- pos++;
- else
- // Error Argument Holes can not be nested.
- FormatError();
- }
- else
- {
- // Yes, is next character also a closing brace, then treat as escaped. eg }}
- if (pos < len && format[pos] == '}')
- pos++;
- else
- {
- // No, then treat it as the closing brace of an Arg Hole.
- pos--;
- break;
- }
- }
-
- // Reaching here means the brace has been escaped
- // so we need to build up the format string in segments
- if (unescapedItemFormat == null)
- {
- unescapedItemFormat = new StringBuilder();
- }
- unescapedItemFormat.Append(format, startPos, pos - startPos - 1);
- startPos = pos;
- }
- }
-
- if (unescapedItemFormat == null || unescapedItemFormat.Length == 0)
- {
- if (startPos != pos)
- {
- // There was no brace escaping, extract the item format as a single string
- itemFormat = format.Substring(startPos, pos - startPos);
- }
- }
- else
- {
- unescapedItemFormat.Append(format, startPos, pos - startPos);
- itemFormat = unescapedItemFormat.ToString();
- unescapedItemFormat.Clear();
- }
- }
- // If current character is not a closing brace then error. (Unexpected Character)
- if (ch != '}') FormatError();
- // Construct the output for this arg hole.
- pos++;
- String s = null;
- if (cf != null) {
- s = cf.Format(itemFormat, arg, provider);
- }
-
- if (s == null) {
- IFormattable formattableArg = arg as IFormattable;
-
- if (formattableArg != null) {
- s = formattableArg.ToString(itemFormat, provider);
- } else if (arg != null) {
- s = arg.ToString();
- }
- }
- // Append it to the final output of the Format String.
- if (s == null) s = String.Empty;
- int pad = width - s.Length;
- if (!leftJustify && pad > 0) Append(' ', pad);
- Append(s);
- if (leftJustify && pad > 0) Append(' ', pad);
- // Continue to parse other characters.
- }
- return this;
- }
-
- // Returns a reference to the current StringBuilder with all instances of oldString
- // replaced with newString. If startIndex and count are specified,
- // we only replace strings completely contained in the range of startIndex to startIndex +
- // count. The strings to be replaced are checked on an ordinal basis (e.g. not culture aware). If
- // newValue is null, instances of oldValue are removed (e.g. replaced with nothing.).
- //
- public StringBuilder Replace(String oldValue, String newValue) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
- return Replace(oldValue, newValue, 0, Length);
- }
-
- public bool Equals(StringBuilder sb)
- {
- if (sb == null)
- return false;
- if (Capacity != sb.Capacity || MaxCapacity != sb.MaxCapacity || Length != sb.Length)
- return false;
- if (sb == this)
- return true;
-
- StringBuilder thisChunk = this;
- int thisChunkIndex = thisChunk.m_ChunkLength;
- StringBuilder sbChunk = sb;
- int sbChunkIndex = sbChunk.m_ChunkLength;
- for (; ; )
- {
- // Decrement the pointer to the 'this' StringBuilder
- --thisChunkIndex;
- --sbChunkIndex;
-
- while (thisChunkIndex < 0)
- {
- thisChunk = thisChunk.m_ChunkPrevious;
- if (thisChunk == null)
- break;
- thisChunkIndex = thisChunk.m_ChunkLength + thisChunkIndex;
- }
-
- // Decrement the pointer to the 'this' StringBuilder
- while (sbChunkIndex < 0)
- {
- sbChunk = sbChunk.m_ChunkPrevious;
- if (sbChunk == null)
- break;
- sbChunkIndex = sbChunk.m_ChunkLength + sbChunkIndex;
- }
-
- if (thisChunkIndex < 0)
- return sbChunkIndex < 0;
- if (sbChunkIndex < 0)
- return false;
- if (thisChunk.m_ChunkChars[thisChunkIndex] != sbChunk.m_ChunkChars[sbChunkIndex])
- return false;
- }
- }
-
- public StringBuilder Replace(String oldValue, String newValue, int startIndex, int count)
- {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- int currentLength = Length;
- if ((uint)startIndex > (uint)currentLength)
- {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- if (count < 0 || startIndex > currentLength - count)
- {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- if (oldValue == null)
- {
- throw new ArgumentNullException(nameof(oldValue));
- }
- if (oldValue.Length == 0)
- {
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(oldValue));
- }
-
- if (newValue == null)
- newValue = "";
-
- int deltaLength = newValue.Length - oldValue.Length;
-
- int[] replacements = null; // A list of replacement positions in a chunk to apply
- int replacementsCount = 0;
-
- // Find the chunk, indexInChunk for the starting point
- StringBuilder chunk = FindChunkForIndex(startIndex);
- int indexInChunk = startIndex - chunk.m_ChunkOffset;
- while (count > 0)
- {
- // Look for a match in the chunk,indexInChunk pointer
- if (StartsWith(chunk, indexInChunk, count, oldValue))
- {
- // Push it on my replacements array (with growth), we will do all replacements in a
- // given chunk in one operation below (see ReplaceAllInChunk) so we don't have to slide
- // many times.
- if (replacements == null)
- replacements = new int[5];
- else if (replacementsCount >= replacements.Length)
- {
- int[] newArray = new int[replacements.Length * 3 / 2 + 4]; // grow by 1.5X but more in the begining
- Array.Copy(replacements, newArray, replacements.Length);
- replacements = newArray;
- }
- replacements[replacementsCount++] = indexInChunk;
- indexInChunk += oldValue.Length;
- count -= oldValue.Length;
- }
- else
- {
- indexInChunk++;
- --count;
- }
-
- if (indexInChunk >= chunk.m_ChunkLength || count == 0) // Have we moved out of the current chunk
- {
- // Replacing mutates the blocks, so we need to convert to logical index and back afterward.
- int index = indexInChunk + chunk.m_ChunkOffset;
- int indexBeforeAdjustment = index;
-
- // See if we accumulated any replacements, if so apply them
- ReplaceAllInChunk(replacements, replacementsCount, chunk, oldValue.Length, newValue);
- // The replacement has affected the logical index. Adjust it.
- index += ((newValue.Length - oldValue.Length) * replacementsCount);
- replacementsCount = 0;
-
- chunk = FindChunkForIndex(index);
- indexInChunk = index - chunk.m_ChunkOffset;
- Debug.Assert(chunk != null || count == 0, "Chunks ended prematurely");
- }
- }
- VerifyClassInvariant();
- return this;
- }
-
- // Returns a StringBuilder with all instances of oldChar replaced with
- // newChar. The size of the StringBuilder is unchanged because we're only
- // replacing characters. If startIndex and count are specified, we
- // only replace characters in the range from startIndex to startIndex+count
- //
- public StringBuilder Replace(char oldChar, char newChar) {
- return Replace(oldChar, newChar, 0, Length);
- }
- public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) {
- Contract.Ensures(Contract.Result<StringBuilder>() != null);
-
- int currentLength = Length;
- if ((uint)startIndex > (uint)currentLength) {
- throw new ArgumentOutOfRangeException(nameof(startIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (count < 0 || startIndex > currentLength - count) {
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- int endIndex = startIndex + count;
- StringBuilder chunk = this;
- for (; ; )
- {
- int endIndexInChunk = endIndex - chunk.m_ChunkOffset;
- int startIndexInChunk = startIndex - chunk.m_ChunkOffset;
- if (endIndexInChunk >= 0)
- {
- int curInChunk = Math.Max(startIndexInChunk, 0);
- int endInChunk = Math.Min(chunk.m_ChunkLength, endIndexInChunk);
- while (curInChunk < endInChunk)
- {
- if (chunk.m_ChunkChars[curInChunk] == oldChar)
- chunk.m_ChunkChars[curInChunk] = newChar;
- curInChunk++;
- }
- }
- if (startIndexInChunk >= 0)
- break;
- chunk = chunk.m_ChunkPrevious;
- }
- return this;
- }
-
- /// <summary>
- /// Appends 'value' of length 'count' to the stringBuilder.
- /// </summary>
- [System.CLSCompliantAttribute(false)]
- public unsafe StringBuilder Append(char* value, int valueCount)
- {
- // We don't check null value as this case will throw null reference exception anyway
- if (valueCount < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_NegativeCount"));
- }
-
- // this is where we can check if the valueCount will put us over m_MaxCapacity
- // We are doing the check here to prevent the corruption of the StringBuilder.
- int newLength = Length + valueCount;
- if (newLength > m_MaxCapacity || newLength < valueCount) {
- throw new ArgumentOutOfRangeException(nameof(valueCount), Environment.GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"));
- }
-
- // This case is so common we want to optimize for it heavily.
- int newIndex = valueCount + m_ChunkLength;
- if (newIndex <= m_ChunkChars.Length)
- {
- ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, valueCount);
- m_ChunkLength = newIndex;
- }
- else
- {
- // Copy the first chunk
- int firstLength = m_ChunkChars.Length - m_ChunkLength;
- if (firstLength > 0)
- {
- ThreadSafeCopy(value, m_ChunkChars, m_ChunkLength, firstLength);
- m_ChunkLength = m_ChunkChars.Length;
- }
-
- // Expand the builder to add another chunk.
- int restLength = valueCount - firstLength;
- ExpandByABlock(restLength);
- Debug.Assert(m_ChunkLength == 0, "Expand did not make a new block");
-
- // Copy the second chunk
- ThreadSafeCopy(value + firstLength, m_ChunkChars, 0, restLength);
- m_ChunkLength = restLength;
- }
- VerifyClassInvariant();
- return this;
- }
-
- /// <summary>
- /// Inserts 'value' of length 'cou
- /// </summary>
- unsafe private void Insert(int index, char* value, int valueCount)
- {
- if ((uint)index > (uint)Length)
- {
- throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
-
- if (valueCount > 0)
- {
- StringBuilder chunk;
- int indexInChunk;
- MakeRoom(index, valueCount, out chunk, out indexInChunk, false);
- ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value, valueCount);
- }
- }
-
- /// <summary>
- /// 'replacements' is a list of index (relative to the begining of the 'chunk' to remove
- /// 'removeCount' characters and replace them with 'value'. This routine does all those
- /// replacements in bulk (and therefore very efficiently.
- /// with the string 'value'.
- /// </summary>
- private void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value)
- {
- if (replacementsCount <= 0)
- return;
-
- unsafe {
- fixed (char* valuePtr = value)
- {
- // calculate the total amount of extra space or space needed for all the replacements.
- int delta = (value.Length - removeCount) * replacementsCount;
-
- StringBuilder targetChunk = sourceChunk; // the target as we copy chars down
- int targetIndexInChunk = replacements[0];
-
- // Make the room needed for all the new characters if needed.
- if (delta > 0)
- MakeRoom(targetChunk.m_ChunkOffset + targetIndexInChunk, delta, out targetChunk, out targetIndexInChunk, true);
- // We made certain that characters after the insertion point are not moved,
- int i = 0;
- for (; ; )
- {
- // Copy in the new string for the ith replacement
- ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, valuePtr, value.Length);
- int gapStart = replacements[i] + removeCount;
- i++;
- if (i >= replacementsCount)
- break;
-
- int gapEnd = replacements[i];
- Debug.Assert(gapStart < sourceChunk.m_ChunkChars.Length, "gap starts at end of buffer. Should not happen");
- Debug.Assert(gapStart <= gapEnd, "negative gap size");
- 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
- fixed (char* sourcePtr = &sourceChunk.m_ChunkChars[gapStart])
- ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart);
- }
- else
- {
- targetIndexInChunk += gapEnd - gapStart;
- Debug.Assert(targetIndexInChunk <= targetChunk.m_ChunkLength, "gap not in chunk");
- }
- }
-
- // Remove extra space if necessary.
- if (delta < 0)
- Remove(targetChunk.m_ChunkOffset + targetIndexInChunk, -delta, out targetChunk, out targetIndexInChunk);
- }
- }
- }
-
- /// <summary>
- /// Returns true if the string that is starts at 'chunk' and 'indexInChunk, and has a logical
- /// length of 'count' starts with the string 'value'.
- /// </summary>
- private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, string value)
- {
- for (int i = 0; i < value.Length; i++)
- {
- if (count == 0)
- return false;
- if (indexInChunk >= chunk.m_ChunkLength)
- {
- chunk = Next(chunk);
- if (chunk == null)
- return false;
- indexInChunk = 0;
- }
-
- // See if there no match, break out of the inner for loop
- if (value[i] != chunk.m_ChunkChars[indexInChunk])
- return false;
-
- indexInChunk++;
- --count;
- }
- return true;
- }
-
- /// <summary>
- /// ReplaceInPlaceAtChunk is the logical equivalent of 'memcpy'. Given a chunk and ann index in
- /// that chunk, it copies in 'count' characters from 'value' and updates 'chunk, and indexInChunk to
- /// point at the end of the characters just copyied (thus you can splice in strings from multiple
- /// places by calling this mulitple times.
- /// </summary>
- unsafe private void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count)
- {
- if (count != 0)
- {
- for (; ; )
- {
- int lengthInChunk = chunk.m_ChunkLength - indexInChunk;
- Debug.Assert(lengthInChunk >= 0, "index not in chunk");
-
- int lengthToCopy = Math.Min(lengthInChunk, count);
- ThreadSafeCopy(value, chunk.m_ChunkChars, indexInChunk, lengthToCopy);
-
- // Advance the index.
- indexInChunk += lengthToCopy;
- if (indexInChunk >= chunk.m_ChunkLength)
- {
- chunk = Next(chunk);
- indexInChunk = 0;
- }
- count -= lengthToCopy;
- if (count == 0)
- break;
- value += lengthToCopy;
- }
- }
- }
-
- /// <summary>
- /// We have to prevent modification off the end of an array.
- /// The only way to do this is to copy all interesting variables out of the heap and then do the
- /// bounds check. This is what we do here.
- /// </summary>
- unsafe private static void ThreadSafeCopy(char* sourcePtr, char[] destination, int destinationIndex, int count)
- {
- if (count > 0)
- {
- if ((uint)destinationIndex <= (uint)destination.Length && (destinationIndex + count) <= destination.Length)
- {
- fixed (char* destinationPtr = &destination[destinationIndex])
- string.wstrcpy(destinationPtr, sourcePtr, count);
- }
- else
- {
- throw new ArgumentOutOfRangeException(nameof(destinationIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- }
- }
- private static void ThreadSafeCopy(char[] source, int sourceIndex, char[] destination, int destinationIndex, int count)
- {
- if (count > 0)
- {
- if ((uint)sourceIndex <= (uint)source.Length && (sourceIndex + count) <= source.Length)
- {
- unsafe {
- fixed (char* sourcePtr = &source[sourceIndex])
- ThreadSafeCopy(sourcePtr, destination, destinationIndex, count);
- }
- }
- else
- {
- throw new ArgumentOutOfRangeException(nameof(sourceIndex), Environment.GetResourceString("ArgumentOutOfRange_Index"));
- }
- }
- }
-
- // Copies the source StringBuilder to the destination IntPtr memory allocated with len bytes.
- internal unsafe void InternalCopy(IntPtr dest, int len) {
- if(len ==0)
- return;
-
- bool isLastChunk = true;
- byte* dstPtr = (byte*) dest.ToPointer();
- StringBuilder currentSrc = FindChunkForByte(len);
-
- do {
- int chunkOffsetInBytes = currentSrc.m_ChunkOffset*sizeof(char);
- int chunkLengthInBytes = currentSrc.m_ChunkLength*sizeof(char);
- fixed(char* charPtr = &currentSrc.m_ChunkChars[0]) {
- byte* srcPtr = (byte*) charPtr;
- if(isLastChunk) {
- isLastChunk= false;
- Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, len - chunkOffsetInBytes);
- } else {
- Buffer.Memcpy(dstPtr + chunkOffsetInBytes, srcPtr, chunkLengthInBytes);
- }
- }
- currentSrc = currentSrc.m_ChunkPrevious;
- } while(currentSrc != null);
- }
-
- /// <summary>
- /// Finds the chunk for the logical index (number of characters in the whole stringbuilder) 'index'
- /// YOu can then get the offset in this chunk by subtracting the m_BlockOffset field from 'index'
- /// </summary>
- /// <param name="index"></param>
- /// <returns></returns>
- private StringBuilder FindChunkForIndex(int index)
- {
- Debug.Assert(0 <= index && index <= Length, "index not in string");
-
- StringBuilder ret = this;
- while (ret.m_ChunkOffset > index)
- ret = ret.m_ChunkPrevious;
-
- Debug.Assert(ret != null, "index not in string");
- return ret;
- }
-
- /// <summary>
- /// Finds the chunk for the logical byte index 'byteIndex'
- /// </summary>
- /// <param name="index"></param>
- /// <returns></returns>
- private StringBuilder FindChunkForByte(int byteIndex)
- {
- Debug.Assert(0 <= byteIndex && byteIndex <= Length*sizeof(char), "Byte Index not in string");
-
- StringBuilder ret = this;
- while (ret.m_ChunkOffset*sizeof(char) > byteIndex)
- ret = ret.m_ChunkPrevious;
-
- Debug.Assert(ret != null, "Byte Index not in string");
- return ret;
- }
-
- /// <summary>
- /// Finds the chunk that logically follows the 'chunk' chunk. Chunks only persist the pointer to
- /// the chunk that is logically before it, so this routine has to start at the this pointer (which
- /// is a assumed to point at the chunk representing the whole stringbuilder) and search
- /// until it finds the current chunk (thus is O(n)). So it is more expensive than a field fetch!
- /// </summary>
- private StringBuilder Next(StringBuilder chunk)
- {
- if (chunk == this)
- return null;
- return FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength);
- }
-
- /// <summary>
- /// Assumes that 'this' is the last chunk in the list and that it is full. Upon return the 'this'
- /// block is updated so that it is a new block that has at least 'minBlockCharCount' characters.
- /// that can be used to copy characters into it.
- /// </summary>
- private void ExpandByABlock(int minBlockCharCount)
- {
- Contract.Requires(Capacity == Length, "Expand expect to be called only when there is no space left"); // We are currently full
- Contract.Requires(minBlockCharCount > 0, "Expansion request must be positive");
-
- VerifyClassInvariant();
-
- if ((minBlockCharCount + Length) > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount)
- throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
-
- // Compute the length of the new block we need
- // We make the new chunk at least big enough for the current need (minBlockCharCount)
- // But also as big as the current length (thus doubling capacity), up to a maximum
- // (so we stay in the small object heap, and never allocate really big chunks even if
- // the string gets really big.
- int newBlockLength = Math.Max(minBlockCharCount, Math.Min(Length, MaxChunkSize));
-
- // Copy the current block to the new block, and initialize this to point at the new buffer.
- m_ChunkPrevious = new StringBuilder(this);
- m_ChunkOffset += m_ChunkLength;
- m_ChunkLength = 0;
-
- // Check for integer overflow (logical buffer size > int.MaxInt)
- if (m_ChunkOffset + newBlockLength < newBlockLength)
- {
- m_ChunkChars = null;
- throw new OutOfMemoryException();
- }
- m_ChunkChars = new char[newBlockLength];
-
- VerifyClassInvariant();
- }
-
- /// <summary>
- /// Used by ExpandByABlock to create a new chunk. The new chunk is a copied from 'from'
- /// In particular the buffer is shared. It is expected that 'from' chunk (which represents
- /// the whole list, is then updated to point to point to this new chunk.
- /// </summary>
- private StringBuilder(StringBuilder from)
- {
- m_ChunkLength = from.m_ChunkLength;
- m_ChunkOffset = from.m_ChunkOffset;
- m_ChunkChars = from.m_ChunkChars;
- m_ChunkPrevious = from.m_ChunkPrevious;
- m_MaxCapacity = from.m_MaxCapacity;
- VerifyClassInvariant();
- }
-
- /// <summary>
- /// Creates a gap of size 'count' at the logical offset (count of characters in the whole string
- /// builder) 'index'. It returns the 'chunk' and 'indexInChunk' which represents a pointer to
- /// this gap that was just created. You can then use 'ReplaceInPlaceAtChunk' to fill in the
- /// chunk
- ///
- /// ReplaceAllChunks relies on the fact that indexes above 'index' are NOT moved outside 'chunk'
- /// by this process (because we make the space by creating the cap BEFORE the chunk). If we
- /// change this ReplaceAllChunks needs to be updated.
- ///
- /// If dontMoveFollowingChars is true, then the room must be made by inserting a chunk BEFORE the
- /// current chunk (this is what it does most of the time anyway)
- /// </summary>
- private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doneMoveFollowingChars)
- {
- VerifyClassInvariant();
- Debug.Assert(count > 0, "Count must be strictly positive");
- Debug.Assert(index >= 0, "Index can't be negative");
- if (count + Length > m_MaxCapacity || count + Length < count)
- throw new ArgumentOutOfRangeException("requiredLength", Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
-
- chunk = this;
- while (chunk.m_ChunkOffset > index)
- {
- chunk.m_ChunkOffset += count;
- chunk = chunk.m_ChunkPrevious;
- }
- indexInChunk = index - chunk.m_ChunkOffset;
-
- // Cool, we have some space in this block, and you don't have to copy much to get it, go ahead
- // and use it. This happens typically when you repeatedly insert small strings at a spot
- // (typically the absolute front) of the buffer.
- if (!doneMoveFollowingChars && chunk.m_ChunkLength <= DefaultCapacity * 2 && chunk.m_ChunkChars.Length - chunk.m_ChunkLength >= count)
- {
- for (int i = chunk.m_ChunkLength; i > indexInChunk; )
- {
- --i;
- chunk.m_ChunkChars[i + count] = chunk.m_ChunkChars[i];
- }
- chunk.m_ChunkLength += count;
- return;
- }
-
- // Allocate space for the new chunk (will go before this one)
- StringBuilder newChunk = new StringBuilder(Math.Max(count, DefaultCapacity), chunk.m_MaxCapacity, chunk.m_ChunkPrevious);
- newChunk.m_ChunkLength = count;
-
- // Copy the head of the buffer to the new buffer.
- int copyCount1 = Math.Min(count, indexInChunk);
- if (copyCount1 > 0)
- {
- unsafe {
- fixed (char* chunkCharsPtr = &chunk.m_ChunkChars[0]) {
- ThreadSafeCopy(chunkCharsPtr, newChunk.m_ChunkChars, 0, copyCount1);
-
- // Slide characters in the current buffer over to make room.
- int copyCount2 = indexInChunk - copyCount1;
- if (copyCount2 >= 0)
- {
- ThreadSafeCopy(chunkCharsPtr + copyCount1, chunk.m_ChunkChars, 0, copyCount2);
- indexInChunk = copyCount2;
- }
- }
- }
- }
-
- chunk.m_ChunkPrevious = newChunk; // Wire in the new chunk
- chunk.m_ChunkOffset += count;
- if (copyCount1 < count)
- {
- chunk = newChunk;
- indexInChunk = copyCount1;
- }
-
- VerifyClassInvariant();
- }
-
- /// <summary>
- /// Used by MakeRoom to allocate another chunk.
- /// </summary>
- private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock)
- {
- Debug.Assert(size > 0, "size not positive");
- Debug.Assert(maxCapacity > 0, "maxCapacity not positive");
- m_ChunkChars = new char[size];
- m_MaxCapacity = maxCapacity;
- m_ChunkPrevious = previousBlock;
- if (previousBlock != null)
- m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength;
- VerifyClassInvariant();
- }
-
- /// <summary>
- /// Removes 'count' characters from the logical index 'startIndex' and returns the chunk and
- /// index in the chunk of that logical index in the out parameters.
- /// </summary>
- private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk)
- {
- VerifyClassInvariant();
- Debug.Assert(startIndex >= 0 && startIndex < Length, "startIndex not in string");
-
- int endIndex = startIndex + count;
-
- // Find the chunks for the start and end of the block to delete.
- chunk = this;
- StringBuilder endChunk = null;
- int endIndexInChunk = 0;
- for (; ; )
- {
- if (endIndex - chunk.m_ChunkOffset >= 0)
- {
- if (endChunk == null)
- {
- endChunk = chunk;
- endIndexInChunk = endIndex - endChunk.m_ChunkOffset;
- }
- if (startIndex - chunk.m_ChunkOffset >= 0)
- {
- indexInChunk = startIndex - chunk.m_ChunkOffset;
- break;
- }
- }
- else
- {
- chunk.m_ChunkOffset -= count;
- }
- chunk = chunk.m_ChunkPrevious;
- }
- Debug.Assert(chunk != null, "fell off beginning of string!");
-
- int copyTargetIndexInChunk = indexInChunk;
- int copyCount = endChunk.m_ChunkLength - endIndexInChunk;
- if (endChunk != chunk)
- {
- copyTargetIndexInChunk = 0;
- // Remove the characters after startIndex to end of the chunk
- chunk.m_ChunkLength = indexInChunk;
-
- // Remove the characters in chunks between start and end chunk
- endChunk.m_ChunkPrevious = chunk;
- endChunk.m_ChunkOffset = chunk.m_ChunkOffset + chunk.m_ChunkLength;
-
- // If the start is 0 then we can throw away the whole start chunk
- if (indexInChunk == 0)
- {
- endChunk.m_ChunkPrevious = chunk.m_ChunkPrevious;
- chunk = endChunk;
- }
- }
- endChunk.m_ChunkLength -= (endIndexInChunk - copyTargetIndexInChunk);
-
- // SafeCritical: We ensure that endIndexInChunk + copyCount is within range of m_ChunkChars and
- // also ensure that copyTargetIndexInChunk + copyCount is within the chunk
- //
- // Remove any characters in the end chunk, by sliding the characters down.
- if (copyTargetIndexInChunk != endIndexInChunk) // Sometimes no move is necessary
- ThreadSafeCopy(endChunk.m_ChunkChars, endIndexInChunk, endChunk.m_ChunkChars, copyTargetIndexInChunk, copyCount);
-
- Debug.Assert(chunk != null, "fell off beginning of string!");
- VerifyClassInvariant();
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/StringBuilderCache.cs b/src/mscorlib/src/System/Text/StringBuilderCache.cs
index 16a786d54e..a8a5e2c7f4 100644
--- a/src/mscorlib/src/System/Text/StringBuilderCache.cs
+++ b/src/mscorlib/src/System/Text/StringBuilderCache.cs
@@ -31,6 +31,7 @@
** cache and return the resulting string
**
===========================================================*/
+
using System.Threading;
namespace System.Text
@@ -47,14 +48,14 @@ namespace System.Text
public static StringBuilder Acquire(int capacity = StringBuilder.DefaultCapacity)
{
- if(capacity <= MAX_BUILDER_SIZE)
+ if (capacity <= MAX_BUILDER_SIZE)
{
StringBuilder sb = StringBuilderCache.CachedInstance;
if (sb != null)
{
// Avoid stringbuilder block fragmentation by getting a new StringBuilder
// when the requested size is larger than the current capacity
- if(capacity <= sb.Capacity)
+ if (capacity <= sb.Capacity)
{
StringBuilderCache.CachedInstance = null;
sb.Clear();
diff --git a/src/mscorlib/src/System/Text/UTF32Encoding.cs b/src/mscorlib/src/System/Text/UTF32Encoding.cs
deleted file mode 100644
index a7ac1d8539..0000000000
--- a/src/mscorlib/src/System/Text/UTF32Encoding.cs
+++ /dev/null
@@ -1,1003 +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.
-
-//
-// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
-//
-
-namespace System.Text
-{
-
- using System;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Globalization;
- // Encodes text into and out of UTF-32. UTF-32 is a way of writing
- // Unicode characters with a single storage unit (32 bits) per character,
- //
- // The UTF-32 byte order mark is simply the Unicode byte order mark
- // (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order
- // mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't
- // switch the byte orderings.
-
- [Serializable]
- public sealed class UTF32Encoding : Encoding
- {
- /*
- words bits UTF-32 representation
- ----- ---- -----------------------------------
- 1 16 00000000 00000000 xxxxxxxx xxxxxxxx
- 2 21 00000000 000xxxxx hhhhhhll llllllll
- ----- ---- -----------------------------------
-
- Surrogate:
- Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
- */
-
- // Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization
- // The initialization code will not be run until a static member of the class is referenced
- 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 bool emitUTF32ByteOrderMark = false;
- private bool isThrowException = false;
- private bool bigEndian = false;
-
-
- public UTF32Encoding(): this(false, true, false)
- {
- }
-
-
- public UTF32Encoding(bool bigEndian, bool byteOrderMark):
- this(bigEndian, byteOrderMark, false)
- {
- }
-
-
- public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters):
- base(bigEndian ? 12001 : 12000)
- {
- this.bigEndian = bigEndian;
- this.emitUTF32ByteOrderMark = byteOrderMark;
- this.isThrowException = throwOnInvalidCharacters;
-
- // Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
- if (this.isThrowException)
- SetDefaultFallbacks();
- }
-
- internal override void SetDefaultFallbacks()
- {
- // For UTF-X encodings, we use a replacement fallback with an empty string
- if (this.isThrowException)
- {
- this.encoderFallback = EncoderFallback.ExceptionFallback;
- this.decoderFallback = DecoderFallback.ExceptionFallback;
- }
- else
- {
- this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
- this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
- }
- }
-
- // NOTE: Many methods in this class forward to EncodingForwarder for
- // validating arguments/wrapping the unsafe methods in this class
- // which do the actual work. That class contains
- // shared logic for doing this which is used by
- // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
- // UTF7Encoding, and UTF8Encoding.
- // The reason the code is separated out into a static class, rather
- // than a base class which overrides all of these methods for us
- // (which is what EncodingNLS is for internal Encodings) is because
- // that's really more of an implementation detail so it's internal.
- // At the same time, C# doesn't allow a public class subclassing an
- // internal/private one, so we end up having to re-override these
- // methods in all of the public Encodings + EncodingNLS.
-
- // Returns the number of bytes required to encode a range of characters in
- // a character array.
-
- public override int GetByteCount(char[] chars, int index, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, index, count);
- }
-
- public override int GetByteCount(String s)
- {
- return EncodingForwarder.GetByteCount(this, s);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetByteCount(char* chars, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, count);
- }
-
- public override int GetBytes(String s, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
- }
-
- // Encodes a range of characters in a character array into a range of bytes
- // in a byte array. An exception occurs if the byte array is not large
- // enough to hold the complete encoding of the characters. The
- // GetByteCount method can be used to determine the exact number of
- // bytes that will be produced for a given range of characters.
- // Alternatively, the GetMaxByteCount method can be used to
- // determine the maximum number of bytes that will be produced for a given
- // number of characters, regardless of the actual character values.
-
- public override int GetBytes(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
- {
- return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
- }
-
- // Returns the number of characters produced by decoding a range of bytes
- // in a byte array.
-
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, index, count);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetCharCount(byte* bytes, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, count);
- }
-
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex)
- {
- return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
- }
-
- [CLSCompliant(false)]
- public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
- {
- return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
- }
-
- // Returns a string containing the decoded representation of a range of
- // bytes in a byte array.
-
- public override String GetString(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetString(this, bytes, index, count);
- }
-
- // End of overridden methods which use EncodingForwarder
-
- internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS encoder)
- {
- Debug.Assert(chars!=null, "[UTF32Encoding.GetByteCount]chars!=null");
- Debug.Assert(count >=0, "[UTF32Encoding.GetByteCount]count >=0");
-
- char* end = chars + count;
- char* charStart = chars;
- int byteCount = 0;
-
- char highSurrogate = '\0';
-
- // For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
- if (encoder != null)
- {
- highSurrogate = encoder.charLeftOver;
- fallbackBuffer = encoder.FallbackBuffer;
-
- // We mustn't have left over fallback data when counting
- if (fallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
- }
- else
- {
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- }
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, end, encoder, false);
-
- char ch;
- TryAgain:
-
- while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // Do we need a low surrogate?
- if (highSurrogate != '\0')
- {
- //
- // In previous char, we encounter a high surrogate, so we are expecting a low surrogate here.
- //
- if (Char.IsLowSurrogate(ch))
- {
- // They're all legal
- highSurrogate = '\0';
-
- //
- // One surrogate pair will be translated into 4 bytes UTF32.
- //
-
- byteCount += 4;
- continue;
- }
-
- // We are missing our low surrogate, decrement chars and fallback the high surrogate
- // The high surrogate may have come from the encoder, but nothing else did.
- Debug.Assert(chars > charStart,
- "[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate");
- chars--;
-
- // Do the fallback
- fallbackBuffer.InternalFallback(highSurrogate, ref chars);
-
- // We're going to fallback the old high surrogate.
- highSurrogate = '\0';
- continue;
-
- }
-
- // Do we have another high surrogate?
- if (Char.IsHighSurrogate(ch))
- {
- //
- // We'll have a high surrogate to check next time.
- //
- highSurrogate = ch;
- continue;
- }
-
- // Check for illegal characters
- if (Char.IsLowSurrogate(ch))
- {
- // We have a leading low surrogate, do the fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
-
- // Try again with fallback buffer
- continue;
- }
-
- // We get to add the character (4 bytes UTF32)
- byteCount += 4;
- }
-
- // May have to do our last surrogate
- if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
- {
- // We have to do the fallback for the lonely high surrogate
- fallbackBuffer.InternalFallback(highSurrogate, ref chars);
- highSurrogate = (char)0;
- goto TryAgain;
- }
-
- // Check for overflows.
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString(
- "ArgumentOutOfRange_GetByteCountOverflow"));
-
- // Shouldn't have anything in fallback buffer for GetByteCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(fallbackBuffer.Remaining == 0,
- "[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end");
-
- // Return our count
- return byteCount;
- }
-
- internal override unsafe int GetBytes(char *chars, int charCount,
- byte* bytes, int byteCount, EncoderNLS encoder)
- {
- Debug.Assert(chars!=null, "[UTF32Encoding.GetBytes]chars!=null");
- Debug.Assert(bytes!=null, "[UTF32Encoding.GetBytes]bytes!=null");
- Debug.Assert(byteCount >=0, "[UTF32Encoding.GetBytes]byteCount >=0");
- Debug.Assert(charCount >=0, "[UTF32Encoding.GetBytes]charCount >=0");
-
- char* charStart = chars;
- char* charEnd = chars + charCount;
- byte* byteStart = bytes;
- byte* byteEnd = bytes + byteCount;
-
- char highSurrogate = '\0';
-
- // For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
- if (encoder != null)
- {
- highSurrogate = encoder.charLeftOver;
- fallbackBuffer = encoder.FallbackBuffer;
-
- // We mustn't have left over fallback data when not converting
- if (encoder.m_throwOnOverflow && fallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
- }
- else
- {
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- }
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
-
- char ch;
- TryAgain:
-
- while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // Do we need a low surrogate?
- if (highSurrogate != '\0')
- {
- //
- // In previous char, we encountered a high surrogate, so we are expecting a low surrogate here.
- //
- if (Char.IsLowSurrogate(ch))
- {
- // Is it a legal one?
- uint iTemp = GetSurrogate(highSurrogate, ch);
- highSurrogate = '\0';
-
- //
- // One surrogate pair will be translated into 4 bytes UTF32.
- //
- if (bytes+3 >= byteEnd)
- {
- // Don't have 4 bytes
- if (fallbackBuffer.bFallingBack)
- {
- fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars
- fallbackBuffer.MovePrevious();
- }
- else
- {
- // If we don't have enough room, then either we should've advanced a while
- // or we should have bytes==byteStart and throw below
- Debug.Assert(chars > charStart + 1 || bytes == byteStart,
- "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
- chars-=2; // Aren't using those 2 chars
- }
- ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
- highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary)
- break;
- }
-
- if (bigEndian)
- {
- *(bytes++) = (byte)(0x00);
- *(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
- *(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
- *(bytes++) = (byte)(iTemp); // Implies & 0xFF
- }
- else
- {
- *(bytes++) = (byte)(iTemp); // Implies & 0xFF
- *(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF
- *(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0
- *(bytes++) = (byte)(0x00);
- }
- continue;
- }
-
- // We are missing our low surrogate, decrement chars and fallback the high surrogate
- // The high surrogate may have come from the encoder, but nothing else did.
- Debug.Assert(chars > charStart,
- "[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate");
- chars--;
-
- // Do the fallback
- fallbackBuffer.InternalFallback(highSurrogate, ref chars);
-
- // We're going to fallback the old high surrogate.
- highSurrogate = '\0';
- continue;
- }
-
- // Do we have another high surrogate?, if so remember it
- if (Char.IsHighSurrogate(ch))
- {
- //
- // We'll have a high surrogate to check next time.
- //
- highSurrogate = ch;
- continue;
- }
-
- // Check for illegal characters (low surrogate)
- if (Char.IsLowSurrogate(ch))
- {
- // We have a leading low surrogate, do the fallback
- fallbackBuffer.InternalFallback(ch, ref chars);
-
- // Try again with fallback buffer
- continue;
- }
-
- // We get to add the character, yippee.
- if (bytes+3 >= byteEnd)
- {
- // Don't have 4 bytes
- if (fallbackBuffer.bFallingBack)
- fallbackBuffer.MovePrevious(); // Aren't using this fallback char
- else
- {
- // Must've advanced already
- Debug.Assert(chars > charStart,
- "[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character");
- chars--; // Aren't using this char
- }
- ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
- break; // Didn't throw, stop
- }
-
- if (bigEndian)
- {
- *(bytes++) = (byte)(0x00);
- *(bytes++) = (byte)(0x00);
- *(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
- *(bytes++) = (byte)(ch); // Implies & 0xFF
- }
- else
- {
- *(bytes++) = (byte)(ch); // Implies & 0xFF
- *(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF
- *(bytes++) = (byte)(0x00);
- *(bytes++) = (byte)(0x00);
- }
- }
-
- // May have to do our last surrogate
- if ((encoder == null || encoder.MustFlush) && highSurrogate > 0)
- {
- // We have to do the fallback for the lonely high surrogate
- fallbackBuffer.InternalFallback(highSurrogate, ref chars);
- highSurrogate = (char)0;
- goto TryAgain;
- }
-
- // Fix our encoder if we have one
- Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush),
- "[UTF32Encoding.GetBytes]Expected encoder to be flushed.");
-
- if (encoder != null)
- {
- // Remember our left over surrogate (or 0 if flushing)
- encoder.charLeftOver = highSurrogate;
-
- // Need # chars used
- encoder.m_charsUsed = (int)(chars-charStart);
- }
-
- // return the new length
- return (int)(bytes - byteStart);
- }
-
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
- {
- Debug.Assert(bytes!=null, "[UTF32Encoding.GetCharCount]bytes!=null");
- Debug.Assert(count >=0, "[UTF32Encoding.GetCharCount]count >=0");
-
- UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
-
- // None so far!
- int charCount = 0;
- byte* end = bytes + count;
- byte* byteStart = bytes;
-
- // Set up decoder
- int readCount = 0;
- uint iChar = 0;
-
- // For fallback we may need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
-
- // See if there's anything in our decoder
- if (decoder != null)
- {
- readCount = decoder.readByteCount;
- iChar = (uint)decoder.iChar;
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for chars or count)
- Debug.Assert(fallbackBuffer.Remaining == 0,
- "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start");
- }
- else
- {
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- }
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, null);
-
- // Loop through our input, 4 characters at a time!
- while (bytes < end && charCount >= 0)
- {
- // Get our next character
- if(bigEndian)
- {
- // Scoot left and add it to the bottom
- iChar <<= 8;
- iChar += *(bytes++);
- }
- else
- {
- // Scoot right and add it to the top
- iChar >>= 8;
- iChar += (uint)(*(bytes++)) << 24;
- }
-
- readCount++;
-
- // See if we have all the bytes yet
- if (readCount < 4)
- continue;
-
- // Have the bytes
- readCount = 0;
-
- // See if its valid to encode
- if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
- {
- // Need to fall back these 4 bytes
- byte[] fallbackBytes;
- if (this.bigEndian)
- {
- fallbackBytes = new byte[] {
- unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
- unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
- }
- else
- {
- fallbackBytes = new byte[] {
- unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
- unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
- }
-
- charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
-
- // Ignore the illegal character
- iChar = 0;
- continue;
- }
-
- // Ok, we have something we can add to our output
- if (iChar >= 0x10000)
- {
- // Surrogates take 2
- charCount++;
- }
-
- // Add the rest of the surrogate or our normal character
- charCount++;
-
- // iChar is back to 0
- iChar = 0;
- }
-
- // See if we have something left over that has to be decoded
- if (readCount > 0 && (decoder == null || decoder.MustFlush))
- {
- // Oops, there's something left over with no place to go.
- byte[] fallbackBytes = new byte[readCount];
- if (this.bigEndian)
- {
- while(readCount > 0)
- {
- fallbackBytes[--readCount] = unchecked((byte)iChar);
- iChar >>= 8;
- }
- }
- else
- {
- while (readCount > 0)
- {
- fallbackBytes[--readCount] = unchecked((byte)(iChar>>24));
- iChar <<= 8;
- }
- }
-
- charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes);
- }
-
- // Check for overflows.
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for chars or count)
- Debug.Assert(fallbackBuffer.Remaining == 0,
- "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end");
-
- // Return our count
- return charCount;
- }
-
- internal override unsafe int GetChars(byte* bytes, int byteCount,
- char* chars, int charCount, DecoderNLS baseDecoder)
- {
- Debug.Assert(chars!=null, "[UTF32Encoding.GetChars]chars!=null");
- Debug.Assert(bytes!=null, "[UTF32Encoding.GetChars]bytes!=null");
- Debug.Assert(byteCount >=0, "[UTF32Encoding.GetChars]byteCount >=0");
- Debug.Assert(charCount >=0, "[UTF32Encoding.GetChars]charCount >=0");
-
- UTF32Decoder decoder = (UTF32Decoder)baseDecoder;
-
- // None so far!
- char* charStart = chars;
- char* charEnd = chars + charCount;
-
- byte* byteStart = bytes;
- byte* byteEnd = bytes + byteCount;
-
- // See if there's anything in our decoder (but don't clear it yet)
- int readCount = 0;
- uint iChar = 0;
-
- // For fallback we may need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
-
- // See if there's anything in our decoder
- if (decoder != null)
- {
- readCount = decoder.readByteCount;
- iChar = (uint)decoder.iChar;
- fallbackBuffer = baseDecoder.FallbackBuffer;
-
- // Shouldn't have anything in fallback buffer for GetChars
- // (don't have to check m_throwOnOverflow for chars)
- Debug.Assert(fallbackBuffer.Remaining == 0,
- "[UTF32Encoding.GetChars]Expected empty fallback buffer at start");
- }
- else
- {
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- }
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(bytes, chars + charCount);
-
- // Loop through our input, 4 characters at a time!
- while (bytes < byteEnd)
- {
- // Get our next character
- if(bigEndian)
- {
- // Scoot left and add it to the bottom
- iChar <<= 8;
- iChar += *(bytes++);
- }
- else
- {
- // Scoot right and add it to the top
- iChar >>= 8;
- iChar += (uint)(*(bytes++)) << 24;
- }
-
- readCount++;
-
- // See if we have all the bytes yet
- if (readCount < 4)
- continue;
-
- // Have the bytes
- readCount = 0;
-
- // See if its valid to encode
- if ( iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF))
- {
- // Need to fall back these 4 bytes
- byte[] fallbackBytes;
- if (this.bigEndian)
- {
- fallbackBytes = new byte[] {
- unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)),
- unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) };
- }
- else
- {
- fallbackBytes = new byte[] {
- unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)),
- unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) };
- }
-
- // Chars won't be updated unless this works.
- if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
- {
- // Couldn't fallback, throw or wait til next time
- // We either read enough bytes for bytes-=4 to work, or we're
- // going to throw in ThrowCharsOverflow because chars == charStart
- Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
- "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)");
- bytes-=4; // get back to where we were
- iChar=0; // Remembering nothing
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // Stop here, didn't throw
- }
-
- // Ignore the illegal character
- iChar = 0;
- continue;
- }
-
-
- // Ok, we have something we can add to our output
- if (iChar >= 0x10000)
- {
- // Surrogates take 2
- if (chars >= charEnd - 1)
- {
- // Throwing or stopping
- // We either read enough bytes for bytes-=4 to work, or we're
- // going to throw in ThrowCharsOverflow because chars == charStart
- Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
- "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)");
- bytes-=4; // get back to where we were
- iChar=0; // Remembering nothing
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // Stop here, didn't throw
- }
-
- *(chars++) = GetHighSurrogate(iChar);
- iChar = GetLowSurrogate(iChar);
- }
- // Bounds check for normal character
- else if (chars >= charEnd)
- {
- // Throwing or stopping
- // We either read enough bytes for bytes-=4 to work, or we're
- // going to throw in ThrowCharsOverflow because chars == charStart
- Debug.Assert(bytes >= byteStart + 4 || chars == charStart,
- "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)");
- bytes-=4; // get back to where we were
- iChar=0; // Remembering nothing
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // Stop here, didn't throw
- }
-
- // Add the rest of the surrogate or our normal character
- *(chars++) = (char)iChar;
-
- // iChar is back to 0
- iChar = 0;
- }
-
- // See if we have something left over that has to be decoded
- if (readCount > 0 && (decoder == null || decoder.MustFlush))
- {
- // Oops, there's something left over with no place to go.
- byte[] fallbackBytes = new byte[readCount];
- int tempCount = readCount;
- if (this.bigEndian)
- {
- while(tempCount > 0)
- {
- fallbackBytes[--tempCount] = unchecked((byte)iChar);
- iChar >>= 8;
- }
- }
- else
- {
- while (tempCount > 0)
- {
- fallbackBytes[--tempCount] = unchecked((byte)(iChar>>24));
- iChar <<= 8;
- }
- }
-
- if (!fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref chars))
- {
- // Couldn't fallback.
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- // Stop here, didn't throw, backed up, so still nothing in buffer
- }
- else
- {
- // Don't clear our decoder unless we could fall it back.
- // If we caught the if above, then we're a convert() and will catch this next time.
- readCount = 0;
- iChar = 0;
- }
- }
-
- // Remember any left over stuff, clearing buffer as well for MustFlush
- if (decoder != null)
- {
- decoder.iChar = (int)iChar;
- decoder.readByteCount = readCount;
- decoder.m_bytesUsed = (int)(bytes - byteStart);
- }
-
- // Shouldn't have anything in fallback buffer for GetChars
- // (don't have to check m_throwOnOverflow for chars)
- Debug.Assert(fallbackBuffer.Remaining == 0,
- "[UTF32Encoding.GetChars]Expected empty fallback buffer at end");
-
- // Return our count
- return (int)(chars - charStart);
- }
-
-
- private uint GetSurrogate(char cHigh, char cLow)
- {
- return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000;
- }
-
- private char GetHighSurrogate(uint iChar)
- {
- return (char)((iChar - 0x10000) / 0x400 + 0xD800);
- }
-
- private char GetLowSurrogate(uint iChar)
- {
- return (char)((iChar - 0x10000) % 0x400 + 0xDC00);
- }
-
-
- public override Decoder GetDecoder()
- {
- return new UTF32Decoder(this);
- }
-
-
- public override Encoder GetEncoder()
- {
- return new EncoderNLS(this);
- }
-
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // 4 bytes per char
- byteCount *= 4;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars,
- // plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char.
- // Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair
- int charCount = (byteCount / 2) + 2;
-
- // Also consider fallback because our input bytes could be out of range of unicode.
- // Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount.
- if (DecoderFallback.MaxCharCount > 2)
- {
- // Multiply time fallback size
- charCount *= DecoderFallback.MaxCharCount;
-
- // We were already figuring 2 chars per 4 bytes, but fallback will be different #
- charCount /= 2;
- }
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
-
- public override byte[] GetPreamble()
- {
- if (emitUTF32ByteOrderMark)
- {
- // Allocate new array to prevent users from modifying it.
- if (bigEndian)
- {
- return new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
- }
- else
- {
- return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF
- }
- }
- else
- return EmptyArray<Byte>.Value;
- }
-
-
- public override bool Equals(Object value)
- {
- UTF32Encoding that = value as UTF32Encoding;
- if (that != null)
- {
- return (emitUTF32ByteOrderMark == that.emitUTF32ByteOrderMark) &&
- (bigEndian == that.bigEndian) &&
-// (isThrowException == that.isThrowException) && // same as encoder/decoderfallback being exceptions
- (EncoderFallback.Equals(that.EncoderFallback)) &&
- (DecoderFallback.Equals(that.DecoderFallback));
- }
- return (false);
- }
-
-
- public override int GetHashCode()
- {
- //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
- return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
- CodePage + (emitUTF32ByteOrderMark?4:0) + (bigEndian?8:0);
- }
-
- [Serializable]
- internal class UTF32Decoder : DecoderNLS
- {
- // Need a place to store any extra bytes we may have picked up
- internal int iChar = 0;
- internal int readByteCount = 0;
-
- public UTF32Decoder(UTF32Encoding encoding) : base(encoding)
- {
- // base calls reset
- }
-
- public override void Reset()
- {
- this.iChar = 0;
- this.readByteCount = 0;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- // ReadByteCount is our flag. (iChar==0 doesn't mean much).
- return (this.readByteCount != 0);
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/UTF7Encoding.cs b/src/mscorlib/src/System/Text/UTF7Encoding.cs
index 9418d2e768..372af0da37 100644
--- a/src/mscorlib/src/System/Text/UTF7Encoding.cs
+++ b/src/mscorlib/src/System/Text/UTF7Encoding.cs
@@ -6,14 +6,13 @@
// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
//
+using System;
+using System.Runtime.Serialization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
namespace System.Text
{
- using System;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-
[Serializable]
public class UTF7Encoding : Encoding
{
@@ -46,9 +45,9 @@ namespace System.Text
private bool[] directEncode;
[OptionalField(VersionAdded = 2)]
- private bool m_allowOptionals;
+ private bool m_allowOptionals;
- private const int UTF7_CODEPAGE=65000;
+ private const int UTF7_CODEPAGE = 65000;
public UTF7Encoding()
@@ -60,7 +59,7 @@ namespace System.Text
: base(UTF7_CODEPAGE) //Set the data item.
{
// Allowing optionals?
- this.m_allowOptionals = allowOptionals;
+ m_allowOptionals = allowOptionals;
// Make our tables
MakeTables();
@@ -81,7 +80,7 @@ namespace System.Text
directEncode[directChars[i]] = true;
}
- if (this.m_allowOptionals)
+ if (m_allowOptionals)
{
count = optionalChars.Length;
for (int i = 0; i < count; i++)
@@ -95,7 +94,7 @@ namespace System.Text
internal override void SetDefaultFallbacks()
{
// UTF7 had an odd decoderFallback behavior, and the Encoder fallback
- // is irrelevent because we encode surrogates individually and never check for unmatched ones
+ // is irrelevant because we encode surrogates individually and never check for unmatched ones
// (so nothing can fallback during encoding)
this.encoderFallback = new EncoderReplacementFallback(String.Empty);
this.decoderFallback = new DecoderUTF7Fallback();
@@ -144,43 +143,105 @@ namespace System.Text
return this.CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode();
}
- // NOTE: Many methods in this class forward to EncodingForwarder for
- // validating arguments/wrapping the unsafe methods in this class
- // which do the actual work. That class contains
- // shared logic for doing this which is used by
- // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
- // UTF7Encoding, and UTF8Encoding.
- // The reason the code is separated out into a static class, rather
- // than a base class which overrides all of these methods for us
- // (which is what EncodingNLS is for internal Encodings) is because
- // that's really more of an implementation detail so it's internal.
- // At the same time, C# doesn't allow a public class subclassing an
- // internal/private one, so we end up having to re-override these
- // methods in all of the public Encodings + EncodingNLS.
+ // The following methods are copied from EncodingNLS.cs.
+ // Unfortunately EncodingNLS.cs is internal and we're public, so we have to reimpliment them here.
+ // These should be kept in sync for the following classes:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
// Returns the number of bytes required to encode a range of characters in
// a character array.
+ //
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+ // parent method is safe
- public override int GetByteCount(char[] chars, int index, int count)
+ public override unsafe int GetByteCount(char[] chars, int index, int count)
{
- return EncodingForwarder.GetByteCount(this, chars, index, count);
+ // Validate input parameters
+ if (chars == null)
+ throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
+
+ if (index < 0 || count < 0)
+ throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
+
+ if (chars.Length - index < count)
+ throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
+ Contract.EndContractBlock();
+
+ // If no input, return 0, avoid fixed empty array problem
+ if (count == 0)
+ return 0;
+
+ // Just call the pointer version
+ fixed (char* pChars = chars)
+ return GetByteCount(pChars + index, count, null);
}
- public override int GetByteCount(String s)
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+ // parent method is safe
+
+ public override unsafe int GetByteCount(string s)
{
- return EncodingForwarder.GetByteCount(this, s);
+ // Validate input
+ if (s==null)
+ throw new ArgumentNullException("s");
+ Contract.EndContractBlock();
+
+ fixed (char* pChars = s)
+ return GetByteCount(pChars, s.Length, null);
}
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+
[CLSCompliant(false)]
public override unsafe int GetByteCount(char* chars, int count)
{
- return EncodingForwarder.GetByteCount(this, chars, count);
+ // Validate Parameters
+ if (chars == null)
+ throw new ArgumentNullException("chars", SR.ArgumentNull_Array);
+
+ if (count < 0)
+ throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
+ Contract.EndContractBlock();
+
+ // Call it with empty encoder
+ return GetByteCount(chars, count, null);
}
- public override int GetBytes(String s, int charIndex, int charCount,
+ // Parent method is safe.
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+
+ public override unsafe int GetBytes(string s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
- return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
+ if (s == null || bytes == null)
+ throw new ArgumentNullException((s == null ? "s" : "bytes"), SR.ArgumentNull_Array);
+
+ if (charIndex < 0 || charCount < 0)
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
+
+ if (s.Length - charIndex < charCount)
+ throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount);
+
+ if (byteIndex < 0 || byteIndex > bytes.Length)
+ throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
+ Contract.EndContractBlock();
+
+ int byteCount = bytes.Length - byteIndex;
+
+ // Fixed doesn't like empty arrays
+ if (bytes.Length == 0)
+ bytes = new byte[1];
+
+ fixed (char* pChars = s) fixed (byte* pBytes = &bytes[0])
+ return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
// Encodes a range of characters in a character array into a range of bytes
@@ -191,59 +252,204 @@ namespace System.Text
// Alternatively, the GetMaxByteCount method can be used to
// determine the maximum number of bytes that will be produced for a given
// number of characters, regardless of the actual character values.
+ //
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+ // parent method is safe
- public override int GetBytes(char[] chars, int charIndex, int charCount,
+ public override unsafe int GetBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
+ // Validate parameters
+ if (chars == null || bytes == null)
+ throw new ArgumentNullException((chars == null ? "chars" : "bytes"), SR.ArgumentNull_Array);
+
+ if (charIndex < 0 || charCount < 0)
+ throw new ArgumentOutOfRangeException((charIndex < 0 ? "charIndex" : "charCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
+
+ if (chars.Length - charIndex < charCount)
+ throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer);
+
+ if (byteIndex < 0 || byteIndex > bytes.Length)
+ throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index);
+ Contract.EndContractBlock();
+
+ // If nothing to encode return 0, avoid fixed problem
+ if (charCount == 0)
+ return 0;
+
+ // Just call pointer version
+ int byteCount = bytes.Length - byteIndex;
+
+ // Fixed doesn't like empty arrays
+ if (bytes.Length == 0)
+ bytes = new byte[1];
+
+ fixed (char* pChars = chars) fixed (byte* pBytes = &bytes[0])
+ // Remember that byteCount is # to decode, not size of array.
+ return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null);
}
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+
[CLSCompliant(false)]
public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
{
- return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
+ // Validate Parameters
+ if (bytes == null || chars == null)
+ throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
+
+ if (charCount < 0 || byteCount < 0)
+ throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
+ Contract.EndContractBlock();
+
+ return GetBytes(chars, charCount, bytes, byteCount, null);
}
// Returns the number of characters produced by decoding a range of bytes
// in a byte array.
+ //
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+ // parent method is safe
- public override int GetCharCount(byte[] bytes, int index, int count)
+ public override unsafe int GetCharCount(byte[] bytes, int index, int count)
{
- return EncodingForwarder.GetCharCount(this, bytes, index, count);
+ // Validate Parameters
+ if (bytes == null)
+ throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
+
+ if (index < 0 || count < 0)
+ throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
+
+ if (bytes.Length - index < count)
+ throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
+ Contract.EndContractBlock();
+
+ // If no input just return 0, fixed doesn't like 0 length arrays.
+ if (count == 0)
+ return 0;
+
+ // Just call pointer version
+ fixed (byte* pBytes = bytes)
+ return GetCharCount(pBytes + index, count, null);
}
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+
[CLSCompliant(false)]
public override unsafe int GetCharCount(byte* bytes, int count)
{
- return EncodingForwarder.GetCharCount(this, bytes, count);
+ // Validate Parameters
+ if (bytes == null)
+ throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
+
+ if (count < 0)
+ throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
+ Contract.EndContractBlock();
+
+ return GetCharCount(bytes, count, null);
}
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+ // parent method is safe
+
+ public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount,
char[] chars, int charIndex)
{
- return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
+ // Validate Parameters
+ if (bytes == null || chars == null)
+ throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
+
+ if (byteIndex < 0 || byteCount < 0)
+ throw new ArgumentOutOfRangeException((byteIndex < 0 ? "byteIndex" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
+
+ if ( bytes.Length - byteIndex < byteCount)
+ throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
+
+ if (charIndex < 0 || charIndex > chars.Length)
+ throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index);
+ Contract.EndContractBlock();
+
+ // If no input, return 0 & avoid fixed problem
+ if (byteCount == 0)
+ return 0;
+
+ // Just call pointer version
+ int charCount = chars.Length - charIndex;
+
+ // Fixed doesn't like empty arrays
+ if (chars.Length == 0)
+ chars = new char[1];
+
+ fixed (byte* pBytes = bytes) fixed (char* pChars = &chars[0])
+ // Remember that charCount is # to decode, not size of array
+ return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null);
}
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+
[CLSCompliant(false)]
public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
{
- return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
+ // Validate Parameters
+ if (bytes == null || chars == null)
+ throw new ArgumentNullException(bytes == null ? "bytes" : "chars", SR.ArgumentNull_Array);
+
+ if (charCount < 0 || byteCount < 0)
+ throw new ArgumentOutOfRangeException((charCount < 0 ? "charCount" : "byteCount"), SR.ArgumentOutOfRange_NeedNonNegNum);
+ Contract.EndContractBlock();
+
+ return GetChars(bytes, byteCount, chars, charCount, null);
}
// Returns a string containing the decoded representation of a range of
// bytes in a byte array.
+ //
+ // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS)
+ // So if you fix this, fix the others. Currently those include:
+ // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding
+ // parent method is safe
- public override String GetString(byte[] bytes, int index, int count)
+ public override unsafe String GetString(byte[] bytes, int index, int count)
{
- return EncodingForwarder.GetString(this, bytes, index, count);
+ // Validate Parameters
+ if (bytes == null)
+ throw new ArgumentNullException("bytes", SR.ArgumentNull_Array);
+
+ if (index < 0 || count < 0)
+ throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
+
+ if (bytes.Length - index < count)
+ throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer);
+ Contract.EndContractBlock();
+
+ // Avoid problems with empty input buffer
+ if (count == 0) return String.Empty;
+
+ fixed (byte* pBytes = bytes)
+ return String.CreateStringFromEncoding(
+ pBytes + index, count, this);
}
-
- // End of overridden methods which use EncodingForwarder
+
+ //
+ // End of standard methods copied from EncodingNLS.cs
+ //
internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS baseEncoder)
{
- Debug.Assert(chars!=null, "[UTF7Encoding.GetByteCount]chars!=null");
- Debug.Assert(count >=0, "[UTF7Encoding.GetByteCount]count >=0");
+ Debug.Assert(chars != null, "[UTF7Encoding.GetByteCount]chars!=null");
+ Debug.Assert(count >= 0, "[UTF7Encoding.GetByteCount]count >=0");
// Just call GetBytes with bytes == null
return GetBytes(chars, count, null, 0, baseEncoder);
@@ -252,9 +458,9 @@ namespace System.Text
internal override unsafe int GetBytes(char* chars, int charCount,
byte* bytes, int byteCount, EncoderNLS baseEncoder)
{
- Debug.Assert(byteCount >=0, "[UTF7Encoding.GetBytes]byteCount >=0");
- Debug.Assert(chars!=null, "[UTF7Encoding.GetBytes]chars!=null");
- Debug.Assert(charCount >=0, "[UTF7Encoding.GetBytes]charCount >=0");
+ Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetBytes]byteCount >=0");
+ Debug.Assert(chars != null, "[UTF7Encoding.GetBytes]chars!=null");
+ Debug.Assert(charCount >= 0, "[UTF7Encoding.GetBytes]charCount >=0");
// Get encoder info
UTF7Encoding.Encoder encoder = (UTF7Encoding.Encoder)baseEncoder;
@@ -339,7 +545,7 @@ namespace System.Text
{
bitCount += 6; // We didn't use these bits
currentChar = buffer.GetNextChar(); // We're processing this char still, but AddByte
- // --'d it when we ran out of space
+ // --'d it when we ran out of space
break; // Stop here, not enough room for bytes
}
}
@@ -391,8 +597,8 @@ namespace System.Text
internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
{
- Debug.Assert(count >=0, "[UTF7Encoding.GetCharCount]count >=0");
- Debug.Assert(bytes!=null, "[UTF7Encoding.GetCharCount]bytes!=null");
+ Debug.Assert(count >= 0, "[UTF7Encoding.GetCharCount]count >=0");
+ Debug.Assert(bytes != null, "[UTF7Encoding.GetCharCount]bytes!=null");
// Just call GetChars with null char* to do counting
return GetChars(bytes, count, null, 0, baseDecoder);
@@ -401,12 +607,12 @@ namespace System.Text
internal override unsafe int GetChars(byte* bytes, int byteCount,
char* chars, int charCount, DecoderNLS baseDecoder)
{
- Debug.Assert(byteCount >=0, "[UTF7Encoding.GetChars]byteCount >=0");
- Debug.Assert(bytes!=null, "[UTF7Encoding.GetChars]bytes!=null");
- Debug.Assert(charCount >=0, "[UTF7Encoding.GetChars]charCount >=0");
+ Debug.Assert(byteCount >= 0, "[UTF7Encoding.GetChars]byteCount >=0");
+ Debug.Assert(bytes != null, "[UTF7Encoding.GetChars]bytes!=null");
+ Debug.Assert(charCount >= 0, "[UTF7Encoding.GetChars]charCount >=0");
// Might use a decoder
- UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder) baseDecoder;
+ UTF7Encoding.Decoder decoder = (UTF7Encoding.Decoder)baseDecoder;
// Get our output buffer info.
Encoding.EncodingCharBuffer buffer = new Encoding.EncodingCharBuffer(
@@ -449,7 +655,7 @@ namespace System.Text
// Modified base 64 encoding.
//
sbyte v;
- if (currentByte < 0x80 && ((v = base64Values[currentByte]) >=0))
+ if (currentByte < 0x80 && ((v = base64Values[currentByte]) >= 0))
{
firstByte = false;
bits = (bits << 6) | ((byte)v);
@@ -581,8 +787,8 @@ namespace System.Text
public override int GetMaxByteCount(int charCount)
{
if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(charCount),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Suppose that every char can not be direct-encoded, we know that
@@ -605,7 +811,7 @@ namespace System.Text
// check for overflow
if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
+ throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow);
return (int)byteCount;
}
@@ -614,8 +820,8 @@ namespace System.Text
public override int GetMaxCharCount(int byteCount)
{
if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(byteCount),
+ SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
// Worst case is 1 char per byte. Minimum 1 for left over bits in case decoder is being flushed
@@ -629,14 +835,16 @@ namespace System.Text
[Serializable]
// Of all the amazing things... This MUST be Decoder so that our com name
// for System.Text.Decoder doesn't change
- private class Decoder : DecoderNLS, ISerializable
+ private sealed class Decoder : DecoderNLS, ISerializable
{
/*private*/
internal int bits;
- /*private*/ internal int bitCount;
- /*private*/ internal bool firstByte;
+ /*private*/
+ internal int bitCount;
+ /*private*/
+ internal bool firstByte;
- public Decoder(UTF7Encoding encoding) : base (encoding)
+ public Decoder(UTF7Encoding encoding) : base(encoding)
{
// base calls reset
}
@@ -645,7 +853,7 @@ namespace System.Text
internal Decoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get common info
@@ -659,7 +867,7 @@ namespace System.Text
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
@@ -693,11 +901,12 @@ namespace System.Text
[Serializable]
// Of all the amazing things... This MUST be Encoder so that our com name
// for System.Text.Encoder doesn't change
- private class Encoder : EncoderNLS, ISerializable
+ private sealed class Encoder : EncoderNLS, ISerializable
{
/*private*/
internal int bits;
- /*private*/ internal int bitCount;
+ /*private*/
+ internal int bitCount;
public Encoder(UTF7Encoding encoding) : base(encoding)
{
@@ -708,7 +917,7 @@ namespace System.Text
internal Encoder(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Get common info
@@ -721,7 +930,7 @@ namespace System.Text
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
+ if (info == null) throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
// Save Whidbey data
@@ -735,7 +944,7 @@ namespace System.Text
this.bitCount = -1;
this.bits = 0;
if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
+ m_fallbackBuffer.Reset();
}
// Anything left in our encoder?
@@ -751,7 +960,7 @@ namespace System.Text
// Preexisting UTF7 behavior for bad bytes was just to spit out the byte as the next char
// and turn off base64 mode if it was in that mode. We still exit the mode, but now we fallback.
[Serializable]
- internal sealed class DecoderUTF7Fallback : DecoderFallback
+ private sealed class DecoderUTF7Fallback : DecoderFallback
{
// Construction. Default replacement fallback uses no best fit and ? replacement string
public DecoderUTF7Fallback()
@@ -773,7 +982,7 @@ namespace System.Text
}
}
- public override bool Equals(Object value)
+ public override bool Equals(Object value)
{
DecoderUTF7Fallback that = value as DecoderUTF7Fallback;
if (that != null)
@@ -789,12 +998,12 @@ namespace System.Text
}
}
- internal sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer
+ private sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer
{
// Store our default string
- char cFallback = (char)0;
- int iCount = -1;
- int iSize;
+ private char cFallback = (char)0;
+ private int iCount = -1;
+ private int iSize;
// Construction
public DecoderUTF7FallbackBuffer(DecoderUTF7Fallback fallback)
@@ -855,7 +1064,7 @@ namespace System.Text
public override unsafe void Reset()
{
iCount = -1;
- byteStart = null;
+ byteStart = null;
}
// This version just counts the fallback and doesn't actually copy anything.
@@ -867,13 +1076,12 @@ namespace System.Text
Debug.Assert(iCount < 0, "[DecoderUTF7FallbackBuffer.InternalFallback] Can't have recursive fallbacks");
if (bytes.Length != 1)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidCharSequenceNoIndex"));
+ throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex);
}
// Can't fallback a byte 0, so return for that case, 1 otherwise.
return bytes[0] == 0 ? 0 : 1;
}
}
-
}
}
diff --git a/src/mscorlib/src/System/Text/UTF8Encoding.cs b/src/mscorlib/src/System/Text/UTF8Encoding.cs
deleted file mode 100644
index 191bbfef56..0000000000
--- a/src/mscorlib/src/System/Text/UTF8Encoding.cs
+++ /dev/null
@@ -1,2286 +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.
-
-
-// The worker functions in this file was optimized for performance. If you make changes
-// you should use care to consider all of the interesting cases.
-
-// The code of all worker functions in this file is written twice: Once as as a slow loop, and the
-// second time as a fast loop. The slow loops handles all special cases, throws exceptions, etc.
-// The fast loops attempts to blaze through as fast as possible with optimistic range checks,
-// processing multiple characters at a time, and falling back to the slow loop for all special cases.
-
-// This define can be used to turn off the fast loops. Useful for finding whether
-// the problem is fastloop-specific.
-#define FASTLOOP
-
-namespace System.Text
-{
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- // Encodes text into and out of UTF-8. UTF-8 is a way of writing
- // Unicode characters with variable numbers of bytes per character,
- // optimized for the lower 127 ASCII characters. It's an efficient way
- // of encoding US English in an internationalizable way.
- //
- // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
- //
- // The UTF-8 byte order mark is simply the Unicode byte order mark
- // (0xFEFF) written in UTF-8 (0xEF 0xBB 0xBF). The byte order mark is
- // used mostly to distinguish UTF-8 text from other encodings, and doesn't
- // switch the byte orderings.
-
- [Serializable]
- public class UTF8Encoding : Encoding
- {
- /*
- bytes bits UTF-8 representation
- ----- ---- -----------------------------------
- 1 7 0vvvvvvv
- 2 11 110vvvvv 10vvvvvv
- 3 16 1110vvvv 10vvvvvv 10vvvvvv
- 4 21 11110vvv 10vvvvvv 10vvvvvv 10vvvvvv
- ----- ---- -----------------------------------
-
- Surrogate:
- Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000
- */
-
- private const int UTF8_CODEPAGE=65001;
-
- // 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 UTF8Encoding s_default = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);
-
- // Yes, the idea of emitting U+FEFF as a UTF-8 identifier has made it into
- // the standard.
- private bool emitUTF8Identifier = false;
-
- private bool isThrowException = false;
-
-
- public UTF8Encoding(): this(false)
- {
- }
-
-
- public UTF8Encoding(bool encoderShouldEmitUTF8Identifier):
- this(encoderShouldEmitUTF8Identifier, false)
- {
- }
-
-
- public UTF8Encoding(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes):
- base(UTF8_CODEPAGE)
- {
- this.emitUTF8Identifier = encoderShouldEmitUTF8Identifier;
- this.isThrowException = throwOnInvalidBytes;
-
- // Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
- if (this.isThrowException)
- SetDefaultFallbacks();
- }
-
- internal override void SetDefaultFallbacks()
- {
- // For UTF-X encodings, we use a replacement fallback with an empty string
- if (this.isThrowException)
- {
- this.encoderFallback = EncoderFallback.ExceptionFallback;
- this.decoderFallback = DecoderFallback.ExceptionFallback;
- }
- else
- {
- this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
- this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
- }
- }
-
- // NOTE: Many methods in this class forward to EncodingForwarder for
- // validating arguments/wrapping the unsafe methods in this class
- // which do the actual work. That class contains
- // shared logic for doing this which is used by
- // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
- // UTF7Encoding, and UTF8Encoding.
- // The reason the code is separated out into a static class, rather
- // than a base class which overrides all of these methods for us
- // (which is what EncodingNLS is for internal Encodings) is because
- // that's really more of an implementation detail so it's internal.
- // At the same time, C# doesn't allow a public class subclassing an
- // internal/private one, so we end up having to re-override these
- // methods in all of the public Encodings + EncodingNLS.
-
- // Returns the number of bytes required to encode a range of characters in
- // a character array.
-
- public override int GetByteCount(char[] chars, int index, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, index, count);
- }
-
- public override int GetByteCount(String chars)
- {
- return EncodingForwarder.GetByteCount(this, chars);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetByteCount(char* chars, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, count);
- }
-
- public override int GetBytes(String s, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
- }
-
- // Encodes a range of characters in a character array into a range of bytes
- // in a byte array. An exception occurs if the byte array is not large
- // enough to hold the complete encoding of the characters. The
- // GetByteCount method can be used to determine the exact number of
- // bytes that will be produced for a given range of characters.
- // Alternatively, the GetMaxByteCount method can be used to
- // determine the maximum number of bytes that will be produced for a given
- // number of characters, regardless of the actual character values.
-
- public override int GetBytes(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
- {
- return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
- }
-
- // Returns the number of characters produced by decoding a range of bytes
- // in a byte array.
-
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, index, count);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetCharCount(byte* bytes, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, count);
- }
-
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex)
- {
- return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
- }
-
- [CLSCompliant(false)]
- public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
- {
- return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
- }
-
- // Returns a string containing the decoded representation of a range of
- // bytes in a byte array.
-
- public override String GetString(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetString(this, bytes, index, count);
- }
-
- // End of overridden methods which use EncodingForwarder
-
- // To simplify maintenance, the structure of GetByteCount and GetBytes should be
- // kept the same as much as possible
- internal override unsafe int GetByteCount(char *chars, int count, EncoderNLS baseEncoder)
- {
- // For fallback we may need a fallback buffer.
- // We wait to initialize it though in case we don't have any broken input unicode
- EncoderFallbackBuffer fallbackBuffer = null;
- char *pSrc = chars;
- char *pEnd = pSrc+count;
-
- // Start by assuming we have as many as count
- int byteCount = count;
-
- int ch = 0;
-
- if (baseEncoder != null) {
- UTF8Encoder encoder = (UTF8Encoder)baseEncoder;
- ch = encoder.surrogateChar;
-
- // We mustn't have left over fallback data when counting
- if (encoder.InternalHasFallbackBuffer)
- {
- fallbackBuffer = encoder.FallbackBuffer;
- if (fallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(chars, pEnd, encoder, false);
- }
- }
-
- for (;;) {
- // SLOWLOOP: does all range checks, handles all special cases, but it is slow
- if (pSrc >= pEnd) {
-
- if (ch == 0) {
- // Unroll any fallback that happens at the end
- ch = fallbackBuffer != null ? fallbackBuffer.InternalGetNextChar() : 0;
- if (ch > 0) {
- byteCount++;
- goto ProcessChar;
- }
- } else {
- // Case of surrogates in the fallback.
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
- Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
- "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
-
- ch = fallbackBuffer.InternalGetNextChar();
- byteCount++;
-
- if (InRange(ch, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- ch = 0xfffd;
- byteCount++;
- goto EncodeChar;
- } else if (ch > 0){
- goto ProcessChar;
- } else {
- byteCount--; // ignore last one.
- break;
- }
- }
- }
-
- if (ch <= 0) {
- break;
- }
- if (baseEncoder != null && !baseEncoder.MustFlush) {
- break;
- }
-
- // attempt to encode the partial surrogate (will fallback or ignore it), it'll also subtract 1.
- byteCount++;
- goto EncodeChar;
- }
-
- if (ch > 0) {
- Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
- "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
-
- // use separate helper variables for local contexts so that the jit optimizations
- // won't get confused about the variable lifetimes
- int cha = *pSrc;
-
- // count the pending surrogate
- byteCount++;
-
- // In previous byte, we encountered a high surrogate, so we are expecting a low surrogate here.
- // if (IsLowSurrogate(cha)) {
- if (InRange(cha, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- // Don't need a real # because we're just counting, anything > 0x7ff ('cept surrogate) will do.
- ch = 0xfffd;
-// ch = cha + (ch << 10) +
-// (0x10000
-// - CharUnicodeInfo.LOW_SURROGATE_START
-// - (CharUnicodeInfo.HIGH_SURROGATE_START << 10) );
-
- // Use this next char
- pSrc++;
- }
- // else ch is still high surrogate and encoding will fail (so don't add count)
-
- // attempt to encode the surrogate or partial surrogate
- goto EncodeChar;
- }
-
- // If we've used a fallback, then we have to check for it
- if (fallbackBuffer != null)
- {
- ch = fallbackBuffer.InternalGetNextChar();
- if (ch > 0)
- {
- // We have an extra byte we weren't expecting.
- byteCount++;
- goto ProcessChar;
- }
- }
-
- // read next char. The JIT optimization seems to be getting confused when
- // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead
- ch = *pSrc;
- pSrc++;
-
- ProcessChar:
- // if (IsHighSurrogate(ch)) {
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END)) {
- // we will count this surrogate next time around
- byteCount--;
- continue;
- }
- // either good char or partial surrogate
-
- EncodeChar:
- // throw exception on partial surrogate if necessary
- // if (IsLowSurrogate(ch) || IsHighSurrogate(ch))
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END))
- {
- // Lone surrogates aren't allowed
- // Have to make a fallback buffer if we don't have one
- if (fallbackBuffer == null)
- {
- // wait on fallbacks if we can
- // For fallback we may need a fallback buffer
- if (baseEncoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = baseEncoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(chars, chars + count, baseEncoder, false);
- }
-
- // Do our fallback. Actually we already know its a mixed up surrogate,
- // so the ref pSrc isn't gonna do anything.
- fallbackBuffer.InternalFallback(unchecked((char)ch), ref pSrc);
-
- // Ignore it if we don't throw (we had preallocated this ch)
- byteCount--;
- ch = 0;
- continue;
- }
-
- // Count them
- if (ch > 0x7F) {
- if (ch > 0x7FF) {
- // the extra surrogate byte was compensated by the second surrogate character
- // (2 surrogates make 4 bytes. We've already counted 2 bytes, 1 per char)
- byteCount++;
- }
- byteCount++;
- }
-
-#if BIT64
- // check for overflow
- if (byteCount < 0) {
- break;
- }
-#endif
-
-#if FASTLOOP
- // If still have fallback don't do fast loop
- if (fallbackBuffer != null && (ch = fallbackBuffer.InternalGetNextChar()) != 0)
- {
- // We're reserving 1 byte for each char by default
- byteCount++;
- goto ProcessChar;
- }
-
- int availableChars = PtrDiff(pEnd, pSrc);
-
- // don't fall into the fast decoding loop if we don't have enough characters
- if (availableChars <= 13) {
- // try to get over the remainder of the ascii characters fast though
- char* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered
- while (pSrc < pLocalEnd) {
- ch = *pSrc;
- pSrc++;
- if (ch > 0x7F)
- goto ProcessChar;
- }
-
- // we are done
- break;
- }
-
-#if BIT64
- // make sure that we won't get a silent overflow inside the fast loop
- // (Fall out to slow loop if we have this many characters)
- availableChars &= 0x0FFFFFFF;
-#endif
-
- // To compute the upper bound, assume that all characters are ASCII characters at this point,
- // the boundary will be decreased for every non-ASCII character we encounter
- // Also, we need 3 + 4 chars reserve for the unrolled ansi decoding loop and for decoding of surrogates
- char *pStop = pSrc + availableChars - (3 + 4);
-
- while (pSrc < pStop) {
- ch = *pSrc;
- pSrc++;
-
- if (ch > 0x7F) // Not ASCII
- {
- if (ch > 0x7FF) // Not 2 Byte
- {
- if ((ch & 0xF800) == 0xD800) // See if its a Surrogate
- goto LongCode;
- byteCount++;
- }
- byteCount ++;
- }
-
- // get pSrc aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
- ch = *pSrc;
- pSrc++;
- if (ch > 0x7F) // Not ASCII
- {
- if (ch > 0x7FF) // Not 2 Byte
- {
- if ((ch & 0xF800) == 0xD800) // See if its a Surrogate
- goto LongCode;
- byteCount++;
- }
- byteCount ++;
- }
- }
-
- // Run 2 * 4 characters at a time!
- while (pSrc < pStop) {
- ch = *(int*)pSrc;
- int chc = *(int*)(pSrc+2);
- if (((ch | chc) & unchecked((int)0xFF80FF80)) != 0) // See if not ASCII
- {
- if (((ch | chc) & unchecked((int)0xF800F800)) != 0) // See if not 2 Byte
- {
- goto LongCodeWithMask;
- }
-
-
- if ((ch & unchecked((int)0xFF800000)) != 0) // Actually 0x07800780 is all we care about (4 bits)
- byteCount++;
- if ((ch & unchecked((int)0xFF80)) != 0)
- byteCount++;
- if ((chc & unchecked((int)0xFF800000)) != 0)
- byteCount++;
- if ((chc & unchecked((int)0xFF80)) != 0)
- byteCount++;
- }
- pSrc += 4;
-
- ch = *(int*)pSrc;
- chc = *(int*)(pSrc+2);
- if (((ch | chc) & unchecked((int)0xFF80FF80)) != 0) // See if not ASCII
- {
- if (((ch | chc) & unchecked((int)0xF800F800)) != 0) // See if not 2 Byte
- {
- goto LongCodeWithMask;
- }
-
- if ((ch & unchecked((int)0xFF800000)) != 0)
- byteCount++;
- if ((ch & unchecked((int)0xFF80)) != 0)
- byteCount++;
- if ((chc & unchecked((int)0xFF800000)) != 0)
- byteCount++;
- if ((chc & unchecked((int)0xFF80)) != 0)
- byteCount++;
- }
- pSrc += 4;
- }
- break;
-
- LongCodeWithMask:
-#if BIGENDIAN
- // be careful about the sign extension
- ch = (int)(((uint)ch) >> 16);
-#else // BIGENDIAN
- ch = (char)ch;
-#endif // BIGENDIAN
- pSrc++;
-
- if (ch <= 0x7F) {
- continue;
- }
-
- LongCode:
- // use separate helper variables for slow and fast loop so that the jit optimizations
- // won't get confused about the variable lifetimes
- if (ch > 0x7FF) {
- // if (IsLowSurrogate(ch) || IsHighSurrogate(ch))
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- // 4 byte encoding - high surrogate + low surrogate
-
- int chd = *pSrc;
- if (
- // !IsHighSurrogate(ch) // low without high -> bad
- ch > CharUnicodeInfo.HIGH_SURROGATE_END ||
- // !IsLowSurrogate(chd) // high not followed by low -> bad
- !InRange(chd, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END) )
- {
- // Back up and drop out to slow loop to figure out error
- pSrc--;
- break;
- }
- pSrc++;
-
- // byteCount - this byte is compensated by the second surrogate character
- }
- byteCount++;
- }
- byteCount++;
-
- // byteCount - the last byte is already included
- }
-#endif // FASTLOOP
-
- // no pending char at this point
- ch = 0;
- }
-
-#if BIT64
- // check for overflow
- if (byteCount < 0) {
- throw new ArgumentException(
- Environment.GetResourceString("Argument_ConversionOverflow"));
- }
-#endif
-
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[UTF8Encoding.GetByteCount]Expected Empty fallback buffer");
-
- return byteCount;
- }
-
- // diffs two char pointers using unsigned arithmetic. The unsigned arithmetic
- // is good enough for us, and it tends to generate better code than the signed
- // arithmetic generated by default
- unsafe private static int PtrDiff(char *a, char* b)
- {
- return (int)(((uint)((byte*)a - (byte*)b)) >> 1);
- }
-
- // byte* flavor just for parity
- unsafe private static int PtrDiff(byte* a, byte* b)
- {
- return (int)(a - b);
- }
-
- private static bool InRange(int ch, int start, int end)
- {
- return (uint)(ch - start) <= (uint)(end - start);
- }
-
- // Our workhorse
- // Note: We ignore mismatched surrogates, unless the exception flag is set in which case we throw
- internal override unsafe int GetBytes(char* chars, int charCount,
- byte* bytes, int byteCount, EncoderNLS baseEncoder)
- {
- Debug.Assert(chars!=null, "[UTF8Encoding.GetBytes]chars!=null");
- Debug.Assert(byteCount >=0, "[UTF8Encoding.GetBytes]byteCount >=0");
- Debug.Assert(charCount >=0, "[UTF8Encoding.GetBytes]charCount >=0");
- Debug.Assert(bytes!=null, "[UTF8Encoding.GetBytes]bytes!=null");
-
- UTF8Encoder encoder = null;
-
- // For fallback we may need a fallback buffer.
- // We wait to initialize it though in case we don't have any broken input unicode
- EncoderFallbackBuffer fallbackBuffer = null;
- char *pSrc = chars;
- byte *pTarget = bytes;
-
- char *pEnd = pSrc+charCount;
- byte *pAllocatedBufferEnd = pTarget+byteCount;
-
- int ch = 0;
-
- // assume that JIT will enregister pSrc, pTarget and ch
-
- if (baseEncoder != null) {
- encoder = (UTF8Encoder)baseEncoder;
- ch = encoder.surrogateChar;
-
- // We mustn't have left over fallback data when counting
- if (encoder.InternalHasFallbackBuffer)
- {
- // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
- fallbackBuffer = encoder.FallbackBuffer;
- if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(chars, pEnd, encoder, true);
- }
- }
-
- for (;;) {
- // SLOWLOOP: does all range checks, handles all special cases, but it is slow
-
- if (pSrc >= pEnd) {
-
- if (ch == 0) {
- // Check if there's anthing left to get out of the fallback buffer
- ch = fallbackBuffer != null ? fallbackBuffer.InternalGetNextChar() : 0;
- if (ch > 0) {
- goto ProcessChar;
- }
- } else {
- // Case of leftover surrogates in the fallback buffer
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack) {
- Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
- "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
-
- int cha = ch;
-
- ch = fallbackBuffer.InternalGetNextChar();
-
- if (InRange(ch, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- ch = ch + (cha << 10) + (0x10000 - CharUnicodeInfo.LOW_SURROGATE_START - (CharUnicodeInfo.HIGH_SURROGATE_START << 10));
- goto EncodeChar;
- } else if (ch > 0){
- goto ProcessChar;
- } else {
- break;
- }
- }
- }
-
- // attempt to encode the partial surrogate (will fail or ignore)
- if (ch > 0 && (encoder == null || encoder.MustFlush))
- goto EncodeChar;
-
- // We're done
- break;
- }
-
- if (ch > 0) {
- // We have a high surrogate left over from a previous loop.
- Debug.Assert(ch >= 0xD800 && ch <= 0xDBFF,
- "[UTF8Encoding.GetBytes]expected high surrogate, not 0x" + ((int)ch).ToString("X4", CultureInfo.InvariantCulture));
-
- // use separate helper variables for local contexts so that the jit optimizations
- // won't get confused about the variable lifetimes
- int cha = *pSrc;
-
- // In previous byte, we encountered a high surrogate, so we are expecting a low surrogate here.
- // if (IsLowSurrogate(cha)) {
- if (InRange(cha, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- ch = cha + (ch << 10) +
- (0x10000
- - CharUnicodeInfo.LOW_SURROGATE_START
- - (CharUnicodeInfo.HIGH_SURROGATE_START << 10) );
-
- pSrc++;
- }
- // else ch is still high surrogate and encoding will fail
-
- // attempt to encode the surrogate or partial surrogate
- goto EncodeChar;
- }
-
- // If we've used a fallback, then we have to check for it
- if (fallbackBuffer != null)
- {
- ch = fallbackBuffer.InternalGetNextChar();
- if (ch > 0) goto ProcessChar;
- }
-
- // read next char. The JIT optimization seems to be getting confused when
- // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead
- ch = *pSrc;
- pSrc++;
-
- ProcessChar:
- // if (IsHighSurrogate(ch)) {
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.HIGH_SURROGATE_END)) {
- continue;
- }
- // either good char or partial surrogate
-
- EncodeChar:
- // throw exception on partial surrogate if necessary
- // if (IsLowSurrogate(ch) || IsHighSurrogate(ch))
- if (InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END))
- {
- // Lone surrogates aren't allowed, we have to do fallback for them
- // Have to make a fallback buffer if we don't have one
- if (fallbackBuffer == null)
- {
- // wait on fallbacks if we can
- // For fallback we may need a fallback buffer
- if (baseEncoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = baseEncoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(chars, pEnd, baseEncoder, true);
- }
-
- // Do our fallback. Actually we already know its a mixed up surrogate,
- // so the ref pSrc isn't gonna do anything.
- fallbackBuffer.InternalFallback(unchecked((char)ch), ref pSrc);
-
- // Ignore it if we don't throw
- ch = 0;
- continue;
- }
-
- // Count bytes needed
- int bytesNeeded = 1;
- if (ch > 0x7F) {
- if (ch > 0x7FF) {
- if (ch > 0xFFFF) {
- bytesNeeded++; // 4 bytes (surrogate pair)
- }
- bytesNeeded++; // 3 bytes (800-FFFF)
- }
- bytesNeeded++; // 2 bytes (80-7FF)
- }
-
- if (pTarget > pAllocatedBufferEnd - bytesNeeded) {
- // Left over surrogate from last time will cause pSrc == chars, so we'll throw
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack)
- {
- fallbackBuffer.MovePrevious(); // Didn't use this fallback char
- if (ch > 0xFFFF)
- fallbackBuffer.MovePrevious(); // Was surrogate, didn't use 2nd part either
- }
- else
- {
- pSrc--; // Didn't use this char
- if (ch > 0xFFFF)
- pSrc--; // Was surrogate, didn't use 2nd part either
- }
- Debug.Assert(pSrc >= chars || pTarget == bytes,
- "[UTF8Encoding.GetBytes]Expected pSrc to be within buffer or to throw with insufficient room.");
- ThrowBytesOverflow(encoder, pTarget == bytes); // Throw if we must
- ch = 0; // Nothing left over (we backed up to start of pair if supplimentary)
- break;
- }
-
- if (ch <= 0x7F) {
- *pTarget = (byte)ch;
- }
- else {
- // use separate helper variables for local contexts so that the jit optimizations
- // won't get confused about the variable lifetimes
- int chb;
- if (ch <= 0x7FF) {
- // 2 byte encoding
- chb = (byte)(unchecked((sbyte)0xC0) | (ch >> 6));
- }
- else
- {
- if (ch <= 0xFFFF) {
- chb = (byte)(unchecked((sbyte)0xE0) | (ch >> 12));
- }
- else
- {
- *pTarget = (byte)(unchecked((sbyte)0xF0) | (ch >> 18));
- pTarget++;
-
- chb = unchecked((sbyte)0x80) | (ch >> 12) & 0x3F;
- }
- *pTarget = (byte)chb;
- pTarget++;
-
- chb = unchecked((sbyte)0x80) | (ch >> 6) & 0x3F;
- }
- *pTarget = (byte)chb;
- pTarget++;
-
- *pTarget = (byte)(unchecked((sbyte)0x80) | ch & 0x3F);
- }
- pTarget++;
-
-
-#if FASTLOOP
- // If still have fallback don't do fast loop
- if (fallbackBuffer != null && (ch = fallbackBuffer.InternalGetNextChar()) != 0)
- goto ProcessChar;
-
- int availableChars = PtrDiff(pEnd, pSrc);
- int availableBytes = PtrDiff(pAllocatedBufferEnd, pTarget);
-
- // don't fall into the fast decoding loop if we don't have enough characters
- // Note that if we don't have enough bytes, pStop will prevent us from entering the fast loop.
- if (availableChars <= 13) {
- // we are hoping for 1 byte per char
- if (availableBytes < availableChars) {
- // not enough output room. no pending bits at this point
- ch = 0;
- continue;
- }
-
- // try to get over the remainder of the ascii characters fast though
- char* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered
- while (pSrc < pLocalEnd) {
- ch = *pSrc;
- pSrc++;
-
- // Not ASCII, need more than 1 byte per char
- if (ch > 0x7F)
- goto ProcessChar;
-
- *pTarget = (byte)ch;
- pTarget++;
- }
- // we are done, let ch be 0 to clear encoder
- ch = 0;
- break;
- }
-
- // we need at least 1 byte per character, but Convert might allow us to convert
- // only part of the input, so try as much as we can. Reduce charCount if necessary
- if (availableBytes < availableChars)
- {
- availableChars = availableBytes;
- }
-
- // FASTLOOP:
- // - optimistic range checks
- // - fallbacks to the slow loop for all special cases, exception throwing, etc.
-
- // To compute the upper bound, assume that all characters are ASCII characters at this point,
- // the boundary will be decreased for every non-ASCII character we encounter
- // Also, we need 5 chars reserve for the unrolled ansi decoding loop and for decoding of surrogates
- // If there aren't enough bytes for the output, then pStop will be <= pSrc and will bypass the loop.
- char *pStop = pSrc + availableChars - 5;
-
- while (pSrc < pStop) {
- ch = *pSrc;
- pSrc++;
-
- if (ch > 0x7F) {
- goto LongCode;
- }
- *pTarget = (byte)ch;
- pTarget++;
-
- // get pSrc aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
- ch = *pSrc;
- pSrc++;
- if (ch > 0x7F) {
- goto LongCode;
- }
- *pTarget = (byte)ch;
- pTarget++;
- }
-
- // Run 4 characters at a time!
- while (pSrc < pStop) {
- ch = *(int*)pSrc;
- int chc = *(int*)(pSrc+2);
- if (((ch | chc) & unchecked((int)0xFF80FF80)) != 0) {
- goto LongCodeWithMask;
- }
-
- // Unfortunately, this is endianess sensitive
-#if BIGENDIAN
- *pTarget = (byte)(ch>>16);
- *(pTarget+1) = (byte)ch;
- pSrc += 4;
- *(pTarget+2) = (byte)(chc>>16);
- *(pTarget+3) = (byte)chc;
- pTarget += 4;
-#else // BIGENDIAN
- *pTarget = (byte)ch;
- *(pTarget+1) = (byte)(ch>>16);
- pSrc += 4;
- *(pTarget+2) = (byte)chc;
- *(pTarget+3) = (byte)(chc>>16);
- pTarget += 4;
-#endif // BIGENDIAN
- }
- continue;
-
- LongCodeWithMask:
-#if BIGENDIAN
- // be careful about the sign extension
- ch = (int)(((uint)ch) >> 16);
-#else // BIGENDIAN
- ch = (char)ch;
-#endif // BIGENDIAN
- pSrc++;
-
- if (ch > 0x7F) {
- goto LongCode;
- }
- *pTarget = (byte)ch;
- pTarget++;
- continue;
-
- LongCode:
- // use separate helper variables for slow and fast loop so that the jit optimizations
- // won't get confused about the variable lifetimes
- int chd;
- if (ch <= 0x7FF) {
- // 2 byte encoding
- chd = unchecked((sbyte)0xC0) | (ch >> 6);
- }
- else {
- // if (!IsLowSurrogate(ch) && !IsHighSurrogate(ch))
- if (!InRange(ch, CharUnicodeInfo.HIGH_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- // 3 byte encoding
- chd = unchecked((sbyte)0xE0) | (ch >> 12);
- }
- else
- {
- // 4 byte encoding - high surrogate + low surrogate
- // if (!IsHighSurrogate(ch))
- if (ch > CharUnicodeInfo.HIGH_SURROGATE_END) {
- // low without high -> bad, try again in slow loop
- pSrc -= 1;
- break;
- }
-
- chd = *pSrc;
- pSrc++;
-
- // if (!IsLowSurrogate(chd)) {
- if (!InRange(chd, CharUnicodeInfo.LOW_SURROGATE_START, CharUnicodeInfo.LOW_SURROGATE_END)) {
- // high not followed by low -> bad, try again in slow loop
- pSrc -= 2;
- break;
- }
-
- ch = chd + (ch << 10) +
- (0x10000
- - CharUnicodeInfo.LOW_SURROGATE_START
- - (CharUnicodeInfo.HIGH_SURROGATE_START << 10) );
-
- *pTarget = (byte)(unchecked((sbyte)0xF0) | (ch >> 18));
- // pStop - this byte is compensated by the second surrogate character
- // 2 input chars require 4 output bytes. 2 have been anticipated already
- // and 2 more will be accounted for by the 2 pStop-- calls below.
- pTarget++;
-
- chd = unchecked((sbyte)0x80) | (ch >> 12) & 0x3F;
- }
- *pTarget = (byte)chd;
- pStop--; // 3 byte sequence for 1 char, so need pStop-- and the one below too.
- pTarget++;
-
- chd = unchecked((sbyte)0x80) | (ch >> 6) & 0x3F;
- }
- *pTarget = (byte)chd;
- pStop--; // 2 byte sequence for 1 char so need pStop--.
- pTarget++;
-
- *pTarget = (byte)(unchecked((sbyte)0x80) | ch & 0x3F);
- // pStop - this byte is already included
- pTarget++;
- }
-
- Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetBytes]pTarget <= pAllocatedBufferEnd");
-
-#endif // FASTLOOP
-
- // no pending char at this point
- ch = 0;
- }
-
- // Do we have to set the encoder bytes?
- if (encoder != null)
- {
- Debug.Assert(!encoder.MustFlush || ch == 0,
- "[UTF8Encoding.GetBytes] Expected no mustflush or 0 leftover ch " + ch.ToString("X2", CultureInfo.InvariantCulture));
-
- encoder.surrogateChar = ch;
- encoder.m_charsUsed = (int)(pSrc - chars);
- }
-
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
- baseEncoder == null || !baseEncoder.m_throwOnOverflow,
- "[UTF8Encoding.GetBytes]Expected empty fallback buffer if not converting");
-
- return (int)(pTarget - bytes);
- }
-
-
- // These are bitmasks used to maintain the state in the decoder. They occupy the higher bits
- // while the actual character is being built in the lower bits. They are shifted together
- // with the actual bits of the character.
-
- // bits 30 & 31 are used for pending bits fixup
- private const int FinalByte = 1 << 29;
- private const int SupplimentarySeq = 1 << 28;
- private const int ThreeByteSeq = 1 << 27;
-
- // Note: We throw exceptions on individually encoded surrogates and other non-shortest forms.
- // If exceptions aren't turned on, then we drop all non-shortest &individual surrogates.
- //
- // To simplify maintenance, the structure of GetCharCount and GetChars should be
- // kept the same as much as possible
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
- {
- Debug.Assert(count >=0, "[UTF8Encoding.GetCharCount]count >=0");
- Debug.Assert(bytes!=null, "[UTF8Encoding.GetCharCount]bytes!=null");
-
- // Initialize stuff
- byte *pSrc = bytes;
- byte *pEnd = pSrc+count;
-
- // Start by assuming we have as many as count, charCount always includes the adjustment
- // for the character being decoded
- int charCount = count;
- int ch = 0;
- DecoderFallbackBuffer fallback = null;
-
- if (baseDecoder != null) {
- UTF8Decoder decoder = (UTF8Decoder)baseDecoder;
- ch = decoder.bits;
- charCount -= (ch >> 30); // Adjust char count for # of expected bytes and expected output chars.
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at start");
- }
-
- for (;;)
- {
- // SLOWLOOP: does all range checks, handles all special cases, but it is slow
-
- if (pSrc >= pEnd) {
- break;
- }
-
- if (ch == 0) {
- // no pending bits
- goto ReadChar;
- }
-
- // read next byte. The JIT optimization seems to be getting confused when
- // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead
- int cha = *pSrc;
- pSrc++;
-
- // we are expecting to see trailing bytes like 10vvvvvv
- if ((cha & unchecked((sbyte)0xC0)) != 0x80) {
- // This can be a valid starting byte for another UTF8 byte sequence, so let's put
- // the current byte back, and try to see if this is a valid byte for another UTF8 byte sequence
- pSrc--;
- charCount += (ch >> 30);
- goto InvalidByteSequence;
- }
-
- // fold in the new byte
- ch = (ch << 6) | (cha & 0x3F);
-
- if ((ch & FinalByte) == 0) {
- Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
- "[UTF8Encoding.GetChars]Invariant volation");
-
- if ((ch & SupplimentarySeq) != 0) {
- if ((ch & (FinalByte >> 6)) != 0) {
- // this is 3rd byte (of 4 byte supplimentary) - nothing to do
- continue;
- }
-
- // 2nd byte, check for non-shortest form of supplimentary char and the valid
- // supplimentary characters in range 0x010000 - 0x10FFFF at the same time
- if (!InRange(ch & 0x1F0, 0x10, 0x100)) {
- goto InvalidByteSequence;
- }
- }
- else {
- // Must be 2nd byte of a 3-byte sequence
- // check for non-shortest form of 3 byte seq
- if ((ch & (0x1F << 5)) == 0 || // non-shortest form
- (ch & (0xF800 >> 6) ) == (0xD800 >> 6)) // illegal individually encoded surrogate
- {
- goto InvalidByteSequence;
- }
- }
- continue;
- }
-
- // ready to punch
-
- // adjust for surrogates in non-shortest form
- if ((ch & (SupplimentarySeq | 0x1F0000)) == SupplimentarySeq) {
- charCount--;
- }
- goto EncodeChar;
-
- InvalidByteSequence:
- // this code fragment should be close to the gotos referencing it
- // Have to do fallback for invalid bytes
- if (fallback == null)
- {
- if (baseDecoder == null)
- fallback = this.decoderFallback.CreateFallbackBuffer();
- else
- fallback = baseDecoder.FallbackBuffer;
- fallback.InternalInitialize(bytes, null);
- }
- charCount += FallbackInvalidByteSequence(pSrc, ch, fallback);
-
- ch = 0;
- continue;
-
- ReadChar:
- ch = *pSrc;
- pSrc++;
-
- ProcessChar:
- if (ch > 0x7F) {
- // If its > 0x7F, its start of a new multi-byte sequence
-
- // Long sequence, so unreserve our char.
- charCount--;
-
- // bit 6 has to be non-zero for start of multibyte chars.
- if ((ch & 0x40) == 0) {
- // Unexpected trail byte
- goto InvalidByteSequence;
- }
-
- // start a new long code
- if ((ch & 0x20) != 0) {
- if ((ch & 0x10) != 0) {
- // 4 byte encoding - supplimentary character (2 surrogates)
-
- ch &= 0x0F;
-
- // check that bit 4 is zero and the valid supplimentary character
- // range 0x000000 - 0x10FFFF at the same time
- if (ch > 0x04) {
- ch |= 0xf0;
- goto InvalidByteSequence;
- }
-
- // Add bit flags so that when we check new characters & rotate we'll be flagged correctly.
- // Final byte flag, count fix if we don't make final byte & supplimentary sequence flag.
- ch |= (FinalByte >> 3*6) | // Final byte is 3 more bytes from now
- (1 << 30) | // If it dies on next byte we'll need an extra char
- (3 << (30-2*6)) | // If it dies on last byte we'll need to subtract a char
- (SupplimentarySeq) | (SupplimentarySeq >> 6) |
- (SupplimentarySeq >> 2*6) | (SupplimentarySeq >> 3*6);
-
- // Our character count will be 2 characters for these 4 bytes, so subtract another char
- charCount--;
- }
- else {
- // 3 byte encoding
- // Add bit flags so that when we check new characters & rotate we'll be flagged correctly.
- ch = (ch & 0x0F) | ( (FinalByte >> 2*6) | (1 << 30) |
- (ThreeByteSeq) | (ThreeByteSeq >> 6) | (ThreeByteSeq >> 2*6) );
-
- // We'll expect 1 character for these 3 bytes, so subtract another char.
- charCount--;
- }
- }
- else {
- // 2 byte encoding
-
- ch &= 0x1F;
-
- // check for non-shortest form
- if (ch <= 1) {
- ch |= 0xc0;
- goto InvalidByteSequence;
- }
-
- // Add bit flags so we'll be flagged correctly
- ch |= (FinalByte >> 6);
- }
- continue;
- }
-
- EncodeChar:
-
-#if FASTLOOP
- int availableBytes = PtrDiff(pEnd, pSrc);
-
- // don't fall into the fast decoding loop if we don't have enough bytes
- if (availableBytes <= 13) {
- // try to get over the remainder of the ascii characters fast though
- byte* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered
- while (pSrc < pLocalEnd) {
- ch = *pSrc;
- pSrc++;
-
- if (ch > 0x7F)
- goto ProcessChar;
- }
- // we are done
- ch = 0;
- break;
- }
-
- // To compute the upper bound, assume that all characters are ASCII characters at this point,
- // the boundary will be decreased for every non-ASCII character we encounter
- // Also, we need 7 chars reserve for the unrolled ansi decoding loop and for decoding of multibyte sequences
- byte *pStop = pSrc + availableBytes - 7;
-
- while (pSrc < pStop) {
- ch = *pSrc;
- pSrc++;
-
- if (ch > 0x7F) {
- goto LongCode;
- }
-
- // get pSrc 2-byte aligned
- if ((unchecked((int)pSrc) & 0x1) != 0) {
- ch = *pSrc;
- pSrc++;
- if (ch > 0x7F) {
- goto LongCode;
- }
- }
-
- // get pSrc 4-byte aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
- ch = *(ushort*)pSrc;
- if ((ch & 0x8080) != 0) {
- goto LongCodeWithMask16;
- }
- pSrc += 2;
- }
-
- // Run 8 + 8 characters at a time!
- while (pSrc < pStop) {
- ch = *(int*)pSrc;
- int chb = *(int*)(pSrc+4);
- if (((ch | chb) & unchecked((int)0x80808080)) != 0) {
- goto LongCodeWithMask32;
- }
- pSrc += 8;
-
- // This is a really small loop - unroll it
- if (pSrc >= pStop)
- break;
-
- ch = *(int*)pSrc;
- chb = *(int*)(pSrc+4);
- if (((ch | chb) & unchecked((int)0x80808080)) != 0) {
- goto LongCodeWithMask32;
- }
- pSrc += 8;
- }
- break;
-
-#if BIGENDIAN
- LongCodeWithMask32:
- // be careful about the sign extension
- ch = (int)(((uint)ch) >> 16);
- LongCodeWithMask16:
- ch = (int)(((uint)ch) >> 8);
-#else // BIGENDIAN
- LongCodeWithMask32:
- LongCodeWithMask16:
- ch &= 0xFF;
-#endif // BIGENDIAN
- pSrc++;
- if (ch <= 0x7F) {
- continue;
- }
-
- LongCode:
- int chc = *pSrc;
- pSrc++;
-
- if (
- // bit 6 has to be zero
- (ch & 0x40) == 0 ||
- // we are expecting to see trailing bytes like 10vvvvvv
- (chc & unchecked((sbyte)0xC0)) != 0x80)
- {
- goto BadLongCode;
- }
-
- chc &= 0x3F;
-
- // start a new long code
- if ((ch & 0x20) != 0) {
-
- // fold the first two bytes together
- chc |= (ch & 0x0F) << 6;
-
- if ((ch & 0x10) != 0) {
- // 4 byte encoding - surrogate
- ch = *pSrc;
- if (
- // check that bit 4 is zero, the non-shortest form of surrogate
- // and the valid surrogate range 0x000000 - 0x10FFFF at the same time
- !InRange(chc >> 4, 0x01, 0x10) ||
- // we are expecting to see trailing bytes like 10vvvvvv
- (ch & unchecked((sbyte)0xC0)) != 0x80 )
- {
- goto BadLongCode;
- }
-
- chc = (chc << 6) | (ch & 0x3F);
-
- ch = *(pSrc+1);
- // we are expecting to see trailing bytes like 10vvvvvv
- if ((ch & unchecked((sbyte)0xC0)) != 0x80) {
- goto BadLongCode;
- }
- pSrc += 2;
-
- // extra byte
- charCount--;
- }
- else {
- // 3 byte encoding
- ch = *pSrc;
- if (
- // check for non-shortest form of 3 byte seq
- (chc & (0x1F << 5)) == 0 ||
- // Can't have surrogates here.
- (chc & (0xF800 >> 6) ) == (0xD800 >> 6) ||
- // we are expecting to see trailing bytes like 10vvvvvv
- (ch & unchecked((sbyte)0xC0)) != 0x80 )
- {
- goto BadLongCode;
- }
- pSrc++;
-
- // extra byte
- charCount--;
- }
- }
- else {
- // 2 byte encoding
-
- // check for non-shortest form
- if ((ch & 0x1E) == 0) {
- goto BadLongCode;
- }
- }
-
- // extra byte
- charCount--;
- }
-#endif // FASTLOOP
-
- // no pending bits at this point
- ch = 0;
- continue;
-
- BadLongCode:
- pSrc -= 2;
- ch = 0;
- continue;
- }
-
- // May have a problem if we have to flush
- if (ch != 0)
- {
- // We were already adjusting for these, so need to unadjust
- charCount += (ch >> 30);
- if (baseDecoder == null || baseDecoder.MustFlush)
- {
- // Have to do fallback for invalid bytes
- if (fallback == null)
- {
- if (baseDecoder == null)
- fallback = this.decoderFallback.CreateFallbackBuffer();
- else
- fallback = baseDecoder.FallbackBuffer;
- fallback.InternalInitialize(bytes, null);
- }
- charCount += FallbackInvalidByteSequence(pSrc, ch, fallback);
- }
- }
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(fallback == null || fallback.Remaining == 0,
- "[UTF8Encoding.GetCharCount]Expected empty fallback buffer at end");
-
- return charCount;
- }
-
- // WARNING: If we throw an error, then System.Resources.ResourceReader calls this method.
- // So if we're really broken, then that could also throw an error... recursively.
- // So try to make sure GetChars can at least process all uses by
- // System.Resources.ResourceReader!
- //
- // Note: We throw exceptions on individually encoded surrogates and other non-shortest forms.
- // If exceptions aren't turned on, then we drop all non-shortest &individual surrogates.
- //
- // To simplify maintenance, the structure of GetCharCount and GetChars should be
- // kept the same as much as possible
- internal override unsafe int GetChars(byte* bytes, int byteCount,
- char* chars, int charCount, DecoderNLS baseDecoder)
- {
- Debug.Assert(chars!=null, "[UTF8Encoding.GetChars]chars!=null");
- Debug.Assert(byteCount >=0, "[UTF8Encoding.GetChars]count >=0");
- Debug.Assert(charCount >=0, "[UTF8Encoding.GetChars]charCount >=0");
- Debug.Assert(bytes!=null, "[UTF8Encoding.GetChars]bytes!=null");
-
- byte *pSrc = bytes;
- char *pTarget = chars;
-
- byte *pEnd = pSrc+byteCount;
- char *pAllocatedBufferEnd = pTarget+charCount;
-
- int ch = 0;
-
- DecoderFallbackBuffer fallback = null;
- if (baseDecoder != null) {
- UTF8Decoder decoder = (UTF8Decoder)baseDecoder;
- ch = decoder.bits;
-
- // Shouldn't have anything in fallback buffer for GetChars
- // (don't have to check m_throwOnOverflow for chars, we always use all or none so always should be empty)
- Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[UTF8Encoding.GetChars]Expected empty fallback buffer at start");
- }
-
- for (;;)
- {
- // SLOWLOOP: does all range checks, handles all special cases, but it is slow
-
- if (pSrc >= pEnd) {
- break;
- }
-
- if (ch == 0) {
- // no pending bits
- goto ReadChar;
- }
-
- // read next byte. The JIT optimization seems to be getting confused when
- // compiling "ch = *pSrc++;", so rather use "ch = *pSrc; pSrc++;" instead
- int cha = *pSrc;
- pSrc++;
-
- // we are expecting to see trailing bytes like 10vvvvvv
- if ((cha & unchecked((sbyte)0xC0)) != 0x80) {
- // This can be a valid starting byte for another UTF8 byte sequence, so let's put
- // the current byte back, and try to see if this is a valid byte for another UTF8 byte sequence
- pSrc--;
- goto InvalidByteSequence;
- }
-
- // fold in the new byte
- ch = (ch << 6) | (cha & 0x3F);
-
- if ((ch & FinalByte) == 0) {
- // Not at last byte yet
- Debug.Assert( (ch & (SupplimentarySeq | ThreeByteSeq)) != 0,
- "[UTF8Encoding.GetChars]Invariant volation");
-
- if ((ch & SupplimentarySeq) != 0) {
- // Its a 4-byte supplimentary sequence
- if ((ch & (FinalByte >> 6)) != 0) {
- // this is 3rd byte of 4 byte sequence - nothing to do
- continue;
- }
-
- // 2nd byte of 4 bytes
- // check for non-shortest form of surrogate and the valid surrogate
- // range 0x000000 - 0x10FFFF at the same time
- if (!InRange(ch & 0x1F0, 0x10, 0x100)) {
- goto InvalidByteSequence;
- }
- }
- else {
- // Must be 2nd byte of a 3-byte sequence
- // check for non-shortest form of 3 byte seq
- if ((ch & (0x1F << 5)) == 0 || // non-shortest form
- (ch & (0xF800 >> 6) ) == (0xD800 >> 6)) // illegal individually encoded surrogate
- {
- goto InvalidByteSequence;
- }
- }
- continue;
- }
-
- // ready to punch
-
- // surrogate in shortest form?
- // Might be possible to get rid of this? Already did non-shortest check for 4-byte sequence when reading 2nd byte?
- if ((ch & (SupplimentarySeq | 0x1F0000)) > SupplimentarySeq) {
- // let the range check for the second char throw the exception
- if (pTarget < pAllocatedBufferEnd) {
- *pTarget = (char)( ((ch >> 10) & 0x7FF) +
- unchecked((short)((CharUnicodeInfo.HIGH_SURROGATE_START - (0x10000 >> 10)))) );
- pTarget++;
-
- ch = (ch & 0x3FF) +
- unchecked((int)(CharUnicodeInfo.LOW_SURROGATE_START));
- }
- }
-
- goto EncodeChar;
-
- InvalidByteSequence:
- // this code fragment should be close to the gotos referencing it
- // Have to do fallback for invalid bytes
- if (fallback == null)
- {
- if (baseDecoder == null)
- fallback = this.decoderFallback.CreateFallbackBuffer();
- else
- fallback = baseDecoder.FallbackBuffer;
- fallback.InternalInitialize(bytes, pAllocatedBufferEnd);
- }
- // This'll back us up the appropriate # of bytes if we didn't get anywhere
- if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget))
- {
- // Ran out of buffer space
- // Need to throw an exception?
- Debug.Assert(pSrc >= bytes || pTarget == chars,
- "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer after fallback");
- fallback.InternalReset();
- ThrowCharsOverflow(baseDecoder, pTarget == chars);
- ch = 0;
- break;
- }
- Debug.Assert(pSrc >= bytes,
- "[UTF8Encoding.GetChars]Expected invalid byte sequence to have remained within the byte array");
- ch = 0;
- continue;
-
- ReadChar:
- ch = *pSrc;
- pSrc++;
-
- ProcessChar:
- if (ch > 0x7F) {
- // If its > 0x7F, its start of a new multi-byte sequence
-
- // bit 6 has to be non-zero
- if ((ch & 0x40) == 0) {
- goto InvalidByteSequence;
- }
-
- // start a new long code
- if ((ch & 0x20) != 0) {
- if ((ch & 0x10) != 0) {
- // 4 byte encoding - supplimentary character (2 surrogates)
-
- ch &= 0x0F;
-
- // check that bit 4 is zero and the valid supplimentary character
- // range 0x000000 - 0x10FFFF at the same time
- if (ch > 0x04) {
- ch |= 0xf0;
- goto InvalidByteSequence;
- }
-
- ch |= (FinalByte >> 3*6) | (1 << 30) | (3 << (30-2*6)) |
- (SupplimentarySeq) | (SupplimentarySeq >> 6) |
- (SupplimentarySeq >> 2*6) | (SupplimentarySeq >> 3*6);
- }
- else {
- // 3 byte encoding
- ch = (ch & 0x0F) | ( (FinalByte >> 2*6) | (1 << 30) |
- (ThreeByteSeq) | (ThreeByteSeq >> 6) | (ThreeByteSeq >> 2*6) );
- }
- }
- else {
- // 2 byte encoding
-
- ch &= 0x1F;
-
- // check for non-shortest form
- if (ch <= 1) {
- ch |= 0xc0;
- goto InvalidByteSequence;
- }
-
- ch |= (FinalByte >> 6);
- }
- continue;
- }
-
- EncodeChar:
- // write the pending character
- if (pTarget >= pAllocatedBufferEnd)
- {
- // Fix chars so we make sure to throw if we didn't output anything
- ch &= 0x1fffff;
- if (ch > 0x7f)
- {
- if (ch > 0x7ff)
- {
- if (ch >= CharUnicodeInfo.LOW_SURROGATE_START &&
- ch <= CharUnicodeInfo.LOW_SURROGATE_END)
- {
- pSrc--; // It was 4 bytes
- pTarget--; // 1 was stored already, but we can't remember 1/2, so back up
- }
- else if (ch > 0xffff)
- {
- pSrc--; // It was 4 bytes, nothing was stored
- }
- pSrc--; // It was at least 3 bytes
- }
- pSrc--; // It was at least 2 bytes
- }
- pSrc--;
-
- // Throw that we don't have enough room (pSrc could be < chars if we had started to process
- // a 4 byte sequence alredy)
- Debug.Assert(pSrc >= bytes || pTarget == chars,
- "[UTF8Encoding.GetChars]Expected pSrc to be within input buffer or throw due to no output]");
- ThrowCharsOverflow(baseDecoder, pTarget == chars);
-
- // Don't store ch in decoder, we already backed up to its start
- ch = 0;
-
- // Didn't throw, just use this buffer size.
- break;
- }
- *pTarget = (char)ch;
- pTarget++;
-
-#if FASTLOOP
- int availableChars = PtrDiff(pAllocatedBufferEnd, pTarget);
- int availableBytes = PtrDiff(pEnd, pSrc);
-
- // don't fall into the fast decoding loop if we don't have enough bytes
- // Test for availableChars is done because pStop would be <= pTarget.
- if (availableBytes <= 13) {
- // we may need as many as 1 character per byte
- if (availableChars < availableBytes) {
- // not enough output room. no pending bits at this point
- ch = 0;
- continue;
- }
-
- // try to get over the remainder of the ascii characters fast though
- byte* pLocalEnd = pEnd; // hint to get pLocalEnd enregistered
- while (pSrc < pLocalEnd) {
- ch = *pSrc;
- pSrc++;
-
- if (ch > 0x7F)
- goto ProcessChar;
-
- *pTarget = (char)ch;
- pTarget++;
- }
- // we are done
- ch = 0;
- break;
- }
-
- // we may need as many as 1 character per byte, so reduce the byte count if necessary.
- // If availableChars is too small, pStop will be before pTarget and we won't do fast loop.
- if (availableChars < availableBytes) {
- availableBytes = availableChars;
- }
-
- // To compute the upper bound, assume that all characters are ASCII characters at this point,
- // the boundary will be decreased for every non-ASCII character we encounter
- // Also, we need 7 chars reserve for the unrolled ansi decoding loop and for decoding of multibyte sequences
- char *pStop = pTarget + availableBytes - 7;
-
- while (pTarget < pStop) {
- ch = *pSrc;
- pSrc++;
-
- if (ch > 0x7F) {
- goto LongCode;
- }
- *pTarget = (char)ch;
- pTarget++;
-
- // get pSrc to be 2-byte aligned
- if ((unchecked((int)pSrc) & 0x1) != 0) {
- ch = *pSrc;
- pSrc++;
- if (ch > 0x7F) {
- goto LongCode;
- }
- *pTarget = (char)ch;
- pTarget++;
- }
-
- // get pSrc to be 4-byte aligned
- if ((unchecked((int)pSrc) & 0x2) != 0) {
- ch = *(ushort*)pSrc;
- if ((ch & 0x8080) != 0) {
- goto LongCodeWithMask16;
- }
-
- // Unfortunately, this is endianess sensitive
-#if BIGENDIAN
- *pTarget = (char)((ch >> 8) & 0x7F);
- pSrc += 2;
- *(pTarget+1) = (char)(ch & 0x7F);
- pTarget += 2;
-#else // BIGENDIAN
- *pTarget = (char)(ch & 0x7F);
- pSrc += 2;
- *(pTarget+1) = (char)((ch >> 8) & 0x7F);
- pTarget += 2;
-#endif // BIGENDIAN
- }
-
- // Run 8 characters at a time!
- while (pTarget < pStop) {
- ch = *(int*)pSrc;
- int chb = *(int*)(pSrc+4);
- if (((ch | chb) & unchecked((int)0x80808080)) != 0) {
- goto LongCodeWithMask32;
- }
-
- // Unfortunately, this is endianess sensitive
-#if BIGENDIAN
- *pTarget = (char)((ch >> 24) & 0x7F);
- *(pTarget+1) = (char)((ch >> 16) & 0x7F);
- *(pTarget+2) = (char)((ch >> 8) & 0x7F);
- *(pTarget+3) = (char)(ch & 0x7F);
- pSrc += 8;
- *(pTarget+4) = (char)((chb >> 24) & 0x7F);
- *(pTarget+5) = (char)((chb >> 16) & 0x7F);
- *(pTarget+6) = (char)((chb >> 8) & 0x7F);
- *(pTarget+7) = (char)(chb & 0x7F);
- pTarget += 8;
-#else // BIGENDIAN
- *pTarget = (char)(ch & 0x7F);
- *(pTarget+1) = (char)((ch >> 8) & 0x7F);
- *(pTarget+2) = (char)((ch >> 16) & 0x7F);
- *(pTarget+3) = (char)((ch >> 24) & 0x7F);
- pSrc += 8;
- *(pTarget+4) = (char)(chb & 0x7F);
- *(pTarget+5) = (char)((chb >> 8) & 0x7F);
- *(pTarget+6) = (char)((chb >> 16) & 0x7F);
- *(pTarget+7) = (char)((chb >> 24) & 0x7F);
- pTarget += 8;
-#endif // BIGENDIAN
- }
- break;
-
-#if BIGENDIAN
- LongCodeWithMask32:
- // be careful about the sign extension
- ch = (int)(((uint)ch) >> 16);
- LongCodeWithMask16:
- ch = (int)(((uint)ch) >> 8);
-#else // BIGENDIAN
- LongCodeWithMask32:
- LongCodeWithMask16:
- ch &= 0xFF;
-#endif // BIGENDIAN
- pSrc++;
- if (ch <= 0x7F) {
- *pTarget = (char)ch;
- pTarget++;
- continue;
- }
-
- LongCode:
- int chc = *pSrc;
- pSrc++;
-
- if (
- // bit 6 has to be zero
- (ch & 0x40) == 0 ||
- // we are expecting to see trailing bytes like 10vvvvvv
- (chc & unchecked((sbyte)0xC0)) != 0x80)
- {
- goto BadLongCode;
- }
-
- chc &= 0x3F;
-
- // start a new long code
- if ((ch & 0x20) != 0) {
-
- // fold the first two bytes together
- chc |= (ch & 0x0F) << 6;
-
- if ((ch & 0x10) != 0) {
- // 4 byte encoding - surrogate
- ch = *pSrc;
- if (
- // check that bit 4 is zero, the non-shortest form of surrogate
- // and the valid surrogate range 0x000000 - 0x10FFFF at the same time
- !InRange(chc >> 4, 0x01, 0x10) ||
- // we are expecting to see trailing bytes like 10vvvvvv
- (ch & unchecked((sbyte)0xC0)) != 0x80 )
- {
- goto BadLongCode;
- }
-
- chc = (chc << 6) | (ch & 0x3F);
-
- ch = *(pSrc+1);
- // we are expecting to see trailing bytes like 10vvvvvv
- if ((ch & unchecked((sbyte)0xC0)) != 0x80) {
- goto BadLongCode;
- }
- pSrc += 2;
-
- ch = (chc << 6) | (ch & 0x3F);
-
- *pTarget = (char)( ((ch >> 10) & 0x7FF) +
- unchecked((short)(CharUnicodeInfo.HIGH_SURROGATE_START - (0x10000 >> 10))) );
- pTarget++;
-
- ch = (ch & 0x3FF) +
- unchecked((short)(CharUnicodeInfo.LOW_SURROGATE_START));
-
- // extra byte, we're already planning 2 chars for 2 of these bytes,
- // but the big loop is testing the target against pStop, so we need
- // to subtract 2 more or we risk overrunning the input. Subtract
- // one here and one below.
- pStop--;
- }
- else {
- // 3 byte encoding
- ch = *pSrc;
- if (
- // check for non-shortest form of 3 byte seq
- (chc & (0x1F << 5)) == 0 ||
- // Can't have surrogates here.
- (chc & (0xF800 >> 6) ) == (0xD800 >> 6) ||
- // we are expecting to see trailing bytes like 10vvvvvv
- (ch & unchecked((sbyte)0xC0)) != 0x80 )
- {
- goto BadLongCode;
- }
- pSrc++;
-
- ch = (chc << 6) | (ch & 0x3F);
-
- // extra byte, we're only expecting 1 char for each of these 3 bytes,
- // but the loop is testing the target (not source) against pStop, so
- // we need to subtract 2 more or we risk overrunning the input.
- // Subtract 1 here and one more below
- pStop--;
- }
- }
- else {
- // 2 byte encoding
-
- ch &= 0x1F;
-
- // check for non-shortest form
- if (ch <= 1) {
- goto BadLongCode;
- }
- ch = (ch << 6) | chc;
- }
-
- *pTarget = (char)ch;
- pTarget++;
-
- // extra byte, we're only expecting 1 char for each of these 2 bytes,
- // but the loop is testing the target (not source) against pStop.
- // subtract an extra count from pStop so that we don't overrun the input.
- pStop--;
- }
-#endif // FASTLOOP
-
- Debug.Assert(pTarget <= pAllocatedBufferEnd, "[UTF8Encoding.GetChars]pTarget <= pAllocatedBufferEnd");
-
- // no pending bits at this point
- ch = 0;
- continue;
-
- BadLongCode:
- pSrc -= 2;
- ch = 0;
- continue;
- }
-
- if (ch != 0 && (baseDecoder == null || baseDecoder.MustFlush))
- {
- // Have to do fallback for invalid bytes
- if (fallback == null)
- {
- if (baseDecoder == null)
- fallback = this.decoderFallback.CreateFallbackBuffer();
- else
- fallback = baseDecoder.FallbackBuffer;
- fallback.InternalInitialize(bytes, pAllocatedBufferEnd);
- }
-
- // This'll back us up the appropriate # of bytes if we didn't get anywhere
- if (!FallbackInvalidByteSequence(ref pSrc, ch, fallback, ref pTarget))
- {
- Debug.Assert(pSrc >= bytes || pTarget == chars,
- "[UTF8Encoding.GetChars]Expected to throw or remain in byte buffer while flushing");
-
- // Ran out of buffer space
- // Need to throw an exception?
- fallback.InternalReset();
- ThrowCharsOverflow(baseDecoder, pTarget == chars);
- }
- Debug.Assert(pSrc >= bytes,
- "[UTF8Encoding.GetChars]Expected flushing invalid byte sequence to have remained within the byte array");
- ch = 0;
- }
-
- if (baseDecoder != null)
- {
- UTF8Decoder decoder = (UTF8Decoder)baseDecoder;
-
- // If we're storing flush data we expect all bits to be used or else
- // we're stuck in the middle of a conversion
- Debug.Assert(!baseDecoder.MustFlush || ch == 0 || !baseDecoder.m_throwOnOverflow,
- "[UTF8Encoding.GetChars]Expected no must flush or no left over bits or no throw on overflow.");
-
- // Remember our leftover bits.
- decoder.bits = ch;
-
- baseDecoder.m_bytesUsed = (int)(pSrc - bytes);
- }
-
- // Shouldn't have anything in fallback buffer for GetChars
- // (don't have to check m_throwOnOverflow for chars)
- Debug.Assert(fallback == null || fallback.Remaining == 0,
- "[UTF8Encoding.GetChars]Expected empty fallback buffer at end");
-
- return PtrDiff(pTarget, chars);
- }
-
- // During GetChars we had an invalid byte sequence
- // pSrc is backed up to the start of the bad sequence if we didn't have room to
- // fall it back. Otherwise pSrc remains wher it is.
- private unsafe bool FallbackInvalidByteSequence(
- ref byte* pSrc, int ch, DecoderFallbackBuffer fallback, ref char* pTarget)
- {
- // Get our byte[]
- byte *pStart = pSrc;
- byte[] bytesUnknown = GetBytesUnknown(ref pStart, ch);
-
- // Do the actual fallback
- if (!fallback.InternalFallback(bytesUnknown, pSrc, ref pTarget))
- {
- // Oops, it failed, back up to pStart
- pSrc = pStart;
- return false;
- }
-
- // It worked
- return true;
- }
-
- // During GetCharCount we had an invalid byte sequence
- // pSrc is used to find the index that points to the invalid bytes,
- // however the byte[] contains the fallback bytes (in case the index is -1)
- private unsafe int FallbackInvalidByteSequence(
- byte* pSrc, int ch, DecoderFallbackBuffer fallback)
- {
- // Get our byte[]
- byte[] bytesUnknown = GetBytesUnknown(ref pSrc, ch);
-
- // Do the actual fallback
- int count = fallback.InternalFallback(bytesUnknown, pSrc);
-
- // # of fallback chars expected.
- // Note that we only get here for "long" sequences, and have already unreserved
- // the count that we prereserved for the input bytes
- return count;
- }
-
- // Note that some of these bytes may have come from a previous fallback, so we cannot
- // just decrement the pointer and use the values we read. In those cases we have
- // to regenerate the original values.
- private unsafe byte[] GetBytesUnknown(ref byte* pSrc, int ch)
- {
- // Get our byte[]
- byte[] bytesUnknown = null;
-
- // See if it was a plain char
- // (have to check >= 0 because we have all sorts of wierd bit flags)
- if (ch < 0x100 && ch >= 0)
- {
- pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)ch) };
- }
- // See if its an unfinished 2 byte sequence
- else if ((ch & (SupplimentarySeq | ThreeByteSeq)) == 0)
- {
- pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)((ch & 0x1F )| 0xc0)) };
- }
- // So now we're either 2nd byte of 3 or 4 byte sequence or
- // we hit a non-trail byte or we ran out of space for 3rd byte of 4 byte sequence
- // 1st check if its a 4 byte sequence
- else if ((ch & SupplimentarySeq) != 0)
- {
- // 3rd byte of 4 byte sequence?
- if ((ch & (FinalByte >> 6)) != 0)
- {
- // 3rd byte of 4 byte sequence
- pSrc-=3;
- bytesUnknown = new byte[] {
- unchecked((byte)(((ch >> 12) & 0x07) | 0xF0)),
- unchecked((byte)(((ch >> 6) & 0x3F) | 0x80)),
- unchecked((byte)(((ch) & 0x3F) | 0x80)) };
- }
- else if ((ch & (FinalByte >> 12)) != 0)
- {
- // 2nd byte of a 4 byte sequence
- pSrc-=2;
- bytesUnknown = new byte[] {
- unchecked((byte)(((ch >> 6) & 0x07) | 0xF0)),
- unchecked((byte)(((ch) & 0x3F) | 0x80)) };
- }
- else
- {
- // 4th byte of a 4 byte sequence
- pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)(((ch) & 0x07) | 0xF0))};
- }
- }
- else
- {
- // 2nd byte of 3 byte sequence?
- if ((ch & (FinalByte >> 6)) != 0)
- {
- // So its 2nd byte of a 3 byte sequence
- pSrc-=2;
- bytesUnknown = new byte[] {
- unchecked((byte)(((ch >> 6) & 0x0F) | 0xE0)), unchecked ((byte)(((ch) & 0x3F) | 0x80)) };
- }
- else
- {
- // 1st byte of a 3 byte sequence
- pSrc--;
- bytesUnknown = new byte[] { unchecked((byte)(((ch) & 0x0F) | 0xE0))};
- }
- }
-
- return bytesUnknown;
- }
-
-
- public override Decoder GetDecoder() {
- return new UTF8Decoder(this);
- }
-
-
- public override Encoder GetEncoder() {
- return new UTF8Encoder(this);
- }
-
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // Max 3 bytes per char. (4 bytes per 2 chars for surrogates)
- byteCount *= 3;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Figure out our length, 1 char per input byte + 1 char if 1st byte is last byte of 4 byte surrogate pair
- long charCount = ((long)byteCount + 1);
-
- // Non-shortest form would fall back, so get max count from fallback.
- // So would 11... followed by 11..., so you could fall back every byte
- if (DecoderFallback.MaxCharCount > 1)
- {
- charCount *= DecoderFallback.MaxCharCount;
- }
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
-
- public override byte[] GetPreamble()
- {
- if (emitUTF8Identifier) {
- // Allocate new array to prevent users from modifying it.
- return new byte[3] { 0xEF, 0xBB, 0xBF };
- }
- else
- return EmptyArray<Byte>.Value;
- }
-
-
- public override bool Equals(Object value) {
- UTF8Encoding that = value as UTF8Encoding;
- if (that != null) {
- return (emitUTF8Identifier == that.emitUTF8Identifier) &&
-// (isThrowException == that.isThrowException) && // Same as encoder/decoderfallbacks being exception
- (EncoderFallback.Equals(that.EncoderFallback)) &&
- (DecoderFallback.Equals(that.DecoderFallback));
- }
- return (false);
- }
-
-
- public override int GetHashCode() {
- //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable.
- return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
- UTF8_CODEPAGE + (emitUTF8Identifier?1:0);
- }
-
- [Serializable]
- internal class UTF8Encoder : EncoderNLS, ISerializable
- {
- // We must save a high surrogate value until the next call, looking
- // for a low surrogate value.
- internal int surrogateChar;
-
- public UTF8Encoder(UTF8Encoding encoding) : base(encoding)
- {
- // base calls reset
- }
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal UTF8Encoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get common info
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- // SurrogateChar happens to mean the same thing
- this.surrogateChar = (int)info.GetValue("surrogateChar", typeof(int));
-
- try
- {
- this.m_fallback = (EncoderFallback) info.GetValue("m_fallback", typeof(EncoderFallback));
- }
- catch (SerializationException)
- {
- this.m_fallback = null;
- }
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Save Whidbey data
- // Just need Everett maxCharSize (BaseCodePageEncoding) or m_maxByteSize (MLangBaseCodePageEncoding)
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("surrogateChar", this.surrogateChar);
-
- info.AddValue("m_fallback", this.m_fallback);
-
- // Extra stuff for Everett that Whidbey doesn't use
- info.AddValue("storedSurrogate", this.surrogateChar > 0 ? true : false);
- info.AddValue("mustFlush", false); // Everett doesn't actually use this either, but it accidently serialized it!
- }
-
- public override void Reset()
-
- {
- this.surrogateChar = 0;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our encoder?
- internal override bool HasState
- {
- get
- {
- return (this.surrogateChar != 0);
- }
- }
- }
-
- [Serializable]
- internal class UTF8Decoder : DecoderNLS, ISerializable
- {
- // We'll need to remember the previous information. See the comments around definition
- // of FinalByte for details.
- internal int bits;
-
- public UTF8Decoder(UTF8Encoding encoding) : base(encoding)
- {
- // base calls reset
- }
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal UTF8Decoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get common info
- this.m_encoding = (Encoding)info.GetValue("encoding", typeof(Encoding));
-
- try
- {
- // Get whidbey version of bits
- this.bits = (int)info.GetValue("wbits", typeof(int));
- this.m_fallback = (DecoderFallback) info.GetValue("m_fallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- // Everett calls bits bits instead of wbits, so this is Everett
- this.bits = 0;
- this.m_fallback = null;
- }
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Save new Whidbey data
- info.AddValue("encoding", this.m_encoding);
- info.AddValue("wbits", this.bits); // Special whidbey bits name
- info.AddValue("m_fallback", this.m_fallback);
-
- // Everett has extra stuff, we set it all to 0 in case this deserializes in Everett
- info.AddValue("bits", (int)0);
- info.AddValue("trailCount", (int)0);
- info.AddValue("isSurrogate", false);
- info.AddValue("byteSequence", (int)0);
- }
-
- public override void Reset()
- {
- this.bits = 0;
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- return (this.bits != 0);
- }
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Text/UnicodeEncoding.cs b/src/mscorlib/src/System/Text/UnicodeEncoding.cs
deleted file mode 100644
index d8ef18ab05..0000000000
--- a/src/mscorlib/src/System/Text/UnicodeEncoding.cs
+++ /dev/null
@@ -1,1826 +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.
-
-//
-// Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused.
-//
-
-namespace System.Text
-{
- using System;
- using System.Globalization;
- using System.Runtime.Serialization;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
-
- [Serializable]
- public class UnicodeEncoding : Encoding
- {
- // Used by Encoding.BigEndianUnicode/Unicode for lazy initialization
- // The initialization code will not be run until a static member of the class is referenced
- internal static readonly UnicodeEncoding s_bigEndianDefault = new UnicodeEncoding(bigEndian: true, byteOrderMark: true);
- internal static readonly UnicodeEncoding s_littleEndianDefault = new UnicodeEncoding(bigEndian: false, byteOrderMark: true);
-
- [OptionalField(VersionAdded = 2)]
- internal bool isThrowException = false;
-
- internal bool bigEndian = false;
- internal bool byteOrderMark = true;
-
- // Unicode version 2.0 character size in bytes
- public const int CharSize = 2;
-
-
- public UnicodeEncoding()
- : this(false, true)
- {
- }
-
-
- public UnicodeEncoding(bool bigEndian, bool byteOrderMark)
- : this(bigEndian, byteOrderMark, false)
- {
- }
-
-
- public UnicodeEncoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes)
- : base(bigEndian ? 1201 : 1200) //Set the data item.
- {
- this.isThrowException = throwOnInvalidBytes;
- this.bigEndian = bigEndian;
- this.byteOrderMark = byteOrderMark;
-
- // Encoding's constructor already did this, but it'll be wrong if we're throwing exceptions
- if (this.isThrowException)
- SetDefaultFallbacks();
- }
-
-#region Serialization
- [OnDeserializing]
- private void OnDeserializing(StreamingContext ctx)
- {
- // In Everett it is false. Whidbey will overwrite this value.
- isThrowException = false;
- }
-#endregion Serialization
-
- internal override void SetDefaultFallbacks()
- {
- // For UTF-X encodings, we use a replacement fallback with an empty string
- if (this.isThrowException)
- {
- this.encoderFallback = EncoderFallback.ExceptionFallback;
- this.decoderFallback = DecoderFallback.ExceptionFallback;
- }
- else
- {
- this.encoderFallback = new EncoderReplacementFallback("\xFFFD");
- this.decoderFallback = new DecoderReplacementFallback("\xFFFD");
- }
- }
-
- // NOTE: Many methods in this class forward to EncodingForwarder for
- // validating arguments/wrapping the unsafe methods in this class
- // which do the actual work. That class contains
- // shared logic for doing this which is used by
- // ASCIIEncoding, EncodingNLS, UnicodeEncoding, UTF32Encoding,
- // UTF7Encoding, and UTF8Encoding.
- // The reason the code is separated out into a static class, rather
- // than a base class which overrides all of these methods for us
- // (which is what EncodingNLS is for internal Encodings) is because
- // that's really more of an implementation detail so it's internal.
- // At the same time, C# doesn't allow a public class subclassing an
- // internal/private one, so we end up having to re-override these
- // methods in all of the public Encodings + EncodingNLS.
-
- // Returns the number of bytes required to encode a range of characters in
- // a character array.
-
- public override int GetByteCount(char[] chars, int index, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, index, count);
- }
-
- public override int GetByteCount(String s)
- {
- return EncodingForwarder.GetByteCount(this, s);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetByteCount(char* chars, int count)
- {
- return EncodingForwarder.GetByteCount(this, chars, count);
- }
-
- public override int GetBytes(String s, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, s, charIndex, charCount, bytes, byteIndex);
- }
-
- // Encodes a range of characters in a character array into a range of bytes
- // in a byte array. An exception occurs if the byte array is not large
- // enough to hold the complete encoding of the characters. The
- // GetByteCount method can be used to determine the exact number of
- // bytes that will be produced for a given range of characters.
- // Alternatively, the GetMaxByteCount method can be used to
- // determine the maximum number of bytes that will be produced for a given
- // number of characters, regardless of the actual character values.
-
- public override int GetBytes(char[] chars, int charIndex, int charCount,
- byte[] bytes, int byteIndex)
- {
- return EncodingForwarder.GetBytes(this, chars, charIndex, charCount, bytes, byteIndex);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
- {
- return EncodingForwarder.GetBytes(this, chars, charCount, bytes, byteCount);
- }
-
- // Returns the number of characters produced by decoding a range of bytes
- // in a byte array.
-
- public override int GetCharCount(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, index, count);
- }
-
- [CLSCompliant(false)]
- public override unsafe int GetCharCount(byte* bytes, int count)
- {
- return EncodingForwarder.GetCharCount(this, bytes, count);
- }
-
- public override int GetChars(byte[] bytes, int byteIndex, int byteCount,
- char[] chars, int charIndex)
- {
- return EncodingForwarder.GetChars(this, bytes, byteIndex, byteCount, chars, charIndex);
- }
-
- [CLSCompliant(false)]
- public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount)
- {
- return EncodingForwarder.GetChars(this, bytes, byteCount, chars, charCount);
- }
-
- // Returns a string containing the decoded representation of a range of
- // bytes in a byte array.
-
- public override String GetString(byte[] bytes, int index, int count)
- {
- return EncodingForwarder.GetString(this, bytes, index, count);
- }
-
- // End of overridden methods which use EncodingForwarder
-
- internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
- {
- Debug.Assert(chars!=null, "[UnicodeEncoding.GetByteCount]chars!=null");
- Debug.Assert(count >= 0, "[UnicodeEncoding.GetByteCount]count >=0");
-
- // Start by assuming each char gets 2 bytes
- int byteCount = count << 1;
-
- // Check for overflow in byteCount
- // (If they were all invalid chars, this would actually be wrong,
- // but that's a ridiculously large # so we're not concerned about that case)
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- char* charStart = chars;
- char* charEnd = chars + count;
- char charLeftOver = (char)0;
-
- bool wasHereBefore = false;
-
- // Need -1 to check 2 at a time. If we have an even #, longChars will go
- // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars
- // will go from longEnd - 1 long to longEnd. (Might not get to use this)
- ulong* longEnd = (ulong*)(charEnd - 3);
-
- // For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
-
- if (encoder != null)
- {
- charLeftOver = encoder.charLeftOver;
-
- // Assume extra bytes to encode charLeftOver if it existed
- if (charLeftOver > 0)
- byteCount+=2;
-
- // We mustn't have left over fallback data when counting
- if (encoder.InternalHasFallbackBuffer)
- {
- fallbackBuffer = encoder.FallbackBuffer;
- if (fallbackBuffer.Remaining > 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
- }
- }
-
- char ch;
- TryAgain:
-
- while (((ch = (fallbackBuffer == null) ? (char)0 :fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, maybe we can do it fast
-#if !NO_FAST_UNICODE_LOOP
-#if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards.
- if ( bigEndian &&
-#else
- if ( !bigEndian &&
-#endif // BIGENDIAN
-
-#if BIT64 // 64 bit CPU needs to be long aligned for this to work.
- charLeftOver == 0 && (unchecked((long)chars) & 7) == 0)
-#else
- charLeftOver == 0 && (unchecked((int)chars) & 3) == 0)
-#endif
- {
- // Need new char* so we can check 4 at a time
- ulong* longChars = (ulong*)chars;
-
- while (longChars < longEnd)
- {
- // See if we potentially have surrogates (0x8000 bit set)
- // (We're either big endian on a big endian machine or little endian on
- // a little endian machine so this'll work)
- if ((0x8000800080008000 & *longChars) != 0)
- {
- // See if any of these are high or low surrogates (0xd800 - 0xdfff). If the high
- // 5 bits looks like 11011, then its a high or low surrogate.
- // We do the & f800 to filter the 5 bits, then ^ d800 to ensure the 0 isn't set.
- // Note that we expect BMP characters to be more common than surrogates
- // & each char with 11111... then ^ with 11011. Zeroes then indicate surrogates
- ulong uTemp = (0xf800f800f800f800 & *longChars) ^ 0xd800d800d800d800;
-
- // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate
- // but no clue if they're high or low.
- // If each of the 4 characters are non-zero, then none are surrogates.
- if ((uTemp & 0xFFFF000000000000) == 0 ||
- (uTemp & 0x0000FFFF00000000) == 0 ||
- (uTemp & 0x00000000FFFF0000) == 0 ||
- (uTemp & 0x000000000000FFFF) == 0)
- {
- // It has at least 1 surrogate, but we don't know if they're high or low surrogates,
- // or if there's 1 or 4 surrogates
-
- // If they happen to be high/low/high/low, we may as well continue. Check the next
- // bit to see if its set (low) or not (high) in the right pattern
-#if BIGENDIAN
- if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xd800dc00d800dc00) != 0)
-#else
- if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xdc00d800dc00d800) != 0)
-#endif
- {
- // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high
- // was hoped for or the 0x0400 bit wasn't set where a low was hoped for.
-
- // Drop out to the slow loop to resolve the surrogates
- break;
- }
- // else they are all surrogates in High/Low/High/Low order, so we can use them.
- }
- // else none are surrogates, so we can use them.
- }
- // else all < 0x8000 so we can use them
-
- // We already counted these four chars, go to next long.
- longChars++;
- }
-
- chars = (char*)longChars;
-
- if (chars >= charEnd)
- break;
- }
-#endif // !NO_FAST_UNICODE_LOOP
-
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
- else
- {
- // We weren't preallocating fallback space.
- byteCount+=2;
- }
-
- // Check for high or low surrogates
- if (ch >= 0xd800 && ch <= 0xdfff)
- {
- // Was it a high surrogate?
- if (ch <= 0xdbff)
- {
- // Its a high surrogate, if we already had a high surrogate do its fallback
- if (charLeftOver > 0)
- {
- // Unwind the current character, this should be safe because we
- // don't have leftover data in the fallback, so chars must have
- // advanced already.
- Debug.Assert(chars > charStart,
- "[UnicodeEncoding.GetByteCount]Expected chars to have advanced in unexpected high surrogate");
- chars--;
-
- // If previous high surrogate deallocate 2 bytes
- byteCount -= 2;
-
- // Fallback the previous surrogate
- // Need to initialize fallback buffer?
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
- }
-
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
-
- // Now no high surrogate left over
- charLeftOver = (char)0;
- continue;
- }
-
- // Remember this high surrogate
- charLeftOver = ch;
- continue;
- }
-
-
- // Its a low surrogate
- if (charLeftOver == 0)
- {
- // Expected a previous high surrogate.
- // Don't count this one (we'll count its fallback if necessary)
- byteCount -= 2;
-
- // fallback this one
- // Need to initialize fallback buffer?
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
- }
- fallbackBuffer.InternalFallback(ch, ref chars);
- continue;
- }
-
- // Valid surrogate pair, add our charLeftOver
- charLeftOver = (char)0;
- continue;
- }
- else if (charLeftOver > 0)
- {
- // Expected a low surrogate, but this char is normal
-
- // Rewind the current character, fallback previous character.
- // this should be safe because we don't have leftover data in the
- // fallback, so chars must have advanced already.
- Debug.Assert(chars > charStart,
- "[UnicodeEncoding.GetByteCount]Expected chars to have advanced when expected low surrogate");
- chars--;
-
- // fallback previous chars
- // Need to initialize fallback buffer?
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
- }
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
-
- // Ignore charLeftOver or throw
- byteCount-=2;
- charLeftOver = (char)0;
-
- continue;
- }
-
- // Ok we had something to add (already counted)
- }
-
- // Don't allocate space for left over char
- if (charLeftOver > 0)
- {
- byteCount -= 2;
-
- // If we have to flush, stick it in fallback and try again
- if (encoder == null || encoder.MustFlush)
- {
- if (wasHereBefore)
- {
- // Throw it, using our complete character
- throw new ArgumentException(
- Environment.GetResourceString("Argument_RecursiveFallback",
- charLeftOver), nameof(chars));
- }
- else
- {
- // Need to initialize fallback buffer?
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
- }
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
- charLeftOver = (char)0;
- wasHereBefore = true;
- goto TryAgain;
- }
- }
- }
-
- // Shouldn't have anything in fallback buffer for GetByteCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[UnicodeEncoding.GetByteCount]Expected empty fallback buffer at end");
-
- // Don't remember fallbackBuffer.encoder for counting
- return byteCount;
- }
-
- internal override unsafe int GetBytes(char* chars, int charCount,
- byte* bytes, int byteCount, EncoderNLS encoder)
- {
- Debug.Assert(chars!=null, "[UnicodeEncoding.GetBytes]chars!=null");
- Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetBytes]byteCount >=0");
- Debug.Assert(charCount >=0, "[UnicodeEncoding.GetBytes]charCount >=0");
- Debug.Assert(bytes!=null, "[UnicodeEncoding.GetBytes]bytes!=null");
-
- char charLeftOver = (char)0;
- char ch;
- bool wasHereBefore = false;
-
-
- byte* byteEnd = bytes + byteCount;
- char* charEnd = chars + charCount;
- byte* byteStart = bytes;
- char* charStart = chars;
-
- // For fallback we may need a fallback buffer
- EncoderFallbackBuffer fallbackBuffer = null;
-
- // Get our encoder, but don't clear it yet.
- if (encoder != null)
- {
- charLeftOver = encoder.charLeftOver;
-
- // We mustn't have left over fallback data when counting
- if (encoder.InternalHasFallbackBuffer)
- {
- // We always need the fallback buffer in get bytes so we can flush any remaining ones if necessary
- fallbackBuffer = encoder.FallbackBuffer;
- if (fallbackBuffer.Remaining > 0 && encoder.m_throwOnOverflow)
- throw new ArgumentException(Environment.GetResourceString("Argument_EncoderFallbackNotEmpty",
- this.EncodingName, encoder.Fallback.GetType()));
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, false);
- }
- }
-
- TryAgain:
- while (((ch = (fallbackBuffer == null) ?
- (char)0 : fallbackBuffer.InternalGetNextChar()) != 0) ||
- chars < charEnd)
- {
- // First unwind any fallback
- if (ch == 0)
- {
- // No fallback, maybe we can do it fast
-#if !NO_FAST_UNICODE_LOOP
-#if BIGENDIAN // If endianess is backwards then each pair of bytes would be backwards.
- if ( bigEndian &&
-#else
- if ( !bigEndian &&
-#endif // BIGENDIAN
-#if BIT64 // 64 bit CPU needs to be long aligned for this to work, 32 bit CPU needs to be 32 bit aligned
- (unchecked((long)chars) & 7) == 0 && (unchecked((long)bytes) & 7) == 0 &&
-#else
- (unchecked((int)chars) & 3) == 0 && (unchecked((int)bytes) & 3) == 0 &&
-#endif // BIT64
- charLeftOver == 0)
- {
- // Need -1 to check 2 at a time. If we have an even #, longChars will go
- // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars
- // will go from longEnd - 1 long to longEnd. (Might not get to use this)
- // We can only go iCount units (limited by shorter of char or byte buffers.
- ulong* longEnd = (ulong*)(chars - 3 +
- (((byteEnd - bytes) >> 1 < charEnd - chars) ?
- (byteEnd - bytes) >> 1 : charEnd - chars));
-
- // Need new char* so we can check 4 at a time
- ulong* longChars = (ulong*)chars;
- ulong* longBytes = (ulong*)bytes;
-
- while (longChars < longEnd)
- {
- // See if we potentially have surrogates (0x8000 bit set)
- // (We're either big endian on a big endian machine or little endian on
- // a little endian machine so this'll work)
- if ((0x8000800080008000 & *longChars) != 0)
- {
- // See if any of these are high or low surrogates (0xd800 - 0xdfff). If the high
- // 5 bits looks like 11011, then its a high or low surrogate.
- // We do the & f800 to filter the 5 bits, then ^ d800 to ensure the 0 isn't set.
- // Note that we expect BMP characters to be more common than surrogates
- // & each char with 11111... then ^ with 11011. Zeroes then indicate surrogates
- ulong uTemp = (0xf800f800f800f800 & *longChars) ^ 0xd800d800d800d800;
-
- // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate
- // but no clue if they're high or low.
- // If each of the 4 characters are non-zero, then none are surrogates.
- if ((uTemp & 0xFFFF000000000000) == 0 ||
- (uTemp & 0x0000FFFF00000000) == 0 ||
- (uTemp & 0x00000000FFFF0000) == 0 ||
- (uTemp & 0x000000000000FFFF) == 0)
- {
- // It has at least 1 surrogate, but we don't know if they're high or low surrogates,
- // or if there's 1 or 4 surrogates
-
- // If they happen to be high/low/high/low, we may as well continue. Check the next
- // bit to see if its set (low) or not (high) in the right pattern
-#if BIGENDIAN
- if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xd800dc00d800dc00) != 0)
-#else
- if (((0xfc00fc00fc00fc00 & *longChars) ^ 0xdc00d800dc00d800) != 0)
-#endif
- {
- // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high
- // was hoped for or the 0x0400 bit wasn't set where a low was hoped for.
-
- // Drop out to the slow loop to resolve the surrogates
- break;
- }
- // else they are all surrogates in High/Low/High/Low order, so we can use them.
- }
- // else none are surrogates, so we can use them.
- }
- // else all < 0x8000 so we can use them
-
- // We can use these 4 chars.
- *longBytes = *longChars;
- longChars++;
- longBytes++;
- }
-
- chars = (char*)longChars;
- bytes = (byte*)longBytes;
-
- if (chars >= charEnd)
- break;
- }
- // Not aligned, but maybe we can still be somewhat faster
- // Also somehow this optimizes the above loop? It seems to cause something above
- // to get enregistered, but I haven't figured out how to make that happen without this loop.
- else if ((charLeftOver == 0) &&
-#if BIGENDIAN
- bigEndian &&
-#else
- !bigEndian &&
-#endif // BIGENDIAN
-
-#if BIT64
- (unchecked((long)chars) & 7) != (unchecked((long)bytes) & 7) && // Only do this if chars & bytes are out of line, otherwise faster loop'll be faster next time
-#else
- (unchecked((int)chars) & 3) != (unchecked((int)bytes) & 3) && // Only do this if chars & bytes are out of line, otherwise faster loop'll be faster next time
-#endif // BIT64
- (unchecked((int)(bytes)) & 1) == 0 )
- {
- // # to use
- long iCount = ((byteEnd - bytes) >> 1 < charEnd - chars) ?
- (byteEnd - bytes) >> 1 : charEnd - chars;
-
- // Need new char*
- char* charOut = ((char*)bytes); // a char* for our output
- char* tempEnd = chars + iCount - 1; // Our end pointer
-
- while (chars < tempEnd)
- {
- if (*chars >= (char)0xd800 && *chars <= (char)0xdfff)
- {
- // break for fallback for low surrogate
- if (*chars >= 0xdc00)
- break;
-
- // break if next one's not a low surrogate (will do fallback)
- if (*(chars+1) < 0xdc00 || *(chars+1) > 0xdfff)
- break;
-
- // They both exist, use them
- }
- // If 2nd char is surrogate & this one isn't then only add one
- else if (*(chars+1) >= (char)0xd800 && *(chars+1) <= 0xdfff)
- {
- *charOut = *chars;
- charOut++;
- chars++;
- continue;
- }
-
- *charOut = *chars;
- *(charOut+1) = *(chars+1);
- charOut+=2;
- chars+=2;
-
- }
-
- bytes=(byte*)charOut;
-
- if (chars >= charEnd)
- break;
- }
-#endif // !NO_FAST_UNICODE_LOOP
-
- // No fallback, just get next char
- ch = *chars;
- chars++;
- }
-
- // Check for high or low surrogates
- if (ch >= 0xd800 && ch <= 0xdfff)
- {
- // Was it a high surrogate?
- if (ch <= 0xdbff)
- {
- // Its a high surrogate, see if we already had a high surrogate
- if (charLeftOver > 0)
- {
- // Unwind the current character, this should be safe because we
- // don't have leftover data in the fallback, so chars must have
- // advanced already.
- Debug.Assert(chars > charStart,
- "[UnicodeEncoding.GetBytes]Expected chars to have advanced in unexpected high surrogate");
- chars--;
-
- // Fallback the previous surrogate
- // Might need to create our fallback buffer
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
- }
-
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
-
- charLeftOver = (char)0;
- continue;
- }
-
- // Remember this high surrogate
- charLeftOver = ch;
- continue;
- }
-
- // Its a low surrogate
- if (charLeftOver == 0)
- {
- // We'll fall back this one
- // Might need to create our fallback buffer
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
- }
-
- fallbackBuffer.InternalFallback(ch, ref chars);
- continue;
- }
-
- // Valid surrogate pair, add our charLeftOver
- if (bytes + 3 >= byteEnd)
- {
- // Not enough room to add this surrogate pair
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack)
- {
- // These must have both been from the fallbacks.
- // Both of these MUST have been from a fallback because if the 1st wasn't
- // from a fallback, then a high surrogate followed by an illegal char
- // would've caused the high surrogate to fall back. If a high surrogate
- // fell back, then it was consumed and both chars came from the fallback.
- fallbackBuffer.MovePrevious(); // Didn't use either fallback surrogate
- fallbackBuffer.MovePrevious();
- }
- else
- {
- // If we don't have enough room, then either we should've advanced a while
- // or we should have bytes==byteStart and throw below
- Debug.Assert(chars > charStart + 1 || bytes == byteStart,
- "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair");
- chars-=2; // Didn't use either surrogate
- }
- ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
- charLeftOver = (char)0; // we'll retry it later
- break; // Didn't throw, but stop 'til next time.
- }
-
- if (bigEndian)
- {
- *(bytes++) = (byte)(charLeftOver >> 8);
- *(bytes++) = (byte)charLeftOver;
- }
- else
- {
- *(bytes++) = (byte)charLeftOver;
- *(bytes++) = (byte)(charLeftOver >> 8);
- }
-
- charLeftOver = (char)0;
- }
- else if (charLeftOver > 0)
- {
- // Expected a low surrogate, but this char is normal
-
- // Rewind the current character, fallback previous character.
- // this should be safe because we don't have leftover data in the
- // fallback, so chars must have advanced already.
- Debug.Assert(chars > charStart,
- "[UnicodeEncoding.GetBytes]Expected chars to have advanced after expecting low surrogate");
- chars--;
-
- // fallback previous chars
- // Might need to create our fallback buffer
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
- }
-
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
-
- // Ignore charLeftOver or throw
- charLeftOver = (char)0;
- continue;
- }
-
- // Ok, we have a char to add
- if (bytes + 1 >= byteEnd)
- {
- // Couldn't add this char
- if (fallbackBuffer != null && fallbackBuffer.bFallingBack)
- fallbackBuffer.MovePrevious(); // Not using this fallback char
- else
- {
- // Lonely charLeftOver (from previous call) would've been caught up above,
- // so this must be a case where we've already read an input char.
- Debug.Assert(chars > charStart,
- "[UnicodeEncoding.GetBytes]Expected chars to have advanced for failed fallback");
- chars--; // Not using this char
- }
- ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written)
- break; // didn't throw, just stop
- }
-
- if (bigEndian)
- {
- *(bytes++) = (byte)(ch >> 8);
- *(bytes++) = (byte)ch;
- }
- else
- {
- *(bytes++) = (byte)ch;
- *(bytes++) = (byte)(ch >> 8);
- }
- }
-
- // Don't allocate space for left over char
- if (charLeftOver > 0)
- {
- // If we aren't flushing we need to fall this back
- if (encoder == null || encoder.MustFlush)
- {
- if (wasHereBefore)
- {
- // Throw it, using our complete character
- throw new ArgumentException(
- Environment.GetResourceString("Argument_RecursiveFallback",
- charLeftOver), nameof(chars));
- }
- else
- {
- // If we have to flush, stick it in fallback and try again
- // Might need to create our fallback buffer
- if (fallbackBuffer == null)
- {
- if (encoder == null)
- fallbackBuffer = this.encoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = encoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true);
- }
-
- // If we're not flushing, this'll remember the left over character.
- fallbackBuffer.InternalFallback(charLeftOver, ref chars);
-
- charLeftOver = (char)0;
- wasHereBefore = true;
- goto TryAgain;
- }
- }
-
- }
-
- // Not flushing, remember it in the encoder
- if (encoder != null)
- {
- encoder.charLeftOver = charLeftOver;
- encoder.m_charsUsed = (int)(chars - charStart);
- }
-
- // Remember charLeftOver if we must, or clear it if we're flushing
- // (charLeftOver should be 0 if we're flushing)
- Debug.Assert((encoder != null && !encoder.MustFlush) || charLeftOver == (char)0,
- "[UnicodeEncoding.GetBytes] Expected no left over characters if flushing");
-
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0 ||
- encoder == null || !encoder.m_throwOnOverflow,
- "[UnicodeEncoding.GetBytes]Expected empty fallback buffer if not converting");
-
- // We used to copy it fast, but this doesn't check for surrogates
- // System.IO.__UnmanagedMemoryStream.memcpyimpl(bytes, (byte*)chars, usedByteCount);
-
- return (int)(bytes - byteStart);
- }
-
- internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder)
- {
- Debug.Assert(bytes!=null, "[UnicodeEncoding.GetCharCount]bytes!=null");
- Debug.Assert(count >= 0, "[UnicodeEncoding.GetCharCount]count >=0");
-
- UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
-
- byte* byteEnd = bytes + count;
- byte* byteStart = bytes;
-
- // Need last vars
- int lastByte = -1;
- char lastChar = (char)0;
-
- // Start by assuming same # of chars as bytes
- int charCount = count >> 1;
-
- // Need -1 to check 2 at a time. If we have an even #, longBytes will go
- // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longBytes
- // will go from longEnd - 1 long to longEnd. (Might not get to use this)
- ulong* longEnd = (ulong*)(byteEnd - 7);
-
- // For fallback we may need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
-
- if (decoder != null)
- {
- lastByte = decoder.lastByte;
- lastChar = decoder.lastChar;
-
- // Assume extra char if last char was around
- if (lastChar > 0)
- charCount++;
-
- // Assume extra char if extra last byte makes up odd # of input bytes
- if (lastByte >= 0 && (count & 1) == 1)
- {
- charCount++;
- }
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at start");
- }
-
- while (bytes < byteEnd)
- {
- // If we're aligned then maybe we can do it fast
- // This'll hurt if we're unaligned because we'll always test but never be aligned
-#if !NO_FAST_UNICODE_LOOP
-#if BIGENDIAN
- if (bigEndian &&
-#else // BIGENDIAN
- if (!bigEndian &&
-#endif // BIGENDIAN
-#if BIT64 // win64 has to be long aligned
- (unchecked((long)bytes) & 7) == 0 &&
-#else
- (unchecked((int)bytes) & 3) == 0 &&
-#endif // BIT64
- lastByte == -1 && lastChar == 0)
- {
- // Need new char* so we can check 4 at a time
- ulong* longBytes = (ulong*)bytes;
-
- while (longBytes < longEnd)
- {
- // See if we potentially have surrogates (0x8000 bit set)
- // (We're either big endian on a big endian machine or little endian on
- // a little endian machine so this'll work)
- if ((0x8000800080008000 & *longBytes) != 0)
- {
- // See if any of these are high or low surrogates (0xd800 - 0xdfff). If the high
- // 5 bits looks like 11011, then its a high or low surrogate.
- // We do the & f800 to filter the 5 bits, then ^ d800 to ensure the 0 isn't set.
- // Note that we expect BMP characters to be more common than surrogates
- // & each char with 11111... then ^ with 11011. Zeroes then indicate surrogates
- ulong uTemp = (0xf800f800f800f800 & *longBytes) ^ 0xd800d800d800d800;
-
- // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate
- // but no clue if they're high or low.
- // If each of the 4 characters are non-zero, then none are surrogates.
- if ((uTemp & 0xFFFF000000000000) == 0 ||
- (uTemp & 0x0000FFFF00000000) == 0 ||
- (uTemp & 0x00000000FFFF0000) == 0 ||
- (uTemp & 0x000000000000FFFF) == 0)
- {
- // It has at least 1 surrogate, but we don't know if they're high or low surrogates,
- // or if there's 1 or 4 surrogates
-
- // If they happen to be high/low/high/low, we may as well continue. Check the next
- // bit to see if its set (low) or not (high) in the right pattern
-#if BIGENDIAN
- if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xd800dc00d800dc00) != 0)
-#else
- if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xdc00d800dc00d800) != 0)
-#endif
- {
- // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high
- // was hoped for or the 0x0400 bit wasn't set where a low was hoped for.
-
- // Drop out to the slow loop to resolve the surrogates
- break;
- }
- // else they are all surrogates in High/Low/High/Low order, so we can use them.
- }
- // else none are surrogates, so we can use them.
- }
- // else all < 0x8000 so we can use them
-
- // We can use these 4 chars.
- longBytes++;
- }
-
- bytes = (byte*)longBytes;
-
- if (bytes >= byteEnd)
- break;
- }
-#endif // !NO_FAST_UNICODE_LOOP
-
- // Get 1st byte
- if (lastByte < 0)
- {
- lastByte = *bytes++;
- if (bytes >= byteEnd) break;
- }
-
- // Get full char
- char ch;
- if (bigEndian)
- {
- ch = (char)(lastByte << 8 | *(bytes++));
- }
- else
- {
- ch = (char)(*(bytes++) << 8 | lastByte);
- }
- lastByte = -1;
-
- // See if the char's valid
- if (ch >= 0xd800 && ch <= 0xdfff)
- {
- // Was it a high surrogate?
- if (ch <= 0xdbff)
- {
- // Its a high surrogate, if we had one then do fallback for previous one
- if (lastChar > 0)
- {
- // Ignore previous bad high surrogate
- charCount--;
-
- // Get fallback for previous high surrogate
- // Note we have to reconstruct bytes because some may have been in decoder
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(lastChar >> 8)), unchecked((byte)lastChar) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, null);
- }
-
- // Get fallback.
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
- }
-
- // Ignore the last one which fell back already,
- // and remember the new high surrogate
- lastChar = ch;
- continue;
- }
-
- // Its a low surrogate
- if (lastChar == 0)
- {
- // Expected a previous high surrogate
- charCount--;
-
- // Get fallback for this low surrogate
- // Note we have to reconstruct bytes because some may have been in decoder
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(ch >> 8)), unchecked((byte)ch) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)ch), unchecked((byte)(ch >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, null);
- }
-
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
-
- // Ignore this one (we already did its fallback)
- continue;
- }
-
- // Valid surrogate pair, already counted.
- lastChar = (char)0;
- }
- else if (lastChar > 0)
- {
- // Had a high surrogate, expected a low surrogate
- // Uncount the last high surrogate
- charCount--;
-
- // fall back the high surrogate.
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(lastChar >> 8)), unchecked((byte)lastChar) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, null);
- }
-
- // Already subtracted high surrogate
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
-
- // Not left over now, clear previous high surrogate and continue to add current char
- lastChar = (char)0;
- }
-
- // Valid char, already counted
- }
-
- // Extra space if we can't use decoder
- if (decoder == null || decoder.MustFlush)
- {
- if (lastChar > 0)
- {
- // No hanging high surrogates allowed, do fallback and remove count for it
- charCount--;
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(lastChar >> 8)), unchecked((byte)lastChar) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, null);
- }
-
- charCount += fallbackBuffer.InternalFallback(byteBuffer, bytes);
-
- lastChar = (char)0;
- }
-
- if (lastByte >= 0)
- {
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, null);
- }
-
- // No hanging odd bytes allowed if must flush
- charCount += fallbackBuffer.InternalFallback( new byte[] { unchecked((byte)lastByte) }, bytes);
- lastByte = -1;
- }
- }
-
- // If we had a high surrogate left over, we can't count it
- if (lastChar > 0)
- charCount--;
-
- // Shouldn't have anything in fallback buffer for GetCharCount
- // (don't have to check m_throwOnOverflow for count)
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[UnicodeEncoding.GetCharCount]Expected empty fallback buffer at end");
-
- return charCount;
- }
-
- internal override unsafe int GetChars(byte* bytes, int byteCount,
- char* chars, int charCount, DecoderNLS baseDecoder )
- {
- Debug.Assert(chars!=null, "[UnicodeEncoding.GetChars]chars!=null");
- Debug.Assert(byteCount >=0, "[UnicodeEncoding.GetChars]byteCount >=0");
- Debug.Assert(charCount >=0, "[UnicodeEncoding.GetChars]charCount >=0");
- Debug.Assert(bytes!=null, "[UnicodeEncoding.GetChars]bytes!=null");
-
- UnicodeEncoding.Decoder decoder = (UnicodeEncoding.Decoder)baseDecoder;
-
- // Need last vars
- int lastByte = -1;
- char lastChar = (char)0;
-
- // Get our decoder (but don't clear it yet)
- if (decoder != null)
- {
- lastByte = decoder.lastByte;
- lastChar = decoder.lastChar;
-
- // Shouldn't have anything in fallback buffer for GetChars
- // (don't have to check m_throwOnOverflow for chars)
- Debug.Assert(!decoder.InternalHasFallbackBuffer || decoder.FallbackBuffer.Remaining == 0,
- "[UnicodeEncoding.GetChars]Expected empty fallback buffer at start");
- }
-
- // For fallback we may need a fallback buffer
- DecoderFallbackBuffer fallbackBuffer = null;
-
- byte* byteEnd = bytes + byteCount;
- char* charEnd = chars + charCount;
- byte* byteStart = bytes;
- char* charStart = chars;
-
- while (bytes < byteEnd)
- {
- // If we're aligned then maybe we can do it fast
- // This'll hurt if we're unaligned because we'll always test but never be aligned
-#if !NO_FAST_UNICODE_LOOP
-#if BIGENDIAN
- if (bigEndian &&
-#else // BIGENDIAN
- if (!bigEndian &&
-#endif // BIGENDIAN
-#if BIT64 // win64 has to be long aligned
- (unchecked((long)chars) & 7) == 0 && (unchecked((long)bytes) & 7) == 0 &&
-#else
- (unchecked((int)chars) & 3) == 0 && (unchecked((int)bytes) & 3) == 0 &&
-#endif // BIT64
- lastByte == -1 && lastChar == 0)
- {
- // Need -1 to check 2 at a time. If we have an even #, longChars will go
- // from longEnd - 1/2 long to longEnd + 1/2 long. If we're odd, longChars
- // will go from longEnd - 1 long to longEnd. (Might not get to use this)
- // We can only go iCount units (limited by shorter of char or byte buffers.
- ulong* longEnd = (ulong*)(bytes - 7 +
- (((byteEnd - bytes) >> 1 < charEnd - chars) ?
- (byteEnd - bytes) : (charEnd - chars) << 1));
-
- // Need new char* so we can check 4 at a time
- ulong* longBytes = (ulong*)bytes;
- ulong* longChars = (ulong*)chars;
-
- while (longBytes < longEnd)
- {
- // See if we potentially have surrogates (0x8000 bit set)
- // (We're either big endian on a big endian machine or little endian on
- // a little endian machine so this'll work)
- if ((0x8000800080008000 & *longBytes) != 0)
- {
- // See if any of these are high or low surrogates (0xd800 - 0xdfff). If the high
- // 5 bits looks like 11011, then its a high or low surrogate.
- // We do the & f800 to filter the 5 bits, then ^ d800 to ensure the 0 isn't set.
- // Note that we expect BMP characters to be more common than surrogates
- // & each char with 11111... then ^ with 11011. Zeroes then indicate surrogates
- ulong uTemp = (0xf800f800f800f800 & *longBytes) ^ 0xd800d800d800d800;
-
- // Check each of the 4 chars. 0 for those 16 bits means it was a surrogate
- // but no clue if they're high or low.
- // If each of the 4 characters are non-zero, then none are surrogates.
- if ((uTemp & 0xFFFF000000000000) == 0 ||
- (uTemp & 0x0000FFFF00000000) == 0 ||
- (uTemp & 0x00000000FFFF0000) == 0 ||
- (uTemp & 0x000000000000FFFF) == 0)
- {
- // It has at least 1 surrogate, but we don't know if they're high or low surrogates,
- // or if there's 1 or 4 surrogates
-
- // If they happen to be high/low/high/low, we may as well continue. Check the next
- // bit to see if its set (low) or not (high) in the right pattern
-#if BIGENDIAN
- if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xd800dc00d800dc00) != 0)
-#else
- if (((0xfc00fc00fc00fc00 & *longBytes) ^ 0xdc00d800dc00d800) != 0)
-#endif
- {
- // Either there weren't 4 surrogates, or the 0x0400 bit was set when a high
- // was hoped for or the 0x0400 bit wasn't set where a low was hoped for.
-
- // Drop out to the slow loop to resolve the surrogates
- break;
- }
- // else they are all surrogates in High/Low/High/Low order, so we can use them.
- }
- // else none are surrogates, so we can use them.
- }
- // else all < 0x8000 so we can use them
-
- // We can use these 4 chars.
- *longChars = *longBytes;
- longBytes++;
- longChars++;
- }
-
- chars = (char*)longChars;
- bytes = (byte*)longBytes;
-
- if (bytes >= byteEnd)
- break;
- }
-#endif // !NO_FAST_UNICODE_LOOP
-
- // Get 1st byte
- if (lastByte < 0)
- {
- lastByte = *bytes++;
- continue;
- }
-
- // Get full char
- char ch;
- if (bigEndian)
- {
- ch = (char)(lastByte << 8 | *(bytes++));
- }
- else
- {
- ch = (char)(*(bytes++) << 8 | lastByte);
- }
- lastByte = -1;
-
- // See if the char's valid
- if (ch >= 0xd800 && ch <= 0xdfff)
- {
- // Was it a high surrogate?
- if (ch <= 0xdbff)
- {
- // Its a high surrogate, if we had one then do fallback for previous one
- if (lastChar > 0)
- {
- // Get fallback for previous high surrogate
- // Note we have to reconstruct bytes because some may have been in decoder
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(lastChar >> 8)), unchecked((byte)lastChar) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, charEnd);
- }
-
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // couldn't fall back lonely surrogate
- // We either advanced bytes or chars should == charStart and throw below
- Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
- "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (bad surrogate)");
- bytes-=2; // didn't use these 2 bytes
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // couldn't fallback but didn't throw
- }
- }
-
- // Ignore the previous high surrogate which fell back already,
- // yet remember the current high surrogate for next time.
- lastChar = ch;
- continue;
- }
-
- // Its a low surrogate
- if (lastChar == 0)
- {
- // Expected a previous high surrogate
- // Get fallback for this low surrogate
- // Note we have to reconstruct bytes because some may have been in decoder
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(ch >> 8)), unchecked((byte)ch) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)ch), unchecked((byte)(ch >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, charEnd);
- }
-
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // couldn't fall back lonely surrogate
- // We either advanced bytes or chars should == charStart and throw below
- Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
- "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (lonely surrogate)");
- bytes-=2; // didn't use these 2 bytes
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // couldn't fallback but didn't throw
- }
-
- // Didn't throw, ignore this one (we already did its fallback)
- continue;
- }
-
- // Valid surrogate pair, add our lastChar (will need 2 chars)
- if (chars >= charEnd - 1)
- {
- // couldn't find room for this surrogate pair
- // We either advanced bytes or chars should == charStart and throw below
- Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
- "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (surrogate pair)");
- bytes-=2; // didn't use these 2 bytes
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- // Leave lastChar for next call to Convert()
- break; // couldn't fallback but didn't throw
- }
-
- *chars++ = lastChar;
- lastChar = (char)0;
- }
- else if (lastChar > 0)
- {
- // Had a high surrogate, expected a low surrogate, fall back the high surrogate.
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(lastChar >> 8)), unchecked((byte)lastChar) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, charEnd);
- }
-
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // couldn't fall back high surrogate, or char that would be next
- // We either advanced bytes or chars should == charStart and throw below
- Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
- "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (no low surrogate)");
- bytes-=2; // didn't use these 2 bytes
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // couldn't fallback but didn't throw
- }
-
- // Not left over now, clear previous high surrogate and continue to add current char
- lastChar = (char)0;
- }
-
- // Valid char, room for it?
- if (chars >= charEnd)
- {
- // 2 bytes couldn't fall back
- // We either advanced bytes or chars should == charStart and throw below
- Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
- "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (normal)");
- bytes-=2; // didn't use these bytes
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- break; // couldn't fallback but didn't throw
- }
-
- // add it
- *chars++ = ch;
- }
-
- // Remember our decoder if we must
- if (decoder == null || decoder.MustFlush)
- {
- if (lastChar > 0)
- {
- // No hanging high surrogates allowed, do fallback and remove count for it
- byte[] byteBuffer = null;
- if (bigEndian)
- {
- byteBuffer = new byte[]
- { unchecked((byte)(lastChar >> 8)), unchecked((byte)lastChar) };
- }
- else
- {
- byteBuffer = new byte[]
- { unchecked((byte)lastChar), unchecked((byte)(lastChar >> 8)) };
-
- }
-
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, charEnd);
- }
-
- if (!fallbackBuffer.InternalFallback(byteBuffer, bytes, ref chars))
- {
- // 2 bytes couldn't fall back
- // We either advanced bytes or chars should == charStart and throw below
- Debug.Assert(bytes >= byteStart + 2 || chars == charStart,
- "[UnicodeEncoding.GetChars]Expected bytes to have advanced or no output (decoder)");
- bytes-=2; // didn't use these bytes
- if (lastByte >= 0)
- bytes--; // had an extra last byte hanging around
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- // We'll remember these in our decoder though
- bytes+=2;
- if (lastByte >= 0)
- bytes++;
- goto End;
- }
-
- // done with this one
- lastChar = (char)0;
- }
-
- if (lastByte >= 0)
- {
- if (fallbackBuffer == null)
- {
- if (decoder == null)
- fallbackBuffer = this.decoderFallback.CreateFallbackBuffer();
- else
- fallbackBuffer = decoder.FallbackBuffer;
-
- // Set our internal fallback interesting things.
- fallbackBuffer.InternalInitialize(byteStart, charEnd);
- }
-
- // No hanging odd bytes allowed if must flush
- if (!fallbackBuffer.InternalFallback( new byte[] { unchecked((byte)lastByte) }, bytes, ref chars ))
- {
- // odd byte couldn't fall back
- bytes--; // didn't use this byte
- fallbackBuffer.InternalReset();
- ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output
- // didn't throw, but we'll remember it in the decoder
- bytes++;
- goto End;
- }
-
- // Didn't fail, clear buffer
- lastByte = -1;
- }
- }
-
- End:
-
- // Remember our decoder if we must
- if (decoder != null)
- {
- Debug.Assert((decoder.MustFlush == false) || ((lastChar == (char)0) && (lastByte == -1)),
- "[UnicodeEncoding.GetChars] Expected no left over chars or bytes if flushing"
-// + " " + ((int)lastChar).ToString("X4") + " " + lastByte.ToString("X2")
- );
-
- decoder.m_bytesUsed = (int)(bytes - byteStart);
- decoder.lastChar = lastChar;
- decoder.lastByte = lastByte;
- }
-
- // Used to do this the old way
- // System.IO.__UnmanagedMemoryStream.memcpyimpl((byte*)chars, bytes, byteCount);
-
- // Shouldn't have anything in fallback buffer for GetChars
- // (don't have to check m_throwOnOverflow for count or chars)
- Debug.Assert(fallbackBuffer == null || fallbackBuffer.Remaining == 0,
- "[UnicodeEncoding.GetChars]Expected empty fallback buffer at end");
-
- return (int)(chars - charStart);
- }
-
-
- public override System.Text.Encoder GetEncoder()
- {
- return new EncoderNLS(this);
- }
-
-
- public override System.Text.Decoder GetDecoder()
- {
- return new UnicodeEncoding.Decoder(this);
- }
-
-
- public override byte[] GetPreamble()
- {
- if (byteOrderMark)
- {
- // Note - we must allocate new byte[]'s here to prevent someone
- // from modifying a cached byte[].
- if (bigEndian)
- return new byte[2] { 0xfe, 0xff };
- else
- return new byte[2] { 0xff, 0xfe };
- }
- return EmptyArray<Byte>.Value;
- }
-
-
- public override int GetMaxByteCount(int charCount)
- {
- if (charCount < 0)
- throw new ArgumentOutOfRangeException(nameof(charCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback
- long byteCount = (long)charCount + 1;
-
- if (EncoderFallback.MaxCharCount > 1)
- byteCount *= EncoderFallback.MaxCharCount;
-
- // 2 bytes per char
- byteCount <<= 1;
-
- if (byteCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(charCount), Environment.GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"));
-
- return (int)byteCount;
- }
-
-
- public override int GetMaxCharCount(int byteCount)
- {
- if (byteCount < 0)
- throw new ArgumentOutOfRangeException(nameof(byteCount),
- Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
- Contract.EndContractBlock();
-
- // long because byteCount could be biggest int.
- // 1 char per 2 bytes. Round up in case 1 left over in decoder.
- // Round up using &1 in case byteCount is max size
- // Might also need an extra 1 if there's a left over high surrogate in the decoder.
- long charCount = (long)(byteCount >> 1) + (byteCount & 1) + 1;
-
- // Don't forget fallback (in case they have a bunch of lonely surrogates or something bizzare like that)
- if (DecoderFallback.MaxCharCount > 1)
- charCount *= DecoderFallback.MaxCharCount;
-
- if (charCount > 0x7fffffff)
- throw new ArgumentOutOfRangeException(nameof(byteCount), Environment.GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"));
-
- return (int)charCount;
- }
-
-
- public override bool Equals(Object value)
- {
- UnicodeEncoding that = value as UnicodeEncoding;
- if (that != null)
- {
- //
- // Big Endian Unicode has different code page (1201) than small Endian one (1200),
- // so we still have to check m_codePage here.
- //
- return (CodePage == that.CodePage) &&
- byteOrderMark == that.byteOrderMark &&
-// isThrowException == that.isThrowException && // Same as Encoder/Decoder being exception fallbacks
- bigEndian == that.bigEndian &&
- (EncoderFallback.Equals(that.EncoderFallback)) &&
- (DecoderFallback.Equals(that.DecoderFallback));
- }
- return (false);
- }
-
- public override int GetHashCode()
- {
- return CodePage + this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() +
- (byteOrderMark?4:0) + (bigEndian?8:0);
- }
-
- [Serializable]
- private class Decoder : System.Text.DecoderNLS, ISerializable
- {
- internal int lastByte = -1;
- internal char lastChar = '\0';
-
- public Decoder(UnicodeEncoding encoding) : base(encoding)
- {
- // base calls reset
- }
-
- // Constructor called by serialization, have to handle deserializing from Everett
- internal Decoder(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Get Common Info
- this.lastByte = (int)info.GetValue("lastByte", typeof(int));
-
- try
- {
- // Try the encoding, which is only serialized in Whidbey
- this.m_encoding = (Encoding)info.GetValue("m_encoding", typeof(Encoding));
- this.lastChar = (char)info.GetValue("lastChar", typeof(char));
- this.m_fallback = (DecoderFallback)info.GetValue("m_fallback", typeof(DecoderFallback));
- }
- catch (SerializationException)
- {
- // Everett didn't serialize the UnicodeEncoding, get the default one
- bool bigEndian = (bool)info.GetValue("bigEndian", typeof(bool));
- this.m_encoding = new UnicodeEncoding(bigEndian, false);
- }
- }
-
- // ISerializable implementation, get data for this object
- void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
- {
- // Any info?
- if (info==null) throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- // Save Whidbey data
- info.AddValue("m_encoding", this.m_encoding);
- info.AddValue("m_fallback", this.m_fallback);
- info.AddValue("lastChar", this.lastChar); // Unused by everett so it'll probably get lost
- info.AddValue("lastByte", this.lastByte);
-
- // Everett Only
- info.AddValue("bigEndian", ((UnicodeEncoding)(this.m_encoding)).bigEndian);
- }
-
- public override void Reset()
- {
- lastByte = -1;
- lastChar = '\0';
- if (m_fallbackBuffer != null)
- m_fallbackBuffer.Reset();
- }
-
- // Anything left in our decoder?
- internal override bool HasState
- {
- get
- {
- return (this.lastByte != -1 || this.lastChar != '\0');
- }
- }
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/ThreadAttributes.cs b/src/mscorlib/src/System/ThreadAttributes.cs
deleted file mode 100644
index 6248736107..0000000000
--- a/src/mscorlib/src/System/ThreadAttributes.cs
+++ /dev/null
@@ -1,28 +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: For Threads-related custom attributes.
-**
-=============================================================================*/
-
-namespace System
-{
- [AttributeUsage(AttributeTargets.Method)]
- public sealed class STAThreadAttribute : Attribute
- {
- public STAThreadAttribute()
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Method)]
- public sealed class MTAThreadAttribute : Attribute
- {
- public MTAThreadAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/ThreadStaticAttribute.cs b/src/mscorlib/src/System/ThreadStaticAttribute.cs
deleted file mode 100644
index 3755e65a7b..0000000000
--- a/src/mscorlib/src/System/ThreadStaticAttribute.cs
+++ /dev/null
@@ -1,28 +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: Custom attribute to indicate that the field should be treated
-** as a static relative to a thread.
-**
-**
-**
-===========================================================*/
-
-using System;
-
-namespace System
-{
- [Serializable]
- [AttributeUsage(AttributeTargets.Field, Inherited = false)]
- public class ThreadStaticAttribute : Attribute
- {
- public ThreadStaticAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Threading/AbandonedMutexException.cs b/src/mscorlib/src/System/Threading/AbandonedMutexException.cs
deleted file mode 100644
index 6b4977fbc5..0000000000
--- a/src/mscorlib/src/System/Threading/AbandonedMutexException.cs
+++ /dev/null
@@ -1,85 +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.
-
-//
-//
-// AbandonedMutexException
-// Thrown when a wait completes because one or more mutexes was abandoned.
-// AbandonedMutexs indicate serious error in user code or machine state.
-////////////////////////////////////////////////////////////////////////////////
-
-namespace System.Threading {
-
- using System;
- using System.Runtime.Serialization;
- using System.Threading;
- using System.Runtime.InteropServices;
-
- [Serializable]
- [ComVisibleAttribute(false)]
- public class AbandonedMutexException : SystemException {
-
- private int m_MutexIndex = -1;
- private Mutex m_Mutex = null;
-
- public AbandonedMutexException()
- : base(Environment.GetResourceString("Threading.AbandonedMutexException")) {
- SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- }
-
- public AbandonedMutexException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- }
-
- public AbandonedMutexException(String message, Exception inner )
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- }
-
- public AbandonedMutexException(int location, WaitHandle handle)
- : base(Environment.GetResourceString("Threading.AbandonedMutexException")) {
- SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- SetupException(location,handle);
- }
-
- public AbandonedMutexException(String message,int location, WaitHandle handle)
- : base(message) {
- SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- SetupException(location,handle);
- }
-
- public AbandonedMutexException(String message, Exception inner,int location, WaitHandle handle )
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_ABANDONEDMUTEX);
- SetupException(location,handle);
- }
-
- private void SetupException(int location, WaitHandle handle)
- {
- m_MutexIndex = location;
- if(handle != null)
- m_Mutex = handle as Mutex;
- }
-
- protected AbandonedMutexException(SerializationInfo info, StreamingContext context) : base(info, context) {
- }
-
- public Mutex Mutex
- {
- get {
- return m_Mutex;
- }
- }
-
- public int MutexIndex
- {
- get{
- return m_MutexIndex;
- }
- }
-
- }
-}
-
diff --git a/src/mscorlib/src/System/Threading/ApartmentState.cs b/src/mscorlib/src/System/Threading/ApartmentState.cs
deleted file mode 100644
index 1edf0af98a..0000000000
--- a/src/mscorlib/src/System/Threading/ApartmentState.cs
+++ /dev/null
@@ -1,27 +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: Enum to represent the different threading models
-**
-**
-=============================================================================*/
-
-namespace System.Threading {
-
- [Serializable]
- public enum ApartmentState
- {
- /*=========================================================================
- ** Constants for thread apartment states.
- =========================================================================*/
- STA = 0,
- MTA = 1,
- Unknown = 2
- }
-}
diff --git a/src/mscorlib/src/System/Threading/AsyncLocal.cs b/src/mscorlib/src/System/Threading/AsyncLocal.cs
deleted file mode 100644
index 8c4319bd2c..0000000000
--- a/src/mscorlib/src/System/Threading/AsyncLocal.cs
+++ /dev/null
@@ -1,487 +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.Collections.Generic;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Security;
-
-namespace System.Threading
-{
- //
- // AsyncLocal<T> represents "ambient" data that is local to a given asynchronous control flow, such as an
- // async method. For example, say you want to associate a culture with a given async flow:
- //
- // static AsyncLocal<Culture> s_currentCulture = new AsyncLocal<Culture>();
- //
- // static async Task SomeOperationAsync(Culture culture)
- // {
- // s_currentCulture.Value = culture;
- //
- // await FooAsync();
- // }
- //
- // static async Task FooAsync()
- // {
- // PrintStringWithCulture(s_currentCulture.Value);
- // }
- //
- // AsyncLocal<T> also provides optional notifications when the value associated with the current thread
- // changes, either because it was explicitly changed by setting the Value property, or implicitly changed
- // when the thread encountered an "await" or other context transition. For example, we might want our
- // current culture to be communicated to the OS as well:
- //
- // static AsyncLocal<Culture> s_currentCulture = new AsyncLocal<Culture>(
- // args =>
- // {
- // NativeMethods.SetThreadCulture(args.CurrentValue.LCID);
- // });
- //
- public sealed class AsyncLocal<T> : IAsyncLocal
- {
- private readonly Action<AsyncLocalValueChangedArgs<T>> m_valueChangedHandler;
-
- //
- // Constructs an AsyncLocal<T> that does not receive change notifications.
- //
- public AsyncLocal()
- {
- }
-
- //
- // Constructs an AsyncLocal<T> with a delegate that is called whenever the current value changes
- // on any thread.
- //
- public AsyncLocal(Action<AsyncLocalValueChangedArgs<T>> valueChangedHandler)
- {
- m_valueChangedHandler = valueChangedHandler;
- }
-
- public T Value
- {
- get
- {
- object obj = ExecutionContext.GetLocalValue(this);
- return (obj == null) ? default(T) : (T)obj;
- }
- set
- {
- ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null);
- }
- }
-
- void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged)
- {
- Debug.Assert(m_valueChangedHandler != null);
- T previousValue = previousValueObj == null ? default(T) : (T)previousValueObj;
- T currentValue = currentValueObj == null ? default(T) : (T)currentValueObj;
- m_valueChangedHandler(new AsyncLocalValueChangedArgs<T>(previousValue, currentValue, contextChanged));
- }
- }
-
- //
- // Interface to allow non-generic code in ExecutionContext to call into the generic AsyncLocal<T> type.
- //
- internal interface IAsyncLocal
- {
- void OnValueChanged(object previousValue, object currentValue, bool contextChanged);
- }
-
- public struct AsyncLocalValueChangedArgs<T>
- {
- public T PreviousValue { get; private set; }
- public T CurrentValue { get; private set; }
-
- //
- // If the value changed because we changed to a different ExecutionContext, this is true. If it changed
- // because someone set the Value property, this is false.
- //
- public bool ThreadContextChanged { get; private set; }
-
- internal AsyncLocalValueChangedArgs(T previousValue, T currentValue, bool contextChanged)
- : this()
- {
- PreviousValue = previousValue;
- CurrentValue = currentValue;
- ThreadContextChanged = contextChanged;
- }
- }
-
- //
- // Interface used to store an IAsyncLocal => object mapping in ExecutionContext.
- // Implementations are specialized based on the number of elements in the immutable
- // map in order to minimize memory consumption and look-up times.
- //
- interface IAsyncLocalValueMap
- {
- bool TryGetValue(IAsyncLocal key, out object value);
- IAsyncLocalValueMap Set(IAsyncLocal key, object value);
- }
-
- //
- // Utility functions for getting/creating instances of IAsyncLocalValueMap
- //
- internal static class AsyncLocalValueMap
- {
- public static IAsyncLocalValueMap Empty { get; } = new EmptyAsyncLocalValueMap();
-
- // Instance without any key/value pairs. Used as a singleton/
- private sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap
- {
- public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
- {
- // If the value isn't null, then create a new one-element map to store
- // the key/value pair. If it is null, then we're still empty.
- return value != null ?
- new OneElementAsyncLocalValueMap(key, value) :
- (IAsyncLocalValueMap)this;
- }
-
- public bool TryGetValue(IAsyncLocal key, out object value)
- {
- value = null;
- return false;
- }
- }
-
- // Instance with one key/value pair.
- private sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap
- {
- private readonly IAsyncLocal _key1;
- private readonly object _value1;
-
- public OneElementAsyncLocalValueMap(IAsyncLocal key, object value)
- {
- _key1 = key; _value1 = value;
- }
-
- public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
- {
- if (value != null)
- {
- // The value is non-null. If the key matches one already contained in this map,
- // then create a new one-element map with the updated value, otherwise create
- // a two-element map with the additional key/value.
- return ReferenceEquals(key, _key1) ?
- new OneElementAsyncLocalValueMap(key, value) :
- (IAsyncLocalValueMap)new TwoElementAsyncLocalValueMap(_key1, _value1, key, value);
- }
- else
- {
- // The value is null. If the key exists in this map, remove it by downgrading to an empty map.
- // Otherwise, there's nothing to add or remove, so just return this map.
- return ReferenceEquals(key, _key1) ?
- Empty :
- (IAsyncLocalValueMap)this;
- }
- }
-
- public bool TryGetValue(IAsyncLocal key, out object value)
- {
- if (ReferenceEquals(key, _key1))
- {
- value = _value1;
- return true;
- }
- else
- {
- value = null;
- return false;
- }
- }
- }
-
- // Instance with two key/value pairs.
- private sealed class TwoElementAsyncLocalValueMap : IAsyncLocalValueMap
- {
- private readonly IAsyncLocal _key1, _key2;
- private readonly object _value1, _value2;
-
- public TwoElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2)
- {
- _key1 = key1; _value1 = value1;
- _key2 = key2; _value2 = value2;
- }
-
- public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
- {
- if (value != null)
- {
- // The value is non-null. If the key matches one already contained in this map,
- // then create a new two-element map with the updated value, otherwise create
- // a three-element map with the additional key/value.
- return
- ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(key, value, _key2, _value2) :
- ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, key, value) :
- (IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
- }
- else
- {
- // The value is null. If the key exists in this map, remove it by downgrading to a one-element map
- // without the key. Otherwise, there's nothing to add or remove, so just return this map.
- return
- ReferenceEquals(key, _key1) ? new OneElementAsyncLocalValueMap(_key2, _value2) :
- ReferenceEquals(key, _key2) ? new OneElementAsyncLocalValueMap(_key1, _value1) :
- (IAsyncLocalValueMap)this;
- }
- }
-
- public bool TryGetValue(IAsyncLocal key, out object value)
- {
- if (ReferenceEquals(key, _key1))
- {
- value = _value1;
- return true;
- }
- else if (ReferenceEquals(key, _key2))
- {
- value = _value2;
- return true;
- }
- else
- {
- value = null;
- return false;
- }
- }
- }
-
- // Instance with three key/value pairs.
- private sealed class ThreeElementAsyncLocalValueMap : IAsyncLocalValueMap
- {
- private readonly IAsyncLocal _key1, _key2, _key3;
- private readonly object _value1, _value2, _value3;
-
- public ThreeElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2, IAsyncLocal key3, object value3)
- {
- _key1 = key1; _value1 = value1;
- _key2 = key2; _value2 = value2;
- _key3 = key3; _value3 = value3;
- }
-
- public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
- {
- if (value != null)
- {
- // The value is non-null. If the key matches one already contained in this map,
- // then create a new three-element map with the updated value.
- if (ReferenceEquals(key, _key1)) return new ThreeElementAsyncLocalValueMap(key, value, _key2, _value2, _key3, _value3);
- if (ReferenceEquals(key, _key2)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, key, value, _key3, _value3);
- if (ReferenceEquals(key, _key3)) return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value);
-
- // The key doesn't exist in this map, so upgrade to a multi map that contains
- // the additional key/value pair.
- var multi = new MultiElementAsyncLocalValueMap(4);
- multi.UnsafeStore(0, _key1, _value1);
- multi.UnsafeStore(1, _key2, _value2);
- multi.UnsafeStore(2, _key3, _value3);
- multi.UnsafeStore(3, key, value);
- return multi;
- }
- else
- {
- // The value is null. If the key exists in this map, remove it by downgrading to a two-element map
- // without the key. Otherwise, there's nothing to add or remove, so just return this map.
- return
- ReferenceEquals(key, _key1) ? new TwoElementAsyncLocalValueMap(_key2, _value2, _key3, _value3) :
- ReferenceEquals(key, _key2) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key3, _value3) :
- ReferenceEquals(key, _key3) ? new TwoElementAsyncLocalValueMap(_key1, _value1, _key2, _value2) :
- (IAsyncLocalValueMap)this;
- }
- }
-
- public bool TryGetValue(IAsyncLocal key, out object value)
- {
- if (ReferenceEquals(key, _key1))
- {
- value = _value1;
- return true;
- }
- else if (ReferenceEquals(key, _key2))
- {
- value = _value2;
- return true;
- }
- else if (ReferenceEquals(key, _key3))
- {
- value = _value3;
- return true;
- }
- else
- {
- value = null;
- return false;
- }
- }
- }
-
- // Instance with up to 16 key/value pairs.
- private sealed class MultiElementAsyncLocalValueMap : IAsyncLocalValueMap
- {
- internal const int MaxMultiElements = 16;
- private readonly KeyValuePair<IAsyncLocal, object>[] _keyValues;
-
- internal MultiElementAsyncLocalValueMap(int count)
- {
- Debug.Assert(count <= MaxMultiElements);
- _keyValues = new KeyValuePair<IAsyncLocal, object>[count];
- }
-
- internal void UnsafeStore(int index, IAsyncLocal key, object value)
- {
- Debug.Assert(index < _keyValues.Length);
- _keyValues[index] = new KeyValuePair<IAsyncLocal, object>(key, value);
- }
-
- public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
- {
- // Find the key in this map.
- for (int i = 0; i < _keyValues.Length; i++)
- {
- if (ReferenceEquals(key, _keyValues[i].Key))
- {
- // The key is in the map. If the value isn't null, then create a new map of the same
- // size that has all of the same pairs, with this new key/value pair overwriting the old.
- if (value != null)
- {
- var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length);
- Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
- multi._keyValues[i] = new KeyValuePair<IAsyncLocal, object>(key, value);
- return multi;
- }
- else if (_keyValues.Length == 4)
- {
- // The value is null, and we only have four elements, one of which we're removing,
- // so downgrade to a three-element map, without the matching element.
- return
- i == 0 ? new ThreeElementAsyncLocalValueMap(_keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
- i == 1 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value) :
- i == 2 ? new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[3].Key, _keyValues[3].Value) :
- (IAsyncLocalValueMap)new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value);
- }
- else
- {
- // The value is null, and we have enough elements remaining to warrant a multi map.
- // Create a new one and copy all of the elements from this one, except the one to be removed.
- var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length - 1);
- if (i != 0) Array.Copy(_keyValues, 0, multi._keyValues, 0, i);
- if (i != _keyValues.Length - 1) Array.Copy(_keyValues, i + 1, multi._keyValues, i, _keyValues.Length - i - 1);
- return multi;
- }
- }
- }
-
- // The key does not already exist in this map.
-
- // If the value is null, then we can simply return this same map, as there's nothing to add or remove.
- if (value == null)
- {
- return this;
- }
-
- // We need to create a new map that has the additional key/value pair.
- // If with the addition we can still fit in a multi map, create one.
- if (_keyValues.Length < MaxMultiElements)
- {
- var multi = new MultiElementAsyncLocalValueMap(_keyValues.Length + 1);
- Array.Copy(_keyValues, 0, multi._keyValues, 0, _keyValues.Length);
- multi._keyValues[_keyValues.Length] = new KeyValuePair<IAsyncLocal, object>(key, value);
- return multi;
- }
-
- // Otherwise, upgrade to a many map.
- var many = new ManyElementAsyncLocalValueMap(MaxMultiElements + 1);
- foreach (KeyValuePair<IAsyncLocal, object> pair in _keyValues)
- {
- many[pair.Key] = pair.Value;
- }
- many[key] = value;
- return many;
- }
-
- public bool TryGetValue(IAsyncLocal key, out object value)
- {
- foreach (KeyValuePair<IAsyncLocal, object> pair in _keyValues)
- {
- if (ReferenceEquals(key, pair.Key))
- {
- value = pair.Value;
- return true;
- }
- }
- value = null;
- return false;
- }
- }
-
- // Instance with any number of key/value pairs.
- private sealed class ManyElementAsyncLocalValueMap : Dictionary<IAsyncLocal, object>, IAsyncLocalValueMap
- {
- public ManyElementAsyncLocalValueMap(int capacity) : base(capacity) { }
-
- public IAsyncLocalValueMap Set(IAsyncLocal key, object value)
- {
- int count = Count;
- bool containsKey = ContainsKey(key);
-
- // If the value being set exists, create a new many map, copy all of the elements from this one,
- // and then store the new key/value pair into it. This is the most common case.
- if (value != null)
- {
- var map = new ManyElementAsyncLocalValueMap(count + (containsKey ? 0 : 1));
- foreach (KeyValuePair<IAsyncLocal, object> pair in this)
- {
- map[pair.Key] = pair.Value;
- }
- map[key] = value;
- return map;
- }
-
- // Otherwise, the value is null, which means null is being stored into an AsyncLocal.Value.
- // Since there's no observable difference at the API level between storing null and the key
- // not existing at all, we can downgrade to a smaller map rather than storing null.
-
- // If the key is contained in this map, we're going to create a new map that's one pair smaller.
- if (containsKey)
- {
- // If the new count would be within range of a multi map instead of a many map,
- // downgrade to the many map, which uses less memory and is faster to access.
- // Otherwise, just create a new many map that's missing this key.
- if (count == MultiElementAsyncLocalValueMap.MaxMultiElements + 1)
- {
- var multi = new MultiElementAsyncLocalValueMap(MultiElementAsyncLocalValueMap.MaxMultiElements);
- int index = 0;
- foreach (KeyValuePair<IAsyncLocal, object> pair in this)
- {
- if (!ReferenceEquals(key, pair.Key))
- {
- multi.UnsafeStore(index++, pair.Key, pair.Value);
- }
- }
- Debug.Assert(index == MultiElementAsyncLocalValueMap.MaxMultiElements);
- return multi;
- }
- else
- {
- var map = new ManyElementAsyncLocalValueMap(count - 1);
- foreach (KeyValuePair<IAsyncLocal, object> pair in this)
- {
- if (!ReferenceEquals(key, pair.Key))
- {
- map[pair.Key] = pair.Value;
- }
- }
- Debug.Assert(map.Count == count - 1);
- return map;
- }
- }
-
- // We were storing null, but the key wasn't in the map, so there's nothing to change.
- // Just return this instance.
- return this;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Threading/AutoResetEvent.cs b/src/mscorlib/src/System/Threading/AutoResetEvent.cs
deleted file mode 100644
index fc6b2301ca..0000000000
--- a/src/mscorlib/src/System/Threading/AutoResetEvent.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: An example of a WaitHandle class
-**
-**
-=============================================================================*/
-namespace System.Threading {
-
- using System;
- using System.Runtime.InteropServices;
-
- public sealed class AutoResetEvent : EventWaitHandle
- {
- public AutoResetEvent(bool initialState) : base(initialState,EventResetMode.AutoReset){ }
- }
-}
-
diff --git a/src/mscorlib/src/System/Threading/CancellationToken.cs b/src/mscorlib/src/System/Threading/CancellationToken.cs
index b68ba4c046..8bddfc90dd 100644
--- a/src/mscorlib/src/System/Threading/CancellationToken.cs
+++ b/src/mscorlib/src/System/Threading/CancellationToken.cs
@@ -78,14 +78,14 @@ namespace System.Threading
/// particularly in situations where related objects are being canceled concurrently.
/// </para>
/// </remarks>
- public bool IsCancellationRequested
+ public bool IsCancellationRequested
{
get
{
return m_source != null && m_source.IsCancellationRequested;
}
}
-
+
/// <summary>
/// Gets whether this token is capable of being in the canceled state.
/// </summary>
@@ -153,12 +153,12 @@ namespace System.Threading
public CancellationToken(bool canceled) :
this()
{
- if(canceled)
+ if (canceled)
m_source = CancellationTokenSource.InternalGetStaticSource(canceled);
}
/* Methods */
-
+
private readonly static Action<Object> s_ActionToActionObjShunt = new Action<Object>(ActionToActionObjShunt);
private static void ActionToActionObjShunt(object obj)
@@ -190,7 +190,7 @@ namespace System.Threading
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
-
+
return Register(
s_ActionToActionObjShunt,
callback,
@@ -225,7 +225,7 @@ namespace System.Threading
{
if (callback == null)
throw new ArgumentNullException(nameof(callback));
-
+
return Register(
s_ActionToActionObjShunt,
callback,
@@ -301,7 +301,7 @@ namespace System.Threading
true // useExecutionContext=true
);
}
-
+
// helper for internal registration needs that don't require an EC capture (e.g. creating linked token sources, or registering unstarted TPL tasks)
// has a handy signature, and skips capturing execution context.
internal CancellationTokenRegistration InternalRegisterWithoutEC(Action<object> callback, Object state)
@@ -366,14 +366,14 @@ namespace System.Threading
{
return other.m_source == CancellationTokenSource.InternalGetStaticSource(false);
}
-
+
if (other.m_source == null)
{
return m_source == CancellationTokenSource.InternalGetStaticSource(false);
}
// general case, we check if the sources are identical
-
+
return m_source == other.m_source;
}
@@ -392,7 +392,7 @@ namespace System.Threading
{
if (other is CancellationToken)
{
- return Equals((CancellationToken) other);
+ return Equals((CancellationToken)other);
}
return false;
@@ -410,9 +410,9 @@ namespace System.Threading
return CancellationTokenSource.InternalGetStaticSource(false).GetHashCode();
}
- return m_source.GetHashCode();
+ return m_source.GetHashCode();
}
-
+
/// <summary>
/// Determines whether two <see cref="T:System.Threading.CancellationToken">CancellationToken</see> instances are equal.
/// </summary>
@@ -455,7 +455,7 @@ namespace System.Threading
/// cref="T:System.Threading.CancellationTokenSource">CancellationTokenSource</see> has been disposed.</exception>
public void ThrowIfCancellationRequested()
{
- if (IsCancellationRequested)
+ if (IsCancellationRequested)
ThrowOperationCanceledException();
}
@@ -469,17 +469,17 @@ namespace System.Threading
// Throws an OCE; separated out to enable better inlining of ThrowIfCancellationRequested
private void ThrowOperationCanceledException()
{
- throw new OperationCanceledException(Environment.GetResourceString("OperationCanceled"), this);
+ throw new OperationCanceledException(SR.OperationCanceled, this);
}
private static void ThrowObjectDisposedException()
{
- throw new ObjectDisposedException(null, Environment.GetResourceString("CancellationToken_SourceDisposed"));
+ throw new ObjectDisposedException(null, SR.CancellationToken_SourceDisposed);
}
// -----------------------------------
// Private helpers
-
+
private void InitializeDefaultSource()
{
// Lazy is slower, and although multiple threads may try and set m_source repeatedly, the race condition is benign.
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
index 89e98fa3c8..be760fab3f 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
@@ -62,7 +62,7 @@ namespace System.Threading
// Remove the entry from the array.
// This call includes a full memory fence which prevents potential reorderings of the reads below
bool deregisterOccurred = TryDeregister();
-
+
// We guarantee that we will not return if the callback is being executed (assuming we are not currently called by the callback itself)
// We achieve this by the following rules:
// 1. if we are called in the context of an executing callback, no need to wait (determined by tracking callback-executor threadID)
@@ -124,7 +124,7 @@ namespace System.Threading
/// </returns>
public override bool Equals(object obj)
{
- return ((obj is CancellationTokenRegistration) && Equals((CancellationTokenRegistration) obj));
+ return ((obj is CancellationTokenRegistration) && Equals((CancellationTokenRegistration)obj));
}
/// <summary>
@@ -152,7 +152,7 @@ namespace System.Threading
{
if (m_registrationInfo.Source != null)
return m_registrationInfo.Source.GetHashCode() ^ m_registrationInfo.Index.GetHashCode();
-
+
return m_registrationInfo.Index.GetHashCode();
}
}
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
index 1e70d6f30f..2707292ed2 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenSource.cs
@@ -45,18 +45,18 @@ namespace System.Threading
// the actual callback lists are only created on demand.
// Storing a registered callback costs around >60bytes, hence some overhead for the lists array is OK
// At most 24 lists seems reasonable, and caps the cost of the listsArray to 96bytes(32-bit,24-way) or 192bytes(64-bit,24-way).
- private static readonly int s_nLists = (PlatformHelper.ProcessorCount > 24) ? 24 : PlatformHelper.ProcessorCount;
+ private static readonly int s_nLists = (PlatformHelper.ProcessorCount > 24) ? 24 : PlatformHelper.ProcessorCount;
private volatile ManualResetEvent m_kernelEvent; //lazily initialized if required.
private volatile SparselyPopulatedArray<CancellationCallbackInfo>[] m_registeredCallbacksLists;
-
+
// legal values for m_state
private const int CANNOT_BE_CANCELED = 0;
private const int NOT_CANCELED = 1;
private const int NOTIFYING = 2;
private const int NOTIFYINGCOMPLETE = 3;
-
+
//m_state uses the pattern "volatile int32 reads, with cmpxch writes" which is safe for updates and cannot suffer torn reads.
private volatile int m_state;
@@ -68,13 +68,13 @@ namespace System.Threading
private volatile int m_threadIDExecutingCallbacks = -1;
private bool m_disposed;
-
+
// we track the running callback to assist ctr.Dispose() to wait for the target callback to complete.
private volatile CancellationCallbackInfo m_executingCallback;
// provided for CancelAfter and timer-related constructors
private volatile Timer m_timer;
-
+
// ----------------------
// ** public properties
@@ -168,11 +168,11 @@ namespace System.Threading
// fast path if already allocated.
if (m_kernelEvent != null)
return m_kernelEvent;
-
+
// lazy-init the mre.
ManualResetEvent mre = new ManualResetEvent(false);
if (Interlocked.CompareExchange(ref m_kernelEvent, mre, null) != null)
- {
+ {
((IDisposable)mre).Dispose();
}
@@ -211,9 +211,9 @@ namespace System.Threading
return 0;
int count = 0;
- foreach(SparselyPopulatedArray<CancellationCallbackInfo> sparseArray in callbackLists)
+ foreach (SparselyPopulatedArray<CancellationCallbackInfo> sparseArray in callbackLists)
{
- if(sparseArray != null)
+ if (sparseArray != null)
{
SparselyPopulatedArrayFragment<CancellationCallbackInfo> currCallbacks = sparseArray.Head;
while (currCallbacks != null)
@@ -379,7 +379,7 @@ namespace System.Threading
public void Cancel(bool throwOnFirstException)
{
ThrowIfDisposed();
- NotifyCancellation(throwOnFirstException);
+ NotifyCancellation(throwOnFirstException);
}
/// <summary>
@@ -476,7 +476,7 @@ namespace System.Threading
}
}
-
+
// It is possible that m_timer has already been disposed, so we must do
// the following in a try/catch block.
try
@@ -490,7 +490,6 @@ namespace System.Threading
// would not be a good way to deal with the observe/dispose
// race condition.
}
-
}
private static readonly TimerCallback s_timerCallback = new TimerCallback(TimerCallbackLogic);
@@ -601,7 +600,7 @@ namespace System.Threading
// separation enables inlining of ThrowIfDisposed
private static void ThrowObjectDisposedException()
{
- throw new ObjectDisposedException(null, Environment.GetResourceString("CancellationTokenSource_Disposed"));
+ throw new ObjectDisposedException(null, SR.CancellationTokenSource_Disposed);
}
/// <summary>
@@ -716,7 +715,7 @@ namespace System.Threading
// Record the threadID being used for running the callbacks.
ThreadIDExecutingCallbacks = Thread.CurrentThread.ManagedThreadId;
-
+
// Set the event if it's been lazily initialized and hasn't yet been disposed of. Dispose may
// be running concurrently, in which case either it'll have set m_kernelEvent back to null and
// we won't see it here, or it'll see that we've transitioned to NOTIFYING and will skip disposing it,
@@ -755,7 +754,7 @@ namespace System.Threading
Interlocked.Exchange(ref m_state, NOTIFYINGCOMPLETE);
return;
}
-
+
try
{
for (int index = 0; index < callbackLists.Length; index++)
@@ -799,13 +798,13 @@ namespace System.Threading
CancellationCallbackCoreWork(args);
}
}
- catch(Exception ex)
+ catch (Exception ex)
{
if (throwOnFirstException)
throw;
-
+
// Otherwise, log it and proceed.
- if(exceptionList == null)
+ if (exceptionList == null)
exceptionList = new List<Exception>();
exceptionList.Add(ex);
}
@@ -821,7 +820,7 @@ namespace System.Threading
{
m_state = NOTIFYINGCOMPLETE;
m_executingCallback = null;
- Thread.MemoryBarrier(); // for safety, prevent reorderings crossing this point and seeing inconsistent state.
+ Interlocked.MemoryBarrier(); // for safety, prevent reorderings crossing this point and seeing inconsistent state.
}
if (exceptionList != null)
@@ -892,7 +891,7 @@ namespace System.Threading
switch (tokens.Length)
{
case 0:
- throw new ArgumentException(Environment.GetResourceString("CancellationToken_CreateLinkedToken_TokensIsEmpty"));
+ throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty);
case 1:
return CreateLinkedTokenSource(tokens[0]);
case 2:
@@ -1004,7 +1003,7 @@ namespace System.Threading
{
internal SparselyPopulatedArrayFragment<CancellationCallbackInfo> m_currArrayFragment;
internal int m_currArrayIndex;
-
+
public CancellationCallbackCoreWorkArguments(SparselyPopulatedArrayFragment<CancellationCallbackInfo> currArrayFragment, int currArrayIndex)
{
m_currArrayFragment = currArrayFragment;
@@ -1040,7 +1039,6 @@ namespace System.Threading
{
TargetSyncContext = targetSyncContext;
}
-
}
internal CancellationCallbackInfo(
@@ -1066,7 +1064,7 @@ namespace System.Threading
// Lazily initialize the callback delegate; benign race condition
var callback = s_executionContextCallback;
if (callback == null) s_executionContextCallback = callback = new ContextCallback(ExecutionContextCallback);
-
+
ExecutionContext.Run(
TargetExecutionContext,
callback,
@@ -1176,7 +1174,7 @@ namespace System.Threading
// If the slot is null, try to CAS our element into it.
int tryIndex = (start + i) % c;
Debug.Assert(tryIndex >= 0 && tryIndex < curr.m_elements.Length, "tryIndex is outside of bounds");
-
+
if (curr.m_elements[tryIndex] == null && Interlocked.CompareExchange(ref curr.m_elements[tryIndex], element, null) == null)
{
// We adjust the free count by --. Note: if this drops to 0, we will skip
@@ -1282,7 +1280,7 @@ namespace System.Threading
internal T SafeAtomicRemove(int index, T expectedElement)
{
T prevailingValue = Interlocked.CompareExchange(ref m_elements[index], null, expectedElement);
- if (prevailingValue != null)
+ if (prevailingValue != null)
++m_freeCount;
return prevailingValue;
}
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
new file mode 100644
index 0000000000..d0cc5afbae
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
@@ -0,0 +1,319 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace System.Threading
+{
+ //
+ // Implementation of ThreadPoolBoundHandle that sits on top of the CLR's ThreadPool and Overlapped infrastructure
+ //
+
+ /// <summary>
+ /// Represents an I/O handle that is bound to the system thread pool and enables low-level
+ /// components to receive notifications for asynchronous I/O operations.
+ /// </summary>
+ public sealed partial class ThreadPoolBoundHandle : IDisposable
+ {
+ private readonly SafeHandle _handle;
+ private bool _isDisposed;
+
+ private ThreadPoolBoundHandle(SafeHandle handle)
+ {
+ _handle = handle;
+ }
+
+ /// <summary>
+ /// Gets the bound operating system handle.
+ /// </summary>
+ /// <value>
+ /// A <see cref="SafeHandle"/> object that holds the bound operating system handle.
+ /// </value>
+ public SafeHandle Handle
+ {
+ get { return _handle; }
+ }
+
+ /// <summary>
+ /// Returns a <see cref="ThreadPoolBoundHandle"/> for the specific handle,
+ /// which is bound to the system thread pool.
+ /// </summary>
+ /// <param name="handle">
+ /// A <see cref="SafeHandle"/> object that holds the operating system handle. The
+ /// handle must have been opened for overlapped I/O on the unmanaged side.
+ /// </param>
+ /// <returns>
+ /// <see cref="ThreadPoolBoundHandle"/> for <paramref name="handle"/>, which
+ /// is bound to the system thread pool.
+ /// </returns>
+ /// <exception cref="ArgumentNullException">
+ /// <paramref name="handle"/> is <see langword="null"/>.
+ /// </exception>
+ /// <exception cref="ArgumentException">
+ /// <paramref name="handle"/> has been disposed.
+ /// <para>
+ /// -or-
+ /// </para>
+ /// <paramref name="handle"/> does not refer to a valid I/O handle.
+ /// <para>
+ /// -or-
+ /// </para>
+ /// <paramref name="handle"/> refers to a handle that has not been opened
+ /// for overlapped I/O.
+ /// <para>
+ /// -or-
+ /// </para>
+ /// <paramref name="handle"/> refers to a handle that has already been bound.
+ /// </exception>
+ /// <remarks>
+ /// This method should be called once per handle.
+ /// <para>
+ /// -or-
+ /// </para>
+ /// <see cref="ThreadPoolBoundHandle"/> does not take ownership of <paramref name="handle"/>,
+ /// it remains the responsibility of the caller to call <see cref="SafeHandle.Dispose"/>.
+ /// </remarks>
+ public static ThreadPoolBoundHandle BindHandle(SafeHandle handle)
+ {
+ if (handle == null)
+ throw new ArgumentNullException(nameof(handle));
+
+ if (handle.IsClosed || handle.IsInvalid)
+ throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
+
+ try
+ {
+ // ThreadPool.BindHandle will always return true, otherwise, it throws. See the underlying FCall
+ // implementation in ThreadPoolNative::CorBindIoCompletionCallback to see the implementation.
+ bool succeeded = ThreadPool.BindHandle(handle);
+ Debug.Assert(succeeded);
+ }
+ catch (Exception ex)
+ { // BindHandle throws ApplicationException on full CLR and Exception on CoreCLR.
+ // 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
+ throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
+
+ if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle
+ throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle));
+
+ throw;
+ }
+
+ return new ThreadPoolBoundHandle(handle);
+ }
+
+ /// <summary>
+ /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, specifying
+ /// a delegate that is invoked when the asynchronous I/O operation is complete, a user-provided
+ /// object providing context, and managed objects that serve as buffers.
+ /// </summary>
+ /// <param name="callback">
+ /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
+ /// invoked when the asynchronous I/O operation completes.
+ /// </param>
+ /// <param name="state">
+ /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/> from other
+ /// <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>.
+ /// </param>
+ /// <param name="pinData">
+ /// An object or array of objects representing the input or output buffer for the operation. Each
+ /// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>.
+ /// </param>
+ /// <returns>
+ /// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure.
+ /// </returns>
+ /// <remarks>
+ /// <para>
+ /// The unmanaged pointer returned by this method can be passed to the operating system in
+ /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
+ /// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called.
+ /// </para>
+ /// <para>
+ /// The buffer or buffers specified in <paramref name="pinData"/> must be the same as those passed
+ /// to the unmanaged operating system function that performs the asynchronous I/O.
+ /// </para>
+ /// <note>
+ /// The buffers specified in <paramref name="pinData"/> are pinned for the duration of
+ /// the I/O operation.
+ /// </note>
+ /// </remarks>
+ /// <exception cref="ArgumentNullException">
+ /// <paramref name="callback"/> is <see langword="null"/>.
+ /// </exception>
+ /// <exception cref="ObjectDisposedException">
+ /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed.
+ /// </exception>
+ [CLSCompliant(false)]
+ public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object state, object pinData)
+ {
+ if (callback == null)
+ throw new ArgumentNullException(nameof(callback));
+
+ EnsureNotDisposed();
+
+ ThreadPoolBoundHandleOverlapped overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, preAllocated: null);
+ overlapped._boundHandle = this;
+ return overlapped._nativeOverlapped;
+ }
+
+ /// <summary>
+ /// Returns an unmanaged pointer to a <see cref="NativeOverlapped"/> structure, using the callback,
+ /// state, and buffers associated with the specified <see cref="PreAllocatedOverlapped"/> object.
+ /// </summary>
+ /// <param name="preAllocated">
+ /// A <see cref="PreAllocatedOverlapped"/> object from which to create the NativeOverlapped pointer.
+ /// </param>
+ /// <returns>
+ /// An unmanaged pointer to a <see cref="NativeOverlapped"/> structure.
+ /// </returns>
+ /// <remarks>
+ /// <para>
+ /// The unmanaged pointer returned by this method can be passed to the operating system in
+ /// overlapped I/O operations. The <see cref="NativeOverlapped"/> structure is fixed in
+ /// physical memory until <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> is called.
+ /// </para>
+ /// </remarks>
+ /// <exception cref="ArgumentNullException">
+ /// <paramref name="preAllocated"/> is <see langword="null"/>.
+ /// </exception>
+ /// <exception cref="ArgumentException">
+ /// <paramref name="preAllocated"/> is currently in use for another I/O operation.
+ /// </exception>
+ /// <exception cref="ObjectDisposedException">
+ /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed, or
+ /// this method was called after <paramref name="preAllocated"/> was disposed.
+ /// </exception>
+ /// <seealso cref="PreAllocatedOverlapped"/>
+ [CLSCompliant(false)]
+ public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated)
+ {
+ if (preAllocated == null)
+ throw new ArgumentNullException(nameof(preAllocated));
+
+ EnsureNotDisposed();
+
+ preAllocated.AddRef();
+ try
+ {
+ ThreadPoolBoundHandleOverlapped overlapped = preAllocated._overlapped;
+
+ if (overlapped._boundHandle != null)
+ throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, nameof(preAllocated));
+
+ overlapped._boundHandle = this;
+
+ return overlapped._nativeOverlapped;
+ }
+ catch
+ {
+ preAllocated.Release();
+ throw;
+ }
+ }
+
+ /// <summary>
+ /// Frees the unmanaged memory associated with a <see cref="NativeOverlapped"/> structure
+ /// allocated by the <see cref="AllocateNativeOverlapped"/> method.
+ /// </summary>
+ /// <param name="overlapped">
+ /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure to be freed.
+ /// </param>
+ /// <remarks>
+ /// <note type="caution">
+ /// You must call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method exactly once
+ /// on every <see cref="NativeOverlapped"/> unmanaged pointer allocated using the
+ /// <see cref="AllocateNativeOverlapped"/> method.
+ /// If you do not call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method, you will
+ /// leak memory. If you call the <see cref="FreeNativeOverlapped(NativeOverlapped*)"/> method more
+ /// than once on the same <see cref="NativeOverlapped"/> unmanaged pointer, memory will be corrupted.
+ /// </note>
+ /// </remarks>
+ /// <exception cref="ArgumentNullException">
+ /// <paramref name="overlapped"/> is <see langword="null"/>.
+ /// </exception>
+ /// <exception cref="ObjectDisposedException">
+ /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed.
+ /// </exception>
+ [CLSCompliant(false)]
+ public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped)
+ {
+ if (overlapped == null)
+ throw new ArgumentNullException(nameof(overlapped));
+
+ // Note: we explicitly allow FreeNativeOverlapped calls after the ThreadPoolBoundHandle has been Disposed.
+
+ ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped, this);
+
+ if (wrapper._boundHandle != this)
+ throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, nameof(overlapped));
+
+ if (wrapper._preAllocated != null)
+ wrapper._preAllocated.Release();
+ else
+ Overlapped.Free(overlapped);
+ }
+
+ /// <summary>
+ /// Returns the user-provided object specified when the <see cref="NativeOverlapped"/> instance was
+ /// allocated using the <see cref="AllocateNativeOverlapped(IOCompletionCallback, object, byte[])"/>.
+ /// </summary>
+ /// <param name="overlapped">
+ /// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the
+ /// asscociated user-provided object.
+ /// </param>
+ /// <returns>
+ /// A user-provided object that distinguishes this <see cref="NativeOverlapped"/>
+ /// from other <see cref="NativeOverlapped"/> instances, otherwise, <see langword="null"/> if one was
+ /// not specified when the instance was allocated using <see cref="AllocateNativeOverlapped"/>.
+ /// </returns>
+ /// <exception cref="ArgumentNullException">
+ /// <paramref name="overlapped"/> is <see langword="null"/>.
+ /// </exception>
+ [CLSCompliant(false)]
+ public unsafe static object GetNativeOverlappedState(NativeOverlapped* overlapped)
+ {
+ if (overlapped == null)
+ throw new ArgumentNullException(nameof(overlapped));
+
+ ThreadPoolBoundHandleOverlapped wrapper = GetOverlappedWrapper(overlapped, null);
+ Debug.Assert(wrapper._boundHandle != null);
+ return wrapper._userState;
+ }
+
+ private static unsafe ThreadPoolBoundHandleOverlapped GetOverlappedWrapper(NativeOverlapped* overlapped, ThreadPoolBoundHandle expectedBoundHandle)
+ {
+ ThreadPoolBoundHandleOverlapped wrapper;
+ try
+ {
+ wrapper = (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(overlapped);
+ }
+ catch (NullReferenceException ex)
+ {
+ throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, nameof(overlapped), ex);
+ }
+
+ return wrapper;
+ }
+
+ public void Dispose()
+ {
+ // .NET Native's version of ThreadPoolBoundHandle that wraps the Win32 ThreadPool holds onto
+ // native resources so it needs to be disposable. To match the contract, we are also disposable.
+ // We also implement a disposable state to mimic behavior between this implementation and
+ // .NET Native's version (code written against us, will also work against .NET Native's version).
+ _isDisposed = true;
+ }
+
+
+ private void EnsureNotDisposed()
+ {
+ if (_isDisposed)
+ throw new ObjectDisposedException(GetType().ToString());
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandleOverlapped.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandleOverlapped.cs
new file mode 100644
index 0000000000..1aea2a294b
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandleOverlapped.cs
@@ -0,0 +1,52 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Threading
+{
+ /// <summary>
+ /// Overlapped subclass adding data needed by ThreadPoolBoundHandle.
+ /// </summary>
+ internal sealed class ThreadPoolBoundHandleOverlapped : Overlapped
+ {
+ private static readonly unsafe IOCompletionCallback s_completionCallback = CompletionCallback;
+
+ private readonly IOCompletionCallback _userCallback;
+ internal readonly object _userState;
+ internal PreAllocatedOverlapped _preAllocated;
+ internal unsafe NativeOverlapped* _nativeOverlapped;
+ internal ThreadPoolBoundHandle _boundHandle;
+ internal bool _completed;
+
+ public unsafe ThreadPoolBoundHandleOverlapped(IOCompletionCallback callback, object state, object pinData, PreAllocatedOverlapped preAllocated)
+ {
+ _userCallback = callback;
+ _userState = state;
+ _preAllocated = preAllocated;
+
+ _nativeOverlapped = Pack(s_completionCallback, pinData);
+ _nativeOverlapped->OffsetLow = 0; // CLR reuses NativeOverlapped instances and does not reset these
+ _nativeOverlapped->OffsetHigh = 0;
+ }
+
+ private unsafe static void CompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
+ {
+ ThreadPoolBoundHandleOverlapped overlapped = (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(nativeOverlapped);
+
+ //
+ // The Win32 thread pool implementation of ThreadPoolBoundHandle does not permit reuse of NativeOverlapped
+ // pointers without freeing them and allocating new a new one. We need to ensure that code using the CLR
+ // ThreadPool implementation follows those rules.
+ //
+ if (overlapped._completed)
+ throw new InvalidOperationException(SR.InvalidOperation_NativeOverlappedReused);
+
+ overlapped._completed = true;
+
+ if (overlapped._boundHandle == null)
+ throw new InvalidOperationException(SR.Argument_NativeOverlappedAlreadyFree);
+
+ overlapped._userCallback(errorCode, numBytes, nativeOverlapped);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs
new file mode 100644
index 0000000000..a42e0c7983
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolPreAllocatedOverlapped.cs
@@ -0,0 +1,105 @@
+// 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.Threading
+{
+ /// <summary>
+ /// Represents pre-allocated state for native overlapped I/O operations.
+ /// </summary>
+ /// <seealso cref="ThreadPoolBoundHandle.AllocateNativeOverlapped(PreAllocatedOverlapped)"/>
+ public sealed class PreAllocatedOverlapped : IDisposable, IDeferredDisposable
+ {
+ internal readonly ThreadPoolBoundHandleOverlapped _overlapped;
+ private DeferredDisposableLifetime<PreAllocatedOverlapped> _lifetime;
+
+ /// <summary>
+ /// Initializes a new instance of the <see cref="PreAllocatedOverlapped"/> class, specifying
+ /// a delegate that is invoked when each asynchronous I/O operation is complete, a user-provided
+ /// object providing context, and managed objects that serve as buffers.
+ /// </summary>
+ /// <param name="callback">
+ /// An <see cref="IOCompletionCallback"/> delegate that represents the callback method
+ /// invoked when each asynchronous I/O operation completes.
+ /// </param>
+ /// <param name="state">
+ /// A user-provided object that distinguishes <see cref="NativeOverlapped"/> instance produced from this
+ /// object from other <see cref="NativeOverlapped"/> instances. Can be <see langword="null"/>.
+ /// </param>
+ /// <param name="pinData">
+ /// An object or array of objects representing the input or output buffer for the operations. Each
+ /// object represents a buffer, for example an array of bytes. Can be <see langword="null"/>.
+ /// </param>
+ /// <remarks>
+ /// The new <see cref="PreAllocatedOverlapped"/> instance can be passed to
+ /// <see cref="ThreadPoolBoundHandle.AllocateNativeOverlapped(PreAllocatedOverlapped)"/>, to produce
+ /// a <see cref="NativeOverlapped"/> instance that can be passed to the operating system in overlapped
+ /// I/O operations. A single <see cref="PreAllocatedOverlapped"/> instance can only be used for
+ /// a single native I/O operation at a time. However, the state stored in the <see cref="PreAllocatedOverlapped"/>
+ /// instance can be reused for subsequent native operations.
+ /// <note>
+ /// The buffers specified in <paramref name="pinData"/> are pinned until <see cref="Dispose"/> is called.
+ /// </note>
+ /// </remarks>
+ /// <exception cref="ArgumentNullException">
+ /// <paramref name="callback"/> is <see langword="null"/>.
+ /// </exception>
+ /// <exception cref="ObjectDisposedException">
+ /// This method was called after the <see cref="ThreadPoolBoundHandle"/> was disposed.
+ /// </exception>
+ [CLSCompliant(false)]
+ public unsafe PreAllocatedOverlapped(IOCompletionCallback callback, object state, object pinData)
+ {
+ if (callback == null)
+ throw new ArgumentNullException(nameof(callback));
+
+ _overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, this);
+ }
+
+ internal bool AddRef()
+ {
+ return _lifetime.AddRef(this);
+ }
+
+ internal void Release()
+ {
+ _lifetime.Release(this);
+ }
+
+ /// <summary>
+ /// Frees the resources associated with this <see cref="PreAllocatedOverlapped"/> instance.
+ /// </summary>
+ public unsafe void Dispose()
+ {
+ _lifetime.Dispose(this);
+ GC.SuppressFinalize(this);
+ }
+
+ ~PreAllocatedOverlapped()
+ {
+ //
+ // During shutdown, don't automatically clean up, because this instance may still be
+ // reachable/usable by other code.
+ //
+ if (!Environment.HasShutdownStarted)
+ Dispose();
+ }
+
+ unsafe void IDeferredDisposable.OnFinalRelease(bool disposed)
+ {
+ if (_overlapped != null)
+ {
+ if (disposed)
+ {
+ Overlapped.Free(_overlapped._nativeOverlapped);
+ }
+ else
+ {
+ _overlapped._boundHandle = null;
+ _overlapped._completed = false;
+ *_overlapped._nativeOverlapped = default(NativeOverlapped);
+ }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/CountdownEvent.cs b/src/mscorlib/src/System/Threading/CountdownEvent.cs
deleted file mode 100644
index af055e347e..0000000000
--- a/src/mscorlib/src/System/Threading/CountdownEvent.cs
+++ /dev/null
@@ -1,589 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// A simple coordination data structure that we use for fork/join style parallelism.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Runtime.InteropServices;
-using System.Threading;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-
-namespace System.Threading
-{
-
- /// <summary>
- /// Represents a synchronization primitive that is signaled when its count reaches zero.
- /// </summary>
- /// <remarks>
- /// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used
- /// concurrently from multiple threads, with the exception of Dispose, which
- /// must only be used when all other operations on the <see cref="CountdownEvent"/> have
- /// completed, and Reset, which should only be used when no other threads are
- /// accessing the event.
- /// </remarks>
- [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")]
- public class CountdownEvent : IDisposable
- {
- // CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a
- // latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can
- // wait on the latch at any point; when the latch count reaches 0, all threads are woken and
- // subsequent waiters return without waiting. The implementation internally lazily creates a true
- // Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a
- // wait.
-
- private int m_initialCount; // The original # of signals the latch was instantiated with.
- private volatile int m_currentCount; // The # of outstanding signals before the latch transitions to a signaled state.
- private ManualResetEventSlim m_event; // An event used to manage blocking and signaling.
- private volatile bool m_disposed; // Whether the latch has been disposed.
-
- /// <summary>
- /// Initializes a new instance of <see cref="T:System.Threading.CountdownEvent"/> class with the
- /// specified count.
- /// </summary>
- /// <param name="initialCount">The number of signals required to set the <see
- /// cref="T:System.Threading.CountdownEvent"/>.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less
- /// than 0.</exception>
- public CountdownEvent(int initialCount)
- {
- if (initialCount < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(initialCount));
- }
-
- m_initialCount = initialCount;
- m_currentCount = initialCount;
-
- // Allocate a thin event, which internally defers creation of an actual Win32 event.
- m_event = new ManualResetEventSlim();
-
- // If the latch was created with a count of 0, then it's already in the signaled state.
- if (initialCount == 0)
- {
- m_event.Set();
- }
- }
-
- /// <summary>
- /// Gets the number of remaining signals required to set the event.
- /// </summary>
- /// <value>
- /// The number of remaining signals required to set the event.
- /// </value>
- public int CurrentCount
- {
- get
- {
- int observedCount = m_currentCount;
- return observedCount < 0 ? 0 : observedCount;
- }
- }
-
- /// <summary>
- /// Gets the numbers of signals initially required to set the event.
- /// </summary>
- /// <value>
- /// The number of signals initially required to set the event.
- /// </value>
- public int InitialCount
- {
- get { return m_initialCount; }
- }
-
- /// <summary>
- /// Determines whether the event is set.
- /// </summary>
- /// <value>true if the event is set; otherwise, false.</value>
- public bool IsSet
- {
- get
- {
- // The latch is "completed" if its current count has reached 0. Note that this is NOT
- // the same thing is checking the event's IsCompleted property. There is a tiny window
- // of time, after the final decrement of the current count to 0 and before setting the
- // event, where the two values are out of sync.
- return (m_currentCount <= 0);
- }
- }
-
- /// <summary>
- /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.
- /// </summary>
- /// <value>A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been disposed.</exception>
- /// <remarks>
- /// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases
- /// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/>
- /// to be set, the <see cref="Wait()"/> method should be preferred.
- /// </remarks>
- public WaitHandle WaitHandle
- {
- get
- {
- ThrowIfDisposed();
- return m_event.WaitHandle;
- }
- }
-
- /// <summary>
- /// Releases all resources used by the current instance of <see cref="T:System.Threading.CountdownEvent"/>.
- /// </summary>
- /// <remarks>
- /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not
- /// thread-safe and may not be used concurrently with other members of this instance.
- /// </remarks>
- public void Dispose()
- {
- // Gets rid of this latch's associated resources. This can consist of a Win32 event
- // which is (lazily) allocated by the underlying thin event. This method is not safe to
- // call concurrently -- i.e. a caller must coordinate to ensure only one thread is using
- // the latch at the time of the call to Dispose.
-
- Dispose(true);
- GC.SuppressFinalize(this);
- }
-
- /// <summary>
- /// When overridden in a derived class, releases the unmanaged resources used by the
- /// <see cref="T:System.Threading.CountdownEvent"/>, and optionally releases the managed resources.
- /// </summary>
- /// <param name="disposing">true to release both managed and unmanaged resources; false to release
- /// only unmanaged resources.</param>
- /// <remarks>
- /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not
- /// thread-safe and may not be used concurrently with other members of this instance.
- /// </remarks>
- protected virtual void Dispose(bool disposing)
- {
- if (disposing)
- {
- m_event.Dispose();
- m_disposed = true;
- }
- }
-
- /// <summary>
- /// Registers a signal with the <see cref="T:System.Threading.CountdownEvent"/>, decrementing its
- /// count.
- /// </summary>
- /// <returns>true if the signal caused the count to reach zero and the event was set; otherwise,
- /// false.</returns>
- /// <exception cref="T:System.InvalidOperationException">The current instance is already set.
- /// </exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public bool Signal()
- {
- ThrowIfDisposed();
- Debug.Assert(m_event != null);
-
- if (m_currentCount <= 0)
- {
- throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero"));
- }
-#pragma warning disable 0420
- int newCount = Interlocked.Decrement(ref m_currentCount);
-#pragma warning restore 0420
- if (newCount == 0)
- {
- m_event.Set();
- return true;
- }
- else if (newCount < 0)
- {
- //if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here
- //because there was a thread already which decremented it to zero and set the event
- throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero"));
- }
-
- return false;
- }
-
- /// <summary>
- /// Registers multiple signals with the <see cref="T:System.Threading.CountdownEvent"/>,
- /// decrementing its count by the specified amount.
- /// </summary>
- /// <param name="signalCount">The number of signals to register.</param>
- /// <returns>true if the signals caused the count to reach zero and the event was set; otherwise,
- /// false.</returns>
- /// <exception cref="T:System.InvalidOperationException">
- /// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see
- /// cref="CurrentCount"/>.
- /// </exception>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
- /// than 1.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public bool Signal(int signalCount)
- {
- if (signalCount <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(signalCount));
- }
-
- ThrowIfDisposed();
- Debug.Assert(m_event != null);
-
- int observedCount;
- SpinWait spin = new SpinWait();
- while (true)
- {
- observedCount = m_currentCount;
-
- // If the latch is already signaled, we will fail.
- if (observedCount < signalCount)
- {
- throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero"));
- }
-
- // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning
- // for this statement. This warning is clearly senseless for Interlocked operations.
-#pragma warning disable 0420
- if (Interlocked.CompareExchange(ref m_currentCount, observedCount - signalCount, observedCount) == observedCount)
-#pragma warning restore 0420
- {
- break;
- }
-
- // The CAS failed. Spin briefly and try again.
- spin.SpinOnce();
- }
-
- // If we were the last to signal, set the event.
- if (observedCount == signalCount)
- {
- m_event.Set();
- return true;
- }
-
- Debug.Assert(m_currentCount >= 0, "latch was decremented below zero");
- return false;
- }
-
- /// <summary>
- /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one.
- /// </summary>
- /// <exception cref="T:System.InvalidOperationException">The current instance is already
- /// set.</exception>
- /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
- /// cref="T:System.Int32.MaxValue"/>.</exception>
- /// <exception cref="T:System.ObjectDisposedException">
- /// The current instance has already been disposed.
- /// </exception>
- public void AddCount()
- {
- AddCount(1);
- }
-
- /// <summary>
- /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one.
- /// </summary>
- /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
- /// already at zero. this will return false.</returns>
- /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
- /// cref="T:System.Int32.MaxValue"/>.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public bool TryAddCount()
- {
- return TryAddCount(1);
- }
-
- /// <summary>
- /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a specified
- /// value.
- /// </summary>
- /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than
- /// 0.</exception>
- /// <exception cref="T:System.InvalidOperationException">The current instance is already
- /// set.</exception>
- /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
- /// cref="T:System.Int32.MaxValue"/>.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public void AddCount(int signalCount)
- {
- if (!TryAddCount(signalCount))
- {
- throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyZero"));
- }
- }
-
- /// <summary>
- /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a
- /// specified value.
- /// </summary>
- /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param>
- /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is
- /// already at zero this will return false.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less
- /// than 0.</exception>
- /// <exception cref="T:System.InvalidOperationException">The current instance is already
- /// set.</exception>
- /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see
- /// cref="T:System.Int32.MaxValue"/>.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public bool TryAddCount(int signalCount)
- {
- if (signalCount <= 0)
- {
- throw new ArgumentOutOfRangeException(nameof(signalCount));
- }
-
- ThrowIfDisposed();
-
- // Loop around until we successfully increment the count.
- int observedCount;
- SpinWait spin = new SpinWait();
- while (true)
- {
- observedCount = m_currentCount;
-
- if (observedCount <= 0)
- {
- return false;
- }
- else if (observedCount > (Int32.MaxValue - signalCount))
- {
- throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyMax"));
- }
-
- // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning
- // for this statement. This warning is clearly senseless for Interlocked operations.
-#pragma warning disable 0420
- if (Interlocked.CompareExchange(ref m_currentCount, observedCount + signalCount, observedCount) == observedCount)
-#pragma warning restore 0420
- {
- break;
- }
-
- // The CAS failed. Spin briefly and try again.
- spin.SpinOnce();
- }
-
- return true;
- }
-
- /// <summary>
- /// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>.
- /// </summary>
- /// <remarks>
- /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not
- /// thread-safe and may not be used concurrently with other members of this instance.
- /// </remarks>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed..</exception>
- public void Reset()
- {
- Reset(m_initialCount);
- }
-
- /// <summary>
- /// Resets the <see cref="CurrentCount"/> to a specified value.
- /// </summary>
- /// <param name="count">The number of signals required to set the <see
- /// cref="T:System.Threading.CountdownEvent"/>.</param>
- /// <remarks>
- /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not
- /// thread-safe and may not be used concurrently with other members of this instance.
- /// </remarks>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="count"/> is
- /// less than 0.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has alread been disposed.</exception>
- public void Reset(int count)
- {
- ThrowIfDisposed();
-
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(count));
- }
-
- m_currentCount = count;
- m_initialCount = count;
-
- if (count == 0)
- {
- m_event.Set();
- }
- else
- {
- m_event.Reset();
- }
- }
-
- /// <summary>
- /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set.
- /// </summary>
- /// <remarks>
- /// The caller of this method blocks indefinitely until the current instance is set. The caller will
- /// return immediately if the event is currently in a set state.
- /// </remarks>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public void Wait()
- {
- Wait(Timeout.Infinite, new CancellationToken());
- }
-
-
- /// <summary>
- /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, while
- /// observing a <see cref="T:System.Threading.CancellationToken"/>.
- /// </summary>
- /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
- /// observe.</param>
- /// <remarks>
- /// The caller of this method blocks indefinitely until the current instance is set. The caller will
- /// return immediately if the event is currently in a set state. If the
- /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> being observed
- /// is canceled during the wait operation, an <see cref="T:System.OperationCanceledException"/>
- /// will be thrown.
- /// </remarks>
- /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been
- /// canceled.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public void Wait(CancellationToken cancellationToken)
- {
- Wait(Timeout.Infinite, cancellationToken);
- }
-
- /// <summary>
- /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a
- /// <see cref="T:System.TimeSpan"/> to measure the time interval.
- /// </summary>
- /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of
- /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to
- /// wait indefinitely.</param>
- /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
- /// false.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
- /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
- /// than <see cref="System.Int32.MaxValue"/>.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public bool Wait(TimeSpan timeout)
- {
- long totalMilliseconds = (long)timeout.TotalMilliseconds;
- if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
- {
- throw new ArgumentOutOfRangeException(nameof(timeout));
- }
-
- return Wait((int)totalMilliseconds, new CancellationToken());
- }
-
- /// <summary>
- /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using
- /// a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a
- /// <see cref="T:System.Threading.CancellationToken"/>.
- /// </summary>
- /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of
- /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to
- /// wait indefinitely.</param>
- /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
- /// observe.</param>
- /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
- /// false.</returns>
- /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative
- /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater
- /// than <see cref="System.Int32.MaxValue"/>.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has
- /// been canceled.</exception>
- public bool Wait(TimeSpan timeout, CancellationToken cancellationToken)
- {
- long totalMilliseconds = (long)timeout.TotalMilliseconds;
- if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
- {
- throw new ArgumentOutOfRangeException(nameof(timeout));
- }
-
- return Wait((int)totalMilliseconds, cancellationToken);
- }
-
- /// <summary>
- /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a
- /// 32-bit signed integer to measure the time interval.
- /// </summary>
- /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
- /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
- /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
- /// false.</returns>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
- /// negative number other than -1, which represents an infinite time-out.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- public bool Wait(int millisecondsTimeout)
- {
- return Wait(millisecondsTimeout, new CancellationToken());
- }
-
- /// <summary>
- /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a
- /// 32-bit signed integer to measure the time interval, while observing a
- /// <see cref="T:System.Threading.CancellationToken"/>.
- /// </summary>
- /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
- /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param>
- /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to
- /// observe.</param>
- /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise,
- /// false.</returns>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
- /// negative number other than -1, which represents an infinite time-out.</exception>
- /// <exception cref="T:System.ObjectDisposedException">The current instance has already been
- /// disposed.</exception>
- /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has
- /// been canceled.</exception>
- public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken)
- {
- if (millisecondsTimeout < -1)
- {
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
- }
-
- ThrowIfDisposed();
- cancellationToken.ThrowIfCancellationRequested();
-
- bool returnValue = IsSet;
-
- // If not completed yet, wait on the event.
- if (!returnValue)
- {
- // ** the actual wait
- returnValue = m_event.Wait(millisecondsTimeout, cancellationToken);
- //the Wait will throw OCE itself if the token is canceled.
- }
-
- return returnValue;
- }
-
- // --------------------------------------
- // Private methods
-
-
- /// <summary>
- /// Throws an exception if the latch has been disposed.
- /// </summary>
- private void ThrowIfDisposed()
- {
- if (m_disposed)
- {
- throw new ObjectDisposedException("CountdownEvent");
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/Threading/EventResetMode.cs b/src/mscorlib/src/System/Threading/EventResetMode.cs
deleted file mode 100644
index edafab9bb5..0000000000
--- a/src/mscorlib/src/System/Threading/EventResetMode.cs
+++ /dev/null
@@ -1,26 +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.
-
-//
-/*=============================================================================
-**
-** Enum: EventResetMode
-**
-**
-** Purpose: Enum to determine the Event type to create
-**
-**
-=============================================================================*/
-
-
-namespace System.Threading
-{
- using System.Runtime.InteropServices;
- [ComVisibleAttribute(false)]
- public enum EventResetMode
- {
- AutoReset = 0,
- ManualReset = 1
- }
-}
diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
index 0268948a5c..611d9de7e7 100644
--- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
@@ -39,25 +39,25 @@ namespace System.Threading
[ComVisibleAttribute(true)]
public class EventWaitHandle : WaitHandle
{
- public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState,mode,null) { }
+ public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState, mode, null) { }
public EventWaitHandle(bool initialState, EventResetMode mode, string name)
{
- if(name != null)
+ if (name != null)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
#endif
}
Contract.EndContractBlock();
-
+
SafeWaitHandle _handle = null;
- switch(mode)
+ switch (mode)
{
case EventResetMode.ManualReset:
_handle = Win32Native.CreateEvent(null, true, initialState, name);
@@ -67,16 +67,16 @@ namespace System.Threading
break;
default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name));
};
-
+
if (_handle.IsInvalid)
{
int errorCode = Marshal.GetLastWin32Error();
-
+
_handle.SetHandleAsInvalid();
- if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
- throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name));
+ 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);
}
@@ -90,14 +90,14 @@ namespace System.Threading
internal unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
{
- if(name != null)
+ if (name != null)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
#endif
}
@@ -106,7 +106,7 @@ namespace System.Threading
SafeWaitHandle _handle = null;
Boolean isManualReset;
- switch(mode)
+ switch (mode)
{
case EventResetMode.ManualReset:
isManualReset = true;
@@ -116,7 +116,7 @@ namespace System.Threading
break;
default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidFlag, name));
};
_handle = Win32Native.CreateEvent(secAttrs, isManualReset, initialState, name);
@@ -124,10 +124,9 @@ namespace System.Threading
if (_handle.IsInvalid)
{
-
_handle.SetHandleAsInvalid();
- if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
- throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name));
+ 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);
}
@@ -154,7 +153,7 @@ namespace System.Threading
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
- throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
+ throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
__Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, "");
@@ -173,23 +172,23 @@ namespace System.Threading
private static OpenExistingResult OpenExistingWorker(string name, EventWaitHandleRights rights, out EventWaitHandle result)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (name == null)
{
- throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
+ throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName);
}
- if(name.Length == 0)
+ if (name.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
}
- if(null != name && System.IO.Path.MaxPath < name.Length)
+ if (null != name && System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
-
+
Contract.EndContractBlock();
result = null;
@@ -200,14 +199,14 @@ namespace System.Threading
{
int errorCode = Marshal.GetLastWin32Error();
- if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
+ if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
- if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
+ if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through Win32Native Errors
- __Error.WinIOError(errorCode,"");
+ __Error.WinIOError(errorCode, "");
}
result = new EventWaitHandle(myHandle);
return OpenExistingResult.Success;
diff --git a/src/mscorlib/src/System/Threading/ExecutionContext.cs b/src/mscorlib/src/System/Threading/ExecutionContext.cs
deleted file mode 100644
index 47a55a3bb9..0000000000
--- a/src/mscorlib/src/System/Threading/ExecutionContext.cs
+++ /dev/null
@@ -1,380 +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: Capture execution context for a thread
-**
-**
-===========================================================*/
-namespace System.Threading
-{
- using System;
- using System.Security;
- using System.Runtime.Remoting;
- using System.Collections;
- using System.Collections.Generic;
- using System.Reflection;
- using System.Runtime.ExceptionServices;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Diagnostics.CodeAnalysis;
-
- public delegate void ContextCallback(Object state);
-
- internal struct ExecutionContextSwitcher
- {
- internal ExecutionContext m_ec;
- internal SynchronizationContext m_sc;
-
- internal void Undo(Thread currentThread)
- {
- Debug.Assert(currentThread == Thread.CurrentThread);
-
- // The common case is that these have not changed, so avoid the cost of a write if not needed.
- if (currentThread.SynchronizationContext != m_sc)
- {
- currentThread.SynchronizationContext = m_sc;
- }
-
- if (currentThread.ExecutionContext != m_ec)
- {
- ExecutionContext.Restore(currentThread, m_ec);
- }
- }
- }
-
- [Serializable]
- public sealed class ExecutionContext : IDisposable, ISerializable
- {
- internal static readonly ExecutionContext Default = new ExecutionContext();
-
- private readonly IAsyncLocalValueMap m_localValues;
- private readonly IAsyncLocal[] m_localChangeNotifications;
- private readonly bool m_isFlowSuppressed;
-
- private ExecutionContext()
- {
- m_localValues = AsyncLocalValueMap.Empty;
- m_localChangeNotifications = Array.Empty<IAsyncLocal>();
- }
-
- private ExecutionContext(
- IAsyncLocalValueMap localValues,
- IAsyncLocal[] localChangeNotifications,
- bool isFlowSuppressed)
- {
- m_localValues = localValues;
- m_localChangeNotifications = localChangeNotifications;
- m_isFlowSuppressed = isFlowSuppressed;
- }
-
- public void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
- Contract.EndContractBlock();
- }
-
- private ExecutionContext(SerializationInfo info, StreamingContext context)
- {
- }
-
- public static ExecutionContext Capture()
- {
- ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
- return
- executionContext == null ? Default :
- executionContext.m_isFlowSuppressed ? null :
- executionContext;
- }
-
- private ExecutionContext ShallowClone(bool isFlowSuppressed)
- {
- Debug.Assert(isFlowSuppressed != m_isFlowSuppressed);
-
- if (!isFlowSuppressed &&
- m_localValues == Default.m_localValues &&
- m_localChangeNotifications == Default.m_localChangeNotifications)
- {
- return null; // implies the default context
- }
- return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed);
- }
-
- public static AsyncFlowControl SuppressFlow()
- {
- Thread currentThread = Thread.CurrentThread;
- ExecutionContext executionContext = currentThread.ExecutionContext ?? Default;
- if (executionContext.m_isFlowSuppressed)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"));
- }
- Contract.EndContractBlock();
-
- executionContext = executionContext.ShallowClone(isFlowSuppressed: true);
- var asyncFlowControl = new AsyncFlowControl();
- currentThread.ExecutionContext = executionContext;
- asyncFlowControl.Initialize(currentThread);
- return asyncFlowControl;
- }
-
- public static void RestoreFlow()
- {
- Thread currentThread = Thread.CurrentThread;
- ExecutionContext executionContext = currentThread.ExecutionContext;
- if (executionContext == null || !executionContext.m_isFlowSuppressed)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"));
- }
- Contract.EndContractBlock();
-
- currentThread.ExecutionContext = executionContext.ShallowClone(isFlowSuppressed: false);
- }
-
- public static bool IsFlowSuppressed()
- {
- ExecutionContext executionContext = Thread.CurrentThread.ExecutionContext;
- return executionContext != null && executionContext.m_isFlowSuppressed;
- }
-
- [HandleProcessCorruptedStateExceptions]
- public static void Run(ExecutionContext executionContext, ContextCallback callback, Object state)
- {
- if (executionContext == null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NullContext"));
-
- Thread currentThread = Thread.CurrentThread;
- ExecutionContextSwitcher ecsw = default(ExecutionContextSwitcher);
- try
- {
- EstablishCopyOnWriteScope(currentThread, ref ecsw);
- ExecutionContext.Restore(currentThread, executionContext);
- callback(state);
- }
- catch
- {
- // Note: we have a "catch" rather than a "finally" because we want
- // to stop the first pass of EH here. That way we can restore the previous
- // context before any of our callers' EH filters run. That means we need to
- // end the scope separately in the non-exceptional case below.
- ecsw.Undo(currentThread);
- throw;
- }
- ecsw.Undo(currentThread);
- }
-
- internal static void Restore(Thread currentThread, ExecutionContext executionContext)
- {
- Debug.Assert(currentThread == Thread.CurrentThread);
-
- ExecutionContext previous = currentThread.ExecutionContext ?? Default;
- currentThread.ExecutionContext = executionContext;
-
- // New EC could be null if that's what ECS.Undo saved off.
- // For the purposes of dealing with context change, treat this as the default EC
- executionContext = executionContext ?? Default;
-
- if (previous != executionContext)
- {
- OnContextChanged(previous, executionContext);
- }
- }
-
- static internal void EstablishCopyOnWriteScope(Thread currentThread, ref ExecutionContextSwitcher ecsw)
- {
- Debug.Assert(currentThread == Thread.CurrentThread);
-
- ecsw.m_ec = currentThread.ExecutionContext;
- ecsw.m_sc = currentThread.SynchronizationContext;
- }
-
- [HandleProcessCorruptedStateExceptions]
- private static void OnContextChanged(ExecutionContext previous, ExecutionContext current)
- {
- Debug.Assert(previous != null);
- Debug.Assert(current != null);
- Debug.Assert(previous != current);
-
- foreach (IAsyncLocal local in previous.m_localChangeNotifications)
- {
- object previousValue;
- object currentValue;
- previous.m_localValues.TryGetValue(local, out previousValue);
- current.m_localValues.TryGetValue(local, out currentValue);
-
- if (previousValue != currentValue)
- local.OnValueChanged(previousValue, currentValue, true);
- }
-
- if (current.m_localChangeNotifications != previous.m_localChangeNotifications)
- {
- try
- {
- foreach (IAsyncLocal local in current.m_localChangeNotifications)
- {
- // If the local has a value in the previous context, we already fired the event for that local
- // in the code above.
- object previousValue;
- if (!previous.m_localValues.TryGetValue(local, out previousValue))
- {
- object currentValue;
- current.m_localValues.TryGetValue(local, out currentValue);
-
- if (previousValue != currentValue)
- local.OnValueChanged(previousValue, currentValue, true);
- }
- }
- }
- catch (Exception ex)
- {
- Environment.FailFast(
- Environment.GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"),
- ex);
- }
- }
- }
-
- internal static object GetLocalValue(IAsyncLocal local)
- {
- ExecutionContext current = Thread.CurrentThread.ExecutionContext;
- if (current == null)
- return null;
-
- object value;
- current.m_localValues.TryGetValue(local, out value);
- return value;
- }
-
- internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications)
- {
- ExecutionContext current = Thread.CurrentThread.ExecutionContext ?? ExecutionContext.Default;
-
- object previousValue;
- bool hadPreviousValue = current.m_localValues.TryGetValue(local, out previousValue);
-
- if (previousValue == newValue)
- return;
-
- IAsyncLocalValueMap newValues = current.m_localValues.Set(local, newValue);
-
- //
- // Either copy the change notification array, or create a new one, depending on whether we need to add a new item.
- //
- IAsyncLocal[] newChangeNotifications = current.m_localChangeNotifications;
- if (needChangeNotifications)
- {
- if (hadPreviousValue)
- {
- Debug.Assert(Array.IndexOf(newChangeNotifications, local) >= 0);
- }
- else
- {
- int newNotificationIndex = newChangeNotifications.Length;
- Array.Resize(ref newChangeNotifications, newNotificationIndex + 1);
- newChangeNotifications[newNotificationIndex] = local;
- }
- }
-
- Thread.CurrentThread.ExecutionContext =
- new ExecutionContext(newValues, newChangeNotifications, current.m_isFlowSuppressed);
-
- if (needChangeNotifications)
- {
- local.OnValueChanged(previousValue, newValue, false);
- }
- }
-
- public ExecutionContext CreateCopy()
- {
- return this; // since CoreCLR's ExecutionContext is immutable, we don't need to create copies.
- }
-
- public void Dispose()
- {
- // For CLR compat only
- }
- }
-
- public struct AsyncFlowControl : IDisposable
- {
- private Thread _thread;
-
- internal void Initialize(Thread currentThread)
- {
- Debug.Assert(currentThread == Thread.CurrentThread);
- _thread = currentThread;
- }
-
- public void Undo()
- {
- if (_thread == null)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCMultiple"));
- }
- if (Thread.CurrentThread != _thread)
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotUseAFCOtherThread"));
- }
-
- // An async flow control cannot be undone when a different execution context is applied. The desktop framework
- // mutates the execution context when its state changes, and only changes the instance when an execution context
- // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution
- // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution
- // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async
- // local's value, the desktop framework verifies that a different execution context has not been applied by
- // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core,
- // since the execution context instance will change after changing the async local's value, it verifies that a
- // different execution context has not been applied, by instead ensuring that the current execution context's
- // flow is suppressed.
- if (!ExecutionContext.IsFlowSuppressed())
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"));
- }
- Contract.EndContractBlock();
-
- _thread = null;
- ExecutionContext.RestoreFlow();
- }
-
- public void Dispose()
- {
- Undo();
- }
-
- public override bool Equals(object obj)
- {
- return obj is AsyncFlowControl && Equals((AsyncFlowControl)obj);
- }
-
- public bool Equals(AsyncFlowControl obj)
- {
- return _thread == obj._thread;
- }
-
- public override int GetHashCode()
- {
- return _thread?.GetHashCode() ?? 0;
- }
-
- public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b)
- {
- return a.Equals(b);
- }
-
- public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b)
- {
- return !(a == b);
- }
- }
-}
-
-
diff --git a/src/mscorlib/src/System/Threading/Interlocked.cs b/src/mscorlib/src/System/Threading/Interlocked.cs
index 131d51a65b..7e2c2aeeab 100644
--- a/src/mscorlib/src/System/Threading/Interlocked.cs
+++ b/src/mscorlib/src/System/Threading/Interlocked.cs
@@ -3,21 +3,24 @@
// See the LICENSE file in the project root for more information.
//
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
+using System.Runtime;
+using System.Runtime.InteropServices;
+using System.Security;
+
namespace System.Threading
{
- using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Runtime;
-
// After much discussion, we decided the Interlocked class doesn't need
// any HPA's for synchronization or external threading. They hurt C#'s
// codegen for the yield keyword, and arguably they didn't protect much.
// Instead, they penalized people (and compilers) for writing threadsafe
// code.
public static class Interlocked
- {
+ {
/******************************
* Increment
* Implemented: int
@@ -102,16 +105,16 @@ namespace System.Threading
*****************************/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern int CompareExchange(ref int location1, int value, int comparand);
+ public static extern int CompareExchange(ref int location1, int value, int comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern long CompareExchange(ref long location1, long value, long comparand);
+ public static extern long CompareExchange(ref long location1, long value, long comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern float CompareExchange(ref float location1, float value, float comparand);
+ public static extern float CompareExchange(ref float location1, float value, float comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern double CompareExchange(ref double location1, double value, double comparand);
+ public static extern double CompareExchange(ref double location1, double value, double comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern Object CompareExchange(ref Object location1, Object value, Object comparand);
@@ -142,7 +145,7 @@ namespace System.Threading
* See getILIntrinsicImplementationForInterlocked() in VM\JitInterface.cpp
* for details.
*****************************************************************/
-
+
public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class
{
// _CompareExchange() passes back the value read from location1 via local named 'value'
@@ -169,28 +172,34 @@ namespace System.Threading
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern long ExchangeAdd(ref long location1, long value);
- public static int Add(ref int location1, int value)
+ public static int Add(ref int location1, int value)
{
return ExchangeAdd(ref location1, value) + value;
}
- public static long Add(ref long location1, long value)
+ public static long Add(ref long location1, long value)
{
return ExchangeAdd(ref location1, value) + value;
}
-
+
/******************************
* Read
*****************************/
public static long Read(ref long location)
{
- return Interlocked.CompareExchange(ref location,0,0);
+ return Interlocked.CompareExchange(ref location, 0, 0);
}
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern void MemoryBarrier();
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void _MemoryBarrierProcessWide();
- public static void MemoryBarrier()
+ public static void MemoryBarrierProcessWide()
{
- Thread.MemoryBarrier();
+ _MemoryBarrierProcessWide();
}
}
}
diff --git a/src/mscorlib/src/System/Threading/LazyInitializer.cs b/src/mscorlib/src/System/Threading/LazyInitializer.cs
index af32673d03..d585ba6c35 100644
--- a/src/mscorlib/src/System/Threading/LazyInitializer.cs
+++ b/src/mscorlib/src/System/Threading/LazyInitializer.cs
@@ -13,40 +13,9 @@
using System.Diagnostics;
using System.Diagnostics.Contracts;
+
namespace System.Threading
{
-
- /// <summary>
- /// Specifies how a <see cref="T:System.Threading.Lazy{T}"/> instance should synchronize access among multiple threads.
- /// </summary>
- public enum LazyThreadSafetyMode
- {
- /// <summary>
- /// This mode makes no guarantees around the thread-safety of the <see cref="T:System.Threading.Lazy{T}"/> instance. If used from multiple threads, the behavior of the <see cref="T:System.Threading.Lazy{T}"/> is undefined.
- /// This mode should be used when a <see cref="T:System.Threading.Lazy{T}"/> is guaranteed to never be initialized from more than one thread simultaneously and high performance is crucial.
- /// If valueFactory throws an exception when the <see cref="T:System.Threading.Lazy{T}"/> is initialized, the exception will be cached and returned on subsequent accesses to Value. Also, if valueFactory recursively
- /// accesses Value on this <see cref="T:System.Threading.Lazy{T}"/> instance, a <see cref="T:System.InvalidOperationException"/> will be thrown.
- /// </summary>
- None,
-
- /// <summary>
- /// When multiple threads attempt to simultaneously initialize a <see cref="T:System.Threading.Lazy{T}"/> instance, this mode allows each thread to execute the
- /// valueFactory but only the first thread to complete initialization will be allowed to set the final value of the <see cref="T:System.Threading.Lazy{T}"/>.
- /// Once initialized successfully, any future calls to Value will return the cached result. If valueFactory throws an exception on any thread, that exception will be
- /// propagated out of Value. If any thread executes valueFactory without throwing an exception and, therefore, successfully sets the value, that value will be returned on
- /// subsequent accesses to Value from any thread. If no thread succeeds in setting the value, IsValueCreated will remain false and subsequent accesses to Value will result in
- /// the valueFactory delegate re-executing. Also, if valueFactory recursively accesses Value on this <see cref="T:System.Threading.Lazy{T}"/> instance, an exception will NOT be thrown.
- /// </summary>
- PublicationOnly,
-
- /// <summary>
- /// This mode uses locks to ensure that only a single thread can initialize a <see cref="T:System.Threading.Lazy{T}"/> instance in a thread-safe manner. In general,
- /// taken if this mode is used in conjunction with a <see cref="T:System.Threading.Lazy{T}"/> valueFactory delegate that uses locks internally, a deadlock can occur if not
- /// handled carefully. If valueFactory throws an exception when the<see cref="T:System.Threading.Lazy{T}"/> is initialized, the exception will be cached and returned on
- /// subsequent accesses to Value. Also, if valueFactory recursively accesses Value on this <see cref="T:System.Threading.Lazy{T}"/> instance, a <see cref="T:System.InvalidOperationException"/> will be thrown.
- /// </summary>
- ExecutionAndPublication
- }
/// <summary>
/// Provides lazy initialization routines.
/// </summary>
@@ -82,16 +51,8 @@ namespace System.Threading
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
- public static T EnsureInitialized<T>(ref T target) where T : class
- {
- // Fast path.
- if (Volatile.Read<T>(ref target) != null)
- {
- return target;
- }
-
- return EnsureInitializedCore<T>(ref target, LazyHelpers<T>.s_activatorFactorySelector);
- }
+ public static T EnsureInitialized<T>(ref T target) where T : class =>
+ Volatile.Read<T>(ref target) ?? EnsureInitializedCore<T>(ref target, LazyHelpers<T>.s_activatorFactorySelector);
/// <summary>
/// Initializes a target reference type using the specified function if it has not already been
@@ -121,16 +82,8 @@ namespace System.Threading
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
- public static T EnsureInitialized<T>(ref T target, Func<T> valueFactory) where T : class
- {
- // Fast path.
- if (Volatile.Read<T>(ref target) != null)
- {
- return target;
- }
-
- return EnsureInitializedCore<T>(ref target, valueFactory);
- }
+ public static T EnsureInitialized<T>(ref T target, Func<T> valueFactory) where T : class =>
+ Volatile.Read<T>(ref target) ?? EnsureInitializedCore<T>(ref target, valueFactory);
/// <summary>
/// Initialize the target using the given delegate (slow path).
@@ -144,7 +97,7 @@ namespace System.Threading
T value = valueFactory();
if (value == null)
{
- throw new InvalidOperationException(Environment.GetResourceString("Lazy_StaticInit_InvalidOperation"));
+ throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
Interlocked.CompareExchange(ref target, value, null);
@@ -152,7 +105,6 @@ namespace System.Threading
return target;
}
-
/// <summary>
/// Initializes a target reference or value type with its default constructor if it has not already
/// been initialized.
@@ -198,11 +150,33 @@ namespace System.Threading
return target;
}
-
return EnsureInitializedCore<T>(ref target, ref initialized, ref syncLock, valueFactory);
}
/// <summary>
+ /// Ensure the lock object is intialized.
+ /// </summary>
+ /// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
+ /// a new object will be instantiated.</param>
+ /// <returns>Initialized lock object.</returns>
+ private static object EnsureLockInitialized(ref object syncLock) =>
+ syncLock ??
+ Interlocked.CompareExchange(ref syncLock, new object(), null) ??
+ syncLock;
+
+ /// <summary>
+ /// Initializes a target reference type with a specified function if it has not already been initialized.
+ /// </summary>
+ /// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
+ /// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
+ /// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
+ /// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
+ /// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the reference.</param>
+ /// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
+ public static T EnsureInitialized<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class =>
+ Volatile.Read(ref target) ?? EnsureInitializedCore<T>(ref target, ref syncLock, valueFactory);
+
+ /// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the supplied function to create the value.
/// </summary>
@@ -217,35 +191,52 @@ namespace System.Threading
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
- // Lazily initialize the lock if necessary.
- object slock = syncLock;
- if (slock == null)
+ // Lazily initialize the lock if necessary and, then double check if initialization is still required.
+ lock (EnsureLockInitialized(ref syncLock))
{
- object newLock = new object();
- slock = Interlocked.CompareExchange(ref syncLock, newLock, null);
- if (slock == null)
+ if (!Volatile.Read(ref initialized))
{
- slock = newLock;
+ target = valueFactory();
+ Volatile.Write(ref initialized, true);
}
}
- // Now double check that initialization is still required.
- lock (slock)
+ return target;
+ }
+
+ /// <summary>
+ /// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
+ /// Uses the supplied function to create the value.
+ /// </summary>
+ /// <typeparam name="T">The type of target. Has to be reference type.</typeparam>
+ /// <param name="target">A reference to the target to be initialized.</param>
+ /// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
+ /// a new object will be instantiated.</param>
+ /// <param name="valueFactory">
+ /// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
+ /// </param>
+ /// <returns>The initialized object.</returns>
+ private static T EnsureInitializedCore<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class
+ {
+ // Lazily initialize the lock if necessary and, then double check if initialization is still required.
+ lock (EnsureLockInitialized(ref syncLock))
{
- if (!Volatile.Read(ref initialized))
+ if (Volatile.Read(ref target) == null)
{
- target = valueFactory();
- Volatile.Write(ref initialized, true);
+ Volatile.Write(ref target, valueFactory());
+ if (target == null)
+ {
+ throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
+ }
}
}
return target;
}
-
}
// Caches the activation selector function to avoid delegate allocations.
- static class LazyHelpers<T>
+ internal static class LazyHelpers<T>
{
internal static Func<T> s_activatorFactorySelector = new Func<T>(ActivatorFactorySelector);
@@ -257,7 +248,7 @@ namespace System.Threading
}
catch (MissingMethodException)
{
- throw new MissingMemberException(Environment.GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT"));
+ throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
}
}
diff --git a/src/mscorlib/src/System/Threading/LockRecursionException.cs b/src/mscorlib/src/System/Threading/LockRecursionException.cs
deleted file mode 100644
index 40f04b00b4..0000000000
--- a/src/mscorlib/src/System/Threading/LockRecursionException.cs
+++ /dev/null
@@ -1,30 +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 exception represents a failed attempt to recursively
-// acquire a lock, because the particular lock kind doesn't
-// support it in its current state.
-============================================================*/
-
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
-
- [Serializable]
- public class LockRecursionException : System.Exception
- {
- public LockRecursionException() { }
- public LockRecursionException(string message) : base(message) { }
- protected LockRecursionException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- public LockRecursionException(string message, Exception innerException) : base(message, innerException) { }
- }
-
-}
diff --git a/src/mscorlib/src/System/Threading/ManualResetEvent.cs b/src/mscorlib/src/System/Threading/ManualResetEvent.cs
deleted file mode 100644
index a8e012fb43..0000000000
--- a/src/mscorlib/src/System/Threading/ManualResetEvent.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: An example of a WaitHandle class
-**
-**
-=============================================================================*/
-namespace System.Threading {
-
- using System;
- using System.Runtime.InteropServices;
-
- public sealed class ManualResetEvent : EventWaitHandle
- {
- public ManualResetEvent(bool initialState) : base(initialState,EventResetMode.ManualReset){}
- }
-}
-
diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
index 2d57b4102b..402a76cdc7 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
@@ -20,7 +20,6 @@ using System.Diagnostics.Contracts;
namespace System.Threading
{
-
// ManualResetEventSlim wraps a manual-reset event internally with a little bit of
// spinning. When an event will be set imminently, it is often advantageous to avoid
// a 4k+ cycle context switch in favor of briefly spinning. Therefore we layer on to
@@ -98,7 +97,6 @@ namespace System.Threading
/// </remarks>
public WaitHandle WaitHandle
{
-
get
{
ThrowIfDisposed();
@@ -165,11 +163,10 @@ namespace System.Threading
// it is possible for the max number of waiters to be exceeded via user-code, hence we use a real exception here.
if (value >= NumWaitersState_MaxValue)
- throw new InvalidOperationException(String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_TooManyWaiters"), NumWaitersState_MaxValue));
+ throw new InvalidOperationException(String.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, NumWaitersState_MaxValue));
UpdateStateAtomically(value << NumWaitersState_ShiftCount, NumWaitersState_BitMask);
}
-
}
//-----------------------------------------------------------------------------------
@@ -184,7 +181,6 @@ namespace System.Threading
public ManualResetEventSlim()
: this(false)
{
-
}
/// <summary>
@@ -222,7 +218,7 @@ namespace System.Threading
{
throw new ArgumentOutOfRangeException(
nameof(spinCount),
- String.Format(Environment.GetResourceString("ManualResetEventSlim_ctor_SpinCountOutOfRange"), SpinCountState_MaxValue));
+ String.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, SpinCountState_MaxValue));
}
// We will suppress default spin because the user specified a count.
@@ -236,14 +232,13 @@ namespace System.Threading
/// <param name="spinCount">The spin count that decides when the event will block.</param>
private void Initialize(bool initialState, int spinCount)
{
- this.m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
+ m_combinedState = initialState ? (1 << SignalledState_ShiftCount) : 0;
//the spinCount argument has been validated by the ctors.
//but we now sanity check our predefined constants.
Debug.Assert(DEFAULT_SPIN_SP >= 0, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
Debug.Assert(DEFAULT_SPIN_SP <= SpinCountState_MaxValue, "Internal error - DEFAULT_SPIN_SP is outside the legal range.");
SpinCount = PlatformHelper.IsSingleProcessor ? DEFAULT_SPIN_SP : spinCount;
-
}
/// <summary>
@@ -283,7 +278,6 @@ namespace System.Threading
}
else
{
-
// Now that the event is published, verify that the state hasn't changed since
// we snapped the preInitializeState. Another thread could have done that
// between our initial observation above and here. The barrier incurred from
@@ -337,7 +331,6 @@ namespace System.Threading
Debug.Assert(m_lock != null); //if waiters>0, then m_lock has already been created.
lock (m_lock)
{
-
Monitor.PulseAll(m_lock);
}
}
@@ -665,7 +658,6 @@ namespace System.Threading
// Now just loop back around, and the right thing will happen. Either:
// 1. We had a spurious wake-up due to some other wait being canceled via a different cancellationToken (rewait)
// or 2. the wait was successful. (the loop will break)
-
}
}
}
@@ -725,7 +717,7 @@ namespace System.Threading
private void ThrowIfDisposed()
{
if ((m_combinedState & Dispose_BitMask) != 0)
- throw new ObjectDisposedException(Environment.GetResourceString("ManualResetEventSlim_Disposed"));
+ throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed);
}
/// <summary>
diff --git a/src/mscorlib/src/System/Threading/Monitor.cs b/src/mscorlib/src/System/Threading/Monitor.cs
index fdbc384243..3ace3335aa 100644
--- a/src/mscorlib/src/System/Threading/Monitor.cs
+++ b/src/mscorlib/src/System/Threading/Monitor.cs
@@ -14,19 +14,20 @@
=============================================================================*/
-namespace System.Threading {
-
- using System;
- using System.Runtime;
- using System.Runtime.Remoting;
- using System.Threading;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
-
- public static class Monitor
+
+using System;
+using System.Runtime;
+using System.Runtime.Remoting;
+using System.Threading;
+using System.Runtime.CompilerServices;
+using System.Runtime.ConstrainedExecution;
+using System.Runtime.Versioning;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System.Threading
+{
+ public static class Monitor
{
/*=========================================================================
** Obtain the monitor lock of obj. Will block if another thread holds the lock
@@ -56,7 +57,7 @@ namespace System.Threading {
private static void ThrowLockTakenException()
{
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeFalse"), "lockTaken");
+ throw new ArgumentException(SR.Argument_MustBeFalse, "lockTaken");
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -75,7 +76,7 @@ namespace System.Threading {
=========================================================================*/
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern void Exit(Object obj);
-
+
/*=========================================================================
** Similar to Enter, but will never block. That is, if the current thread can
** acquire the monitor lock without blocking, it will do so and TRUE will
@@ -99,7 +100,7 @@ namespace System.Threading {
ReliableEnterTimeout(obj, 0, ref lockTaken);
}
-
+
/*=========================================================================
** Version of TryEnter that will block, but only up to a timeout period
** expressed in milliseconds. If timeout == Timeout.Infinite the method
@@ -121,7 +122,7 @@ namespace System.Threading {
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1 || tm > (long)Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return (int)tm;
}
diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs
index dcb821307a..454a323f9a 100644
--- a/src/mscorlib/src/System/Threading/Mutex.cs
+++ b/src/mscorlib/src/System/Threading/Mutex.cs
@@ -11,8 +11,9 @@
**
**
=============================================================================*/
-namespace System.Threading
-{
+
+namespace System.Threading
+{
using System;
using System.Threading;
using System.Runtime.CompilerServices;
@@ -28,7 +29,7 @@ namespace System.Threading
public sealed class Mutex : WaitHandle
{
- static bool dummyBool;
+ private static bool dummyBool;
internal class MutexSecurity
{
@@ -46,12 +47,12 @@ namespace System.Threading
// Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on.
name = null;
}
-#if !PLATFORM_UNIX
+#if PLATFORM_WINDOWS
if (name != null && System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
-#endif
+#endif // PLATFORM_WINDOWS
Contract.EndContractBlock();
Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
@@ -67,20 +68,20 @@ namespace System.Threading
RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
tryCode,
cleanupCode,
- cleanupInfo);
+ cleanupInfo);
createdNew = tryCodeHelper.m_newMutex;
}
- internal class MutexTryCodeHelper
+ internal class MutexTryCodeHelper
{
- bool m_initiallyOwned;
- MutexCleanupInfo m_cleanupInfo;
+ private bool m_initiallyOwned;
+ private MutexCleanupInfo m_cleanupInfo;
internal bool m_newMutex;
- String m_name;
- Win32Native.SECURITY_ATTRIBUTES m_secAttrs;
- Mutex m_mutex;
+ private String m_name;
+ private Win32Native.SECURITY_ATTRIBUTES m_secAttrs;
+ private Mutex m_mutex;
- internal MutexTryCodeHelper(bool initiallyOwned,MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
+ internal MutexTryCodeHelper(bool initiallyOwned, MutexCleanupInfo cleanupInfo, String name, Win32Native.SECURITY_ATTRIBUTES secAttrs, Mutex mutex)
{
Debug.Assert(name == null || name.Length != 0);
@@ -92,16 +93,16 @@ namespace System.Threading
}
internal void MutexTryCode(object userData)
- {
+ {
SafeWaitHandle mutexHandle = null;
// try block
RuntimeHelpers.PrepareConstrainedRegions();
- try
+ try
{
}
- finally
+ finally
{
- if (m_initiallyOwned)
+ if (m_initiallyOwned)
{
m_cleanupInfo.inCriticalRegion = true;
}
@@ -109,15 +110,15 @@ namespace System.Threading
int errorCode = 0;
RuntimeHelpers.PrepareConstrainedRegions();
- try
+ try
{
}
- finally
+ finally
{
errorCode = CreateMutexHandle(m_initiallyOwned, m_name, m_secAttrs, out mutexHandle);
- }
+ }
- if (mutexHandle.IsInvalid)
+ if (mutexHandle.IsInvalid)
{
mutexHandle.SetHandleAsInvalid();
if (m_name != null)
@@ -127,11 +128,11 @@ namespace System.Threading
#if PLATFORM_UNIX
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Interop.Sys.MaxName), "name");
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Sys.MaxName), "name");
#endif
case Win32Native.ERROR_INVALID_HANDLE:
- throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", m_name));
+ throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, m_name));
}
}
__Error.WinIOError(errorCode, m_name);
@@ -140,19 +141,21 @@ namespace System.Threading
m_mutex.SetHandleInternal(mutexHandle);
m_mutex.hasThreadAffinity = true;
-
}
}
private void MutexCleanupCode(Object userData, bool exceptionThrown)
{
- MutexCleanupInfo cleanupInfo = (MutexCleanupInfo) userData;
-
+ MutexCleanupInfo cleanupInfo = (MutexCleanupInfo)userData;
+
// If hasThreadAffinity isn't true, we've thrown an exception in the above try, and we must free the mutex
// on this OS thread before ending our thread affninity.
- if(!hasThreadAffinity) {
- if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid) {
- if( cleanupInfo.inCriticalRegion) {
+ if (!hasThreadAffinity)
+ {
+ if (cleanupInfo.mutexHandle != null && !cleanupInfo.mutexHandle.IsInvalid)
+ {
+ if (cleanupInfo.inCriticalRegion)
+ {
Win32Native.ReleaseMutex(cleanupInfo.mutexHandle);
}
cleanupInfo.mutexHandle.Dispose();
@@ -171,7 +174,8 @@ namespace System.Threading
}
}
- public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool) {
+ public Mutex(bool initiallyOwned, String name) : this(initiallyOwned, name, out dummyBool)
+ {
}
public Mutex(bool initiallyOwned) : this(initiallyOwned, null, out dummyBool)
@@ -181,7 +185,7 @@ namespace System.Threading
public Mutex() : this(false, null, out dummyBool)
{
}
-
+
private Mutex(SafeWaitHandle handle)
{
SetHandleInternal(handle);
@@ -190,7 +194,7 @@ namespace System.Threading
public static Mutex OpenExisting(string name)
{
- return OpenExisting(name, (MutexRights) 0);
+ return OpenExisting(name, (MutexRights)0);
}
internal enum MutexRights
@@ -206,7 +210,7 @@ namespace System.Threading
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
- throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
+ throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
__Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, name);
@@ -226,17 +230,17 @@ namespace System.Threading
{
if (name == null)
{
- throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
+ throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName);
}
- if(name.Length == 0)
+ if (name.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
}
#if !PLATFORM_UNIX
- if(System.IO.Path.MaxPath < name.Length)
+ if (System.IO.Path.MaxPath < name.Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
}
#endif
Contract.EndContractBlock();
@@ -258,11 +262,11 @@ namespace System.Threading
if (name != null && errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE)
{
// On Unix, length validation is done by CoreCLR's PAL after converting to utf-8
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Interop.Sys.MaxName), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Interop.Sys.MaxName), nameof(name));
}
#endif
- if(Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
+ if (Win32Native.ERROR_FILE_NOT_FOUND == errorCode || Win32Native.ERROR_INVALID_NAME == errorCode)
return OpenExistingResult.NameNotFound;
if (Win32Native.ERROR_PATH_NOT_FOUND == errorCode)
return OpenExistingResult.PathNotFound;
@@ -270,7 +274,7 @@ namespace System.Threading
return OpenExistingResult.NameInvalid;
// this is for passed through Win32Native Errors
- __Error.WinIOError(errorCode,name);
+ __Error.WinIOError(errorCode, name);
}
result = new Mutex(myHandle);
@@ -287,11 +291,11 @@ namespace System.Threading
}
else
{
- throw new ApplicationException(Environment.GetResourceString("Arg_SynchronizationLockException"));
+ throw new ApplicationException(SR.Arg_SynchronizationLockException);
}
}
- static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle)
+ private static int CreateMutexHandle(bool initiallyOwned, String name, Win32Native.SECURITY_ATTRIBUTES securityAttribute, out SafeWaitHandle mutexHandle)
{
int errorCode;
diff --git a/src/mscorlib/src/System/Threading/Overlapped.cs b/src/mscorlib/src/System/Threading/Overlapped.cs
index d3caff5e74..0830ee6b6c 100644
--- a/src/mscorlib/src/System/Threading/Overlapped.cs
+++ b/src/mscorlib/src/System/Threading/Overlapped.cs
@@ -24,18 +24,18 @@
=============================================================================*/
-namespace System.Threading
-{
- using System;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Runtime.ConstrainedExecution;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Collections.Concurrent;
-
+using System;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Security;
+using System.Runtime.ConstrainedExecution;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Collections.Concurrent;
+
+namespace System.Threading
+{
#region struct NativeOverlapped
// Valuetype that represents the (unmanaged) Win32 OVERLAPPED structure
@@ -45,11 +45,11 @@ namespace System.Threading
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct NativeOverlapped
{
- public IntPtr InternalLow;
- public IntPtr InternalHigh;
- public int OffsetLow;
- public int OffsetHigh;
- public IntPtr EventHandle;
+ public IntPtr InternalLow;
+ public IntPtr InternalHigh;
+ public int OffsetLow;
+ public int OffsetHigh;
+ public IntPtr EventHandle;
}
#endregion struct NativeOverlapped
@@ -59,15 +59,11 @@ namespace System.Threading
unsafe internal class _IOCompletionCallback
{
- IOCompletionCallback _ioCompletionCallback;
- ExecutionContext _executionContext;
- uint _errorCode; // Error code
- uint _numBytes; // No. of bytes transferred
- NativeOverlapped* _pOVERLAP;
-
- static _IOCompletionCallback()
- {
- }
+ private IOCompletionCallback _ioCompletionCallback;
+ private ExecutionContext _executionContext;
+ private uint _errorCode; // Error code
+ private uint _numBytes; // No. of bytes transferred
+ private NativeOverlapped* _pOVERLAP;
internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback)
{
@@ -79,12 +75,12 @@ namespace System.Threading
static internal ContextCallback _ccb = new ContextCallback(IOCompletionCallback_Context);
static internal void IOCompletionCallback_Context(Object state)
{
- _IOCompletionCallback helper = (_IOCompletionCallback)state;
- Debug.Assert(helper != null,"_IOCompletionCallback cannot be null");
+ _IOCompletionCallback helper = (_IOCompletionCallback)state;
+ Debug.Assert(helper != null, "_IOCompletionCallback cannot be null");
helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
}
-
+
// call back helper
static unsafe internal void PerformIOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
@@ -97,13 +93,13 @@ namespace System.Threading
do
{
overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
- helper = overlapped.iocbHelper;
+ helper = overlapped.iocbHelper;
if (helper == null || helper._executionContext == null || helper._executionContext == ExecutionContext.Default)
{
// We got here because of UnsafePack (or) Pack with EC flow supressed
IOCompletionCallback callback = overlapped.UserCallback;
- callback( errorCode, numBytes, pOVERLAP);
+ callback(errorCode, numBytes, pOVERLAP);
}
else
{
@@ -112,12 +108,11 @@ namespace System.Threading
helper._numBytes = numBytes;
helper._pOVERLAP = pOVERLAP;
ExecutionContext.Run(helper._executionContext, _ccb, helper);
- }
+ }
//Quickly check the VM again, to see if a packet has arrived.
OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
} while (pOVERLAP != null);
-
}
}
@@ -147,7 +142,7 @@ namespace System.Threading
internal NativeOverlapped m_nativeOverlapped;
// Adding an empty default ctor for annotation purposes
- internal OverlappedData(){}
+ internal OverlappedData() { }
internal void ReInitialize()
{
@@ -169,8 +164,9 @@ namespace System.Threading
unsafe internal NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
- if (!m_pinSelf.IsNull()) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
+ if (!m_pinSelf.IsNull())
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack);
}
if (iocb != null)
@@ -199,9 +195,10 @@ namespace System.Threading
}
unsafe internal NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
- {
- if (!m_pinSelf.IsNull()) {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_Overlapped_Pack"));
+ {
+ if (!m_pinSelf.IsNull())
+ {
+ throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack);
}
m_userObject = userData;
if (m_userObject != null)
@@ -225,7 +222,7 @@ namespace System.Threading
get { return m_nativeOverlapped.EventHandle; }
set { m_nativeOverlapped.EventHandle = value; }
}
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe private extern NativeOverlapped* AllocateNativeOverlapped();
@@ -233,7 +230,7 @@ namespace System.Threading
unsafe internal static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr);
+ unsafe internal static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern void CheckVMForIOPacket(out NativeOverlapped* pOVERLAP, out uint errorCode, out uint numBytes);
@@ -244,21 +241,20 @@ namespace System.Threading
#region class Overlapped
- /// <internalonly/>
public class Overlapped
{
private OverlappedData m_overlappedData;
- private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", ()=> new OverlappedData());
-
- public Overlapped()
+ private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", () => new OverlappedData());
+
+ public Overlapped()
{
- m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
+ m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
}
public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar)
{
- m_overlappedData = (OverlappedData) s_overlappedDataCache.Allocate();
+ m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo;
m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi;
@@ -321,7 +317,7 @@ namespace System.Threading
[CLSCompliant(false)]
unsafe public NativeOverlapped* Pack(IOCompletionCallback iocb)
{
- return Pack (iocb, null);
+ return Pack(iocb, null);
}
[CLSCompliant(false)]
@@ -334,12 +330,12 @@ namespace System.Threading
[CLSCompliant(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
{
- return UnsafePack (iocb, null);
+ return UnsafePack(iocb, null);
}
[CLSCompliant(false)]
unsafe public NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
- {
+ {
return m_overlappedData.UnsafePack(iocb, userData);
}
@@ -355,7 +351,7 @@ namespace System.Threading
Contract.EndContractBlock();
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
-
+
return overlapped;
}
@@ -373,9 +369,7 @@ namespace System.Threading
overlappedData.ReInitialize();
s_overlappedDataCache.Free(overlappedData);
}
-
}
#endregion class Overlapped
-
} // namespace
diff --git a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs b/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
deleted file mode 100644
index 32b63153c4..0000000000
--- a/src/mscorlib/src/System/Threading/ParameterizedThreadStart.cs
+++ /dev/null
@@ -1,23 +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 a Delegate which defines the start method
-** for starting a thread. That method must match this delegate.
-**
-**
-=============================================================================*/
-
-
-namespace System.Threading {
- using System.Threading;
- using System.Runtime.InteropServices;
-
- [ComVisibleAttribute(false)]
- public delegate void ParameterizedThreadStart(object obj);
-}
diff --git a/src/mscorlib/src/System/Threading/ReaderWriterLockSlim.cs b/src/mscorlib/src/System/Threading/ReaderWriterLockSlim.cs
new file mode 100644
index 0000000000..98517ad85f
--- /dev/null
+++ b/src/mscorlib/src/System/Threading/ReaderWriterLockSlim.cs
@@ -0,0 +1,1311 @@
+// 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 Internal.Runtime.Augments;
+using System.Diagnostics; // for TraceInformation
+using System.Threading;
+using System.Runtime.CompilerServices;
+
+namespace System.Threading
+{
+ public enum LockRecursionPolicy
+ {
+ NoRecursion = 0,
+ SupportsRecursion = 1,
+ }
+
+ //
+ // ReaderWriterCount tracks how many of each kind of lock is held by each thread.
+ // We keep a linked list for each thread, attached to a ThreadStatic field.
+ // These are reused wherever possible, so that a given thread will only
+ // allocate N of these, where N is the maximum number of locks held simultaneously
+ // by that thread.
+ //
+ internal class ReaderWriterCount
+ {
+ // Which lock does this object belong to? This is a numeric ID for two reasons:
+ // 1) We don't want this field to keep the lock object alive, and a WeakReference would
+ // be too expensive.
+ // 2) Setting the value of a long is faster than setting the value of a reference.
+ // The "hot" paths in ReaderWriterLockSlim are short enough that this actually
+ // matters.
+ public long lockID;
+
+ // How many reader locks does this thread hold on this ReaderWriterLockSlim instance?
+ public int readercount;
+
+ // Ditto for writer/upgrader counts. These are only used if the lock allows recursion.
+ // But we have to have the fields on every ReaderWriterCount instance, because
+ // we reuse it for different locks.
+ public int writercount;
+ public int upgradecount;
+
+ // Next RWC in this thread's list.
+ public ReaderWriterCount next;
+ }
+
+ /// <summary>
+ /// A reader-writer lock implementation that is intended to be simple, yet very
+ /// efficient. In particular only 1 interlocked operation is taken for any lock
+ /// operation (we use spin locks to achieve this). The spin lock is never held
+ /// 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).
+ /// </summary>
+ public class ReaderWriterLockSlim : IDisposable
+ {
+ //Specifying if locked can be reacquired recursively.
+ private 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
+ // the events that hang off this lock (eg writeEvent, readEvent upgradeEvent).
+ private int _myLock;
+
+ //The variables controlling spinning behavior of Mylock(which is a spin-lock)
+
+ private const int LockSpinCycles = 20;
+ private const int LockSpinCount = 10;
+ private const int LockSleep0Count = 5;
+
+ // These variables allow use to avoid Setting events (which is expensive) if we don't have to.
+ private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent
+ private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent
+ 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 int _upgradeLockOwnerId;
+ private int _writeLockOwnerId;
+
+ // conditions we wait on.
+ private EventWaitHandle _writeEvent; // threads waiting to acquire a write lock go here.
+ private EventWaitHandle _readEvent; // threads waiting to acquire a read lock go here (will be released in bulk)
+ private EventWaitHandle _upgradeEvent; // thread waiting to acquire the upgrade lock
+ private EventWaitHandle _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one)
+
+ // Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock
+ // without holding a reference to it.
+ private static long s_nextLockID;
+ private long _lockID;
+
+ // See comments on ReaderWriterCount.
+ [ThreadStatic]
+ private static ReaderWriterCount t_rwc;
+
+ private bool _fUpgradeThreadHoldingRead;
+
+ private const int MaxSpinCount = 20;
+
+ //The uint, that contains info like if the writer lock is held, num of
+ //readers etc.
+ private uint _owners;
+
+ //Various R/W masks
+ //Note:
+ //The Uint is divided as follows:
+ //
+ //Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers
+ // 31 30 29 28.......0
+ //
+ //Dividing the uint, allows to vastly simplify logic for checking if a
+ //reader should go in etc. Setting the writer bit will automatically
+ //make the value of the uint much larger than the max num of readers
+ //allowed, thus causing the check for max_readers to fail.
+
+ private const uint WRITER_HELD = 0x80000000;
+ private const uint WAITING_WRITERS = 0x40000000;
+ private const uint WAITING_UPGRADER = 0x20000000;
+
+ //The max readers is actually one less then its theoretical max.
+ //This is done in order to prevent reader count overflows. If the reader
+ //count reaches max, other readers will wait.
+ private const uint MAX_READER = 0x10000000 - 2;
+
+ private const uint READER_MASK = 0x10000000 - 1;
+
+ private bool _fDisposed;
+
+ private void InitializeThreadCounts()
+ {
+ _upgradeLockOwnerId = -1;
+ _writeLockOwnerId = -1;
+ }
+
+ public ReaderWriterLockSlim()
+ : this(LockRecursionPolicy.NoRecursion)
+ {
+ }
+
+ public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy)
+ {
+ if (recursionPolicy == LockRecursionPolicy.SupportsRecursion)
+ {
+ _fIsReentrant = true;
+ }
+ InitializeThreadCounts();
+ _fNoWaiters = true;
+ _lockID = Interlocked.Increment(ref s_nextLockID);
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
+ {
+ if (rwc.lockID == 0)
+ return true;
+ else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0)
+ return true;
+ else
+ return false;
+ }
+
+ private bool IsRwHashEntryChanged(ReaderWriterCount lrwc)
+ {
+ return lrwc.lockID != _lockID;
+ }
+
+ /// <summary>
+ /// This routine retrieves/sets the per-thread counts needed to enforce the
+ /// various rules related to acquiring the lock.
+ ///
+ /// DontAllocate is set to true if the caller just wants to get an existing
+ /// entry for this thread, but doesn't want to add one if an existing one
+ /// could not be found.
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private ReaderWriterCount GetThreadRWCount(bool dontAllocate)
+ {
+ ReaderWriterCount rwc = t_rwc;
+ ReaderWriterCount empty = null;
+ while (rwc != null)
+ {
+ if (rwc.lockID == _lockID)
+ return rwc;
+
+ if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc))
+ empty = rwc;
+
+ rwc = rwc.next;
+ }
+
+ if (dontAllocate)
+ return null;
+
+ if (empty == null)
+ {
+ empty = new ReaderWriterCount();
+ empty.next = t_rwc;
+ t_rwc = empty;
+ }
+
+ empty.lockID = _lockID;
+ return empty;
+ }
+
+ public void EnterReadLock()
+ {
+ TryEnterReadLock(-1);
+ }
+
+ //
+ // Common timeout support
+ //
+ private struct TimeoutTracker
+ {
+ private int _total;
+ private int _start;
+
+ public TimeoutTracker(TimeSpan timeout)
+ {
+ long ltm = (long)timeout.TotalMilliseconds;
+ if (ltm < -1 || ltm > (long)Int32.MaxValue)
+ throw new ArgumentOutOfRangeException(nameof(timeout));
+ _total = (int)ltm;
+ if (_total != -1 && _total != 0)
+ _start = Environment.TickCount;
+ else
+ _start = 0;
+ }
+
+ public TimeoutTracker(int millisecondsTimeout)
+ {
+ if (millisecondsTimeout < -1)
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout));
+ _total = millisecondsTimeout;
+ if (_total != -1 && _total != 0)
+ _start = Environment.TickCount;
+ else
+ _start = 0;
+ }
+
+ public int RemainingMilliseconds
+ {
+ get
+ {
+ if (_total == -1 || _total == 0)
+ return _total;
+
+ int elapsed = Environment.TickCount - _start;
+ // elapsed may be negative if TickCount has overflowed by 2^31 milliseconds.
+ if (elapsed < 0 || elapsed >= _total)
+ return 0;
+
+ return _total - elapsed;
+ }
+ }
+
+ public bool IsExpired
+ {
+ get
+ {
+ return RemainingMilliseconds == 0;
+ }
+ }
+ }
+
+ public bool TryEnterReadLock(TimeSpan timeout)
+ {
+ return TryEnterReadLock(new TimeoutTracker(timeout));
+ }
+
+ public bool TryEnterReadLock(int millisecondsTimeout)
+ {
+ return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout));
+ }
+
+ private bool TryEnterReadLock(TimeoutTracker timeout)
+ {
+ return TryEnterReadLockCore(timeout);
+ }
+
+ private bool TryEnterReadLockCore(TimeoutTracker timeout)
+ {
+ if (_fDisposed)
+ throw new ObjectDisposedException(null);
+
+ ReaderWriterCount lrwc = null;
+ int id = Environment.CurrentManagedThreadId;
+
+ if (!_fIsReentrant)
+ {
+ if (id == _writeLockOwnerId)
+ {
+ //Check for AW->AR
+ throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed);
+ }
+
+ EnterMyLock();
+
+ lrwc = GetThreadRWCount(false);
+
+ //Check if the reader lock is already acquired. Note, we could
+ //check the presence of a reader by not allocating rwc (But that
+ //would lead to two lookups in the common case. It's better to keep
+ //a count in the structure).
+ if (lrwc.readercount > 0)
+ {
+ ExitMyLock();
+ throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed);
+ }
+ else if (id == _upgradeLockOwnerId)
+ {
+ //The upgrade lock is already held.
+ //Update the global read counts and exit.
+
+ lrwc.readercount++;
+ _owners++;
+ ExitMyLock();
+ return true;
+ }
+ }
+ else
+ {
+ EnterMyLock();
+ lrwc = GetThreadRWCount(false);
+ if (lrwc.readercount > 0)
+ {
+ lrwc.readercount++;
+ ExitMyLock();
+ return true;
+ }
+ else if (id == _upgradeLockOwnerId)
+ {
+ //The upgrade lock is already held.
+ //Update the global read counts and exit.
+ lrwc.readercount++;
+ _owners++;
+ ExitMyLock();
+ _fUpgradeThreadHoldingRead = true;
+ return true;
+ }
+ else if (id == _writeLockOwnerId)
+ {
+ //The write lock is already held.
+ //Update global read counts here,
+ lrwc.readercount++;
+ _owners++;
+ ExitMyLock();
+ return true;
+ }
+ }
+
+ bool retVal = true;
+
+ int spincount = 0;
+
+ for (; ;)
+ {
+ // We can enter a read lock if there are only read-locks have been given out
+ // and a writer is not trying to get in.
+
+ if (_owners < MAX_READER)
+ {
+ // Good case, there is no contention, we are basically done
+ _owners++; // Indicate we have another reader
+ lrwc.readercount++;
+ break;
+ }
+
+ if (spincount < MaxSpinCount)
+ {
+ ExitMyLock();
+ if (timeout.IsExpired)
+ return false;
+ 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))
+ lrwc = GetThreadRWCount(false);
+ continue;
+ }
+
+ // Drat, we need to wait. Mark that we have waiters and wait.
+ if (_readEvent == null) // Create the needed event
+ {
+ LazyCreateEvent(ref _readEvent, false);
+ if (IsRwHashEntryChanged(lrwc))
+ lrwc = GetThreadRWCount(false);
+ continue; // since we left the lock, start over.
+ }
+
+ retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false);
+ if (!retVal)
+ {
+ return false;
+ }
+ if (IsRwHashEntryChanged(lrwc))
+ lrwc = GetThreadRWCount(false);
+ }
+
+ ExitMyLock();
+ return retVal;
+ }
+
+ public void EnterWriteLock()
+ {
+ TryEnterWriteLock(-1);
+ }
+
+ public bool TryEnterWriteLock(TimeSpan timeout)
+ {
+ return TryEnterWriteLock(new TimeoutTracker(timeout));
+ }
+
+ public bool TryEnterWriteLock(int millisecondsTimeout)
+ {
+ return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout));
+ }
+
+ private bool TryEnterWriteLock(TimeoutTracker timeout)
+ {
+ return TryEnterWriteLockCore(timeout);
+ }
+
+ private bool TryEnterWriteLockCore(TimeoutTracker timeout)
+ {
+ if (_fDisposed)
+ throw new ObjectDisposedException(null);
+
+ int id = Environment.CurrentManagedThreadId;
+ ReaderWriterCount lrwc;
+ bool upgradingToWrite = false;
+
+ if (!_fIsReentrant)
+ {
+ if (id == _writeLockOwnerId)
+ {
+ //Check for AW->AW
+ throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed);
+ }
+ else if (id == _upgradeLockOwnerId)
+ {
+ //AU->AW case is allowed once.
+ upgradingToWrite = true;
+ }
+
+ EnterMyLock();
+ lrwc = GetThreadRWCount(true);
+
+ //Can't acquire write lock with reader lock held.
+ if (lrwc != null && lrwc.readercount > 0)
+ {
+ ExitMyLock();
+ throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
+ }
+ }
+ else
+ {
+ EnterMyLock();
+ lrwc = GetThreadRWCount(false);
+
+ if (id == _writeLockOwnerId)
+ {
+ lrwc.writercount++;
+ ExitMyLock();
+ return true;
+ }
+ else if (id == _upgradeLockOwnerId)
+ {
+ upgradingToWrite = true;
+ }
+ else if (lrwc.readercount > 0)
+ {
+ //Write locks may not be acquired if only read locks have been
+ //acquired.
+ ExitMyLock();
+ throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed);
+ }
+ }
+
+ int spincount = 0;
+ bool retVal = true;
+
+ for (; ;)
+ {
+ if (IsWriterAcquired())
+ {
+ // Good case, there is no contention, we are basically done
+ SetWriterAcquired();
+ break;
+ }
+
+ //Check if there is just one upgrader, and no readers.
+ //Assumption: Only one thread can have the upgrade lock, so the
+ //following check will fail for all other threads that may sneak in
+ //when the upgrading thread is waiting.
+
+ if (upgradingToWrite)
+ {
+ uint readercount = GetNumReaders();
+
+ if (readercount == 1)
+ {
+ //Good case again, there is just one upgrader, and no readers.
+ SetWriterAcquired(); // indicate we have a writer.
+ break;
+ }
+ else if (readercount == 2)
+ {
+ if (lrwc != null)
+ {
+ if (IsRwHashEntryChanged(lrwc))
+ lrwc = GetThreadRWCount(false);
+
+ if (lrwc.readercount > 0)
+ {
+ //This check is needed for EU->ER->EW case, as the owner count will be two.
+ Debug.Assert(_fIsReentrant);
+ Debug.Assert(_fUpgradeThreadHoldingRead);
+
+ //Good case again, there is just one upgrader, and no readers.
+ SetWriterAcquired(); // indicate we have a writer.
+ break;
+ }
+ }
+ }
+ }
+
+ if (spincount < MaxSpinCount)
+ {
+ ExitMyLock();
+ if (timeout.IsExpired)
+ return false;
+ spincount++;
+ SpinWait(spincount);
+ EnterMyLock();
+ continue;
+ }
+
+ if (upgradingToWrite)
+ {
+ if (_waitUpgradeEvent == null) // Create the needed event
+ {
+ LazyCreateEvent(ref _waitUpgradeEvent, true);
+ continue; // since we left the lock, start over.
+ }
+
+ Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
+
+ retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true);
+
+ //The lock is not held in case of failure.
+ if (!retVal)
+ return false;
+ }
+ else
+ {
+ // Drat, we need to wait. Mark that we have waiters and wait.
+ if (_writeEvent == null) // create the needed event.
+ {
+ LazyCreateEvent(ref _writeEvent, true);
+ continue; // since we left the lock, start over.
+ }
+
+ retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true);
+ //The lock is not held in case of failure.
+ if (!retVal)
+ return false;
+ }
+ }
+
+ Debug.Assert((_owners & WRITER_HELD) > 0);
+
+ if (_fIsReentrant)
+ {
+ if (IsRwHashEntryChanged(lrwc))
+ lrwc = GetThreadRWCount(false);
+ lrwc.writercount++;
+ }
+
+ ExitMyLock();
+
+ _writeLockOwnerId = id;
+
+ return true;
+ }
+
+ public void EnterUpgradeableReadLock()
+ {
+ TryEnterUpgradeableReadLock(-1);
+ }
+
+ public bool TryEnterUpgradeableReadLock(TimeSpan timeout)
+ {
+ return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout));
+ }
+
+ public bool TryEnterUpgradeableReadLock(int millisecondsTimeout)
+ {
+ return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout));
+ }
+
+ private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout)
+ {
+ return TryEnterUpgradeableReadLockCore(timeout);
+ }
+
+ private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout)
+ {
+ if (_fDisposed)
+ throw new ObjectDisposedException(null);
+
+ int id = Environment.CurrentManagedThreadId;
+ ReaderWriterCount lrwc;
+
+ if (!_fIsReentrant)
+ {
+ if (id == _upgradeLockOwnerId)
+ {
+ //Check for AU->AU
+ throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed);
+ }
+ else if (id == _writeLockOwnerId)
+ {
+ //Check for AU->AW
+ throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed);
+ }
+
+ EnterMyLock();
+ lrwc = GetThreadRWCount(true);
+ //Can't acquire upgrade lock with reader lock held.
+ if (lrwc != null && lrwc.readercount > 0)
+ {
+ ExitMyLock();
+ throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
+ }
+ }
+ else
+ {
+ EnterMyLock();
+ lrwc = GetThreadRWCount(false);
+
+ if (id == _upgradeLockOwnerId)
+ {
+ lrwc.upgradecount++;
+ ExitMyLock();
+ return true;
+ }
+ else if (id == _writeLockOwnerId)
+ {
+ //Write lock is already held, Just update the global state
+ //to show presence of upgrader.
+ Debug.Assert((_owners & WRITER_HELD) > 0);
+ _owners++;
+ _upgradeLockOwnerId = id;
+ lrwc.upgradecount++;
+ if (lrwc.readercount > 0)
+ _fUpgradeThreadHoldingRead = true;
+ ExitMyLock();
+ return true;
+ }
+ else if (lrwc.readercount > 0)
+ {
+ //Upgrade locks may not be acquired if only read locks have been
+ //acquired.
+ ExitMyLock();
+ throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed);
+ }
+ }
+
+ bool retVal = true;
+
+ int spincount = 0;
+
+ for (; ;)
+ {
+ //Once an upgrade lock is taken, it's like having a reader lock held
+ //until upgrade or downgrade operations are performed.
+
+ if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER))
+ {
+ _owners++;
+ _upgradeLockOwnerId = id;
+ break;
+ }
+
+ if (spincount < MaxSpinCount)
+ {
+ ExitMyLock();
+ if (timeout.IsExpired)
+ return false;
+ spincount++;
+ SpinWait(spincount);
+ EnterMyLock();
+ continue;
+ }
+
+ // Drat, we need to wait. Mark that we have waiters and wait.
+ if (_upgradeEvent == null) // Create the needed event
+ {
+ LazyCreateEvent(ref _upgradeEvent, true);
+ continue; // since we left the lock, start over.
+ }
+
+ //Only one thread with the upgrade lock held can proceed.
+ retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false);
+ if (!retVal)
+ return false;
+ }
+
+ if (_fIsReentrant)
+ {
+ //The lock may have been dropped getting here, so make a quick check to see whether some other
+ //thread did not grab the entry.
+ if (IsRwHashEntryChanged(lrwc))
+ lrwc = GetThreadRWCount(false);
+ lrwc.upgradecount++;
+ }
+
+ ExitMyLock();
+
+ return true;
+ }
+
+ public void ExitReadLock()
+ {
+ ReaderWriterCount lrwc = null;
+
+ EnterMyLock();
+
+ lrwc = GetThreadRWCount(true);
+
+ if (lrwc == null || lrwc.readercount < 1)
+ {
+ //You have to be holding the read lock to make this call.
+ ExitMyLock();
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead);
+ }
+
+ if (_fIsReentrant)
+ {
+ if (lrwc.readercount > 1)
+ {
+ lrwc.readercount--;
+ ExitMyLock();
+ return;
+ }
+
+ if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
+ {
+ _fUpgradeThreadHoldingRead = false;
+ }
+ }
+
+ Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken");
+
+ --_owners;
+
+ Debug.Assert(lrwc.readercount == 1);
+ lrwc.readercount--;
+
+ ExitAndWakeUpAppropriateWaiters();
+ }
+
+ public void ExitWriteLock()
+ {
+ ReaderWriterCount lrwc;
+ if (!_fIsReentrant)
+ {
+ if (Environment.CurrentManagedThreadId != _writeLockOwnerId)
+ {
+ //You have to be holding the write lock to make this call.
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
+ }
+ EnterMyLock();
+ }
+ else
+ {
+ EnterMyLock();
+ lrwc = GetThreadRWCount(false);
+
+ if (lrwc == null)
+ {
+ ExitMyLock();
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
+ }
+
+ if (lrwc.writercount < 1)
+ {
+ ExitMyLock();
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite);
+ }
+
+ lrwc.writercount--;
+
+ if (lrwc.writercount > 0)
+ {
+ ExitMyLock();
+ return;
+ }
+ }
+
+ Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held");
+
+ ClearWriterAcquired();
+
+ _writeLockOwnerId = -1;
+
+ ExitAndWakeUpAppropriateWaiters();
+ }
+
+ public void ExitUpgradeableReadLock()
+ {
+ ReaderWriterCount lrwc;
+ if (!_fIsReentrant)
+ {
+ if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId)
+ {
+ //You have to be holding the upgrade lock to make this call.
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
+ }
+ EnterMyLock();
+ }
+ else
+ {
+ EnterMyLock();
+ lrwc = GetThreadRWCount(true);
+
+ if (lrwc == null)
+ {
+ ExitMyLock();
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
+ }
+
+ if (lrwc.upgradecount < 1)
+ {
+ ExitMyLock();
+ throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade);
+ }
+
+ lrwc.upgradecount--;
+
+ if (lrwc.upgradecount > 0)
+ {
+ ExitMyLock();
+ return;
+ }
+
+ _fUpgradeThreadHoldingRead = false;
+ }
+
+ _owners--;
+ _upgradeLockOwnerId = -1;
+
+ ExitAndWakeUpAppropriateWaiters();
+ }
+
+ /// <summary>
+ /// A routine for lazily creating a event outside the lock (so if errors
+ /// happen they are outside the lock and that we don't do much work
+ /// while holding a spin lock). If all goes well, reenter the lock and
+ /// set 'waitEvent'
+ /// </summary>
+ private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent)
+ {
+#if DEBUG
+ Debug.Assert(MyLockHeld);
+ Debug.Assert(waitEvent == null);
+#endif
+ ExitMyLock();
+ EventWaitHandle newEvent;
+ if (makeAutoResetEvent)
+ newEvent = new AutoResetEvent(false);
+ else
+ newEvent = new ManualResetEvent(false);
+ EnterMyLock();
+ if (waitEvent == null) // maybe someone snuck in.
+ waitEvent = newEvent;
+ else
+ newEvent.Dispose();
+ }
+
+ /// <summary>
+ /// Waits on 'waitEvent' with a timeout
+ /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
+ /// </summary>
+ private bool WaitOnEvent(
+ EventWaitHandle waitEvent,
+ ref uint numWaiters,
+ TimeoutTracker timeout,
+ bool isWriteWaiter)
+ {
+#if DEBUG
+ Debug.Assert(MyLockHeld);
+#endif
+ waitEvent.Reset();
+ numWaiters++;
+ _fNoWaiters = false;
+
+ //Setting these bits will prevent new readers from getting in.
+ if (_numWriteWaiters == 1)
+ SetWritersWaiting();
+ if (_numWriteUpgradeWaiters == 1)
+ SetUpgraderWaiting();
+
+ bool waitSuccessful = false;
+ ExitMyLock(); // Do the wait outside of any lock
+
+ try
+ {
+ waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds);
+ }
+ finally
+ {
+ EnterMyLock();
+ --numWaiters;
+
+ if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
+ _fNoWaiters = true;
+
+ if (_numWriteWaiters == 0)
+ ClearWritersWaiting();
+ if (_numWriteUpgradeWaiters == 0)
+ ClearUpgraderWaiting();
+
+ if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock.
+ {
+ if (isWriteWaiter)
+ {
+ // Write waiters block read waiters from acquiring the lock. Since this was the last write waiter, try
+ // to wake up the appropriate read waiters.
+ ExitAndWakeUpAppropriateReadWaiters();
+ }
+ else
+ ExitMyLock();
+ }
+ }
+ return waitSuccessful;
+ }
+
+ /// <summary>
+ /// Determines the appropriate events to set, leaves the locks, and sets the events.
+ /// </summary>
+ private void ExitAndWakeUpAppropriateWaiters()
+ {
+#if DEBUG
+ Debug.Assert(MyLockHeld);
+#endif
+ if (_fNoWaiters)
+ {
+ ExitMyLock();
+ return;
+ }
+
+ ExitAndWakeUpAppropriateWaitersPreferringWriters();
+ }
+
+ private void ExitAndWakeUpAppropriateWaitersPreferringWriters()
+ {
+ uint readercount = GetNumReaders();
+
+ //We need this case for EU->ER->EW case, as the read count will be 2 in
+ //that scenario.
+ if (_fIsReentrant)
+ {
+ if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2)
+ {
+ ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
+ _waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
+ return;
+ }
+ }
+
+ if (readercount == 1 && _numWriteUpgradeWaiters > 0)
+ {
+ //We have to be careful now, as we are dropping the lock.
+ //No new writes should be allowed to sneak in if an upgrade
+ //was pending.
+
+ ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
+ _waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one).
+ }
+ else if (readercount == 0 && _numWriteWaiters > 0)
+ {
+ ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
+ _writeEvent.Set(); // release one writer.
+ }
+ else
+ {
+ ExitAndWakeUpAppropriateReadWaiters();
+ }
+ }
+
+ private void ExitAndWakeUpAppropriateReadWaiters()
+ {
+#if DEBUG
+ Debug.Assert(MyLockHeld);
+#endif
+
+ if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters)
+ {
+ ExitMyLock();
+ return;
+ }
+
+ Debug.Assert(_numReadWaiters != 0 || _numUpgradeWaiters != 0);
+
+ bool setReadEvent = _numReadWaiters != 0;
+ bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
+
+ ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
+
+ if (setReadEvent)
+ _readEvent.Set(); // release all readers.
+
+ if (setUpgradeEvent)
+ _upgradeEvent.Set(); //release one upgrader.
+ }
+
+ private bool IsWriterAcquired()
+ {
+ return (_owners & ~WAITING_WRITERS) == 0;
+ }
+
+ private void SetWriterAcquired()
+ {
+ _owners |= WRITER_HELD; // indicate we have a writer.
+ }
+
+ private void ClearWriterAcquired()
+ {
+ _owners &= ~WRITER_HELD;
+ }
+
+ private void SetWritersWaiting()
+ {
+ _owners |= WAITING_WRITERS;
+ }
+
+ private void ClearWritersWaiting()
+ {
+ _owners &= ~WAITING_WRITERS;
+ }
+
+ private void SetUpgraderWaiting()
+ {
+ _owners |= WAITING_UPGRADER;
+ }
+
+ private void ClearUpgraderWaiting()
+ {
+ _owners &= ~WAITING_UPGRADER;
+ }
+
+ private uint GetNumReaders()
+ {
+ return _owners & READER_MASK;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private void EnterMyLock()
+ {
+ if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0)
+ EnterMyLockSpin();
+ }
+
+ private void EnterMyLockSpin()
+ {
+ int pc = Environment.ProcessorCount;
+ for (int i = 0; ; i++)
+ {
+ if (i < LockSpinCount && pc > 1)
+ {
+ RuntimeThread.SpinWait(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
+ }
+ else if (i < (LockSpinCount + LockSleep0Count))
+ {
+ RuntimeThread.Sleep(0); // Give up my quantum.
+ }
+ else
+ {
+ RuntimeThread.Sleep(1); // Give up my quantum.
+ }
+
+ if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0)
+ return;
+ }
+ }
+
+ private void ExitMyLock()
+ {
+ Debug.Assert(_myLock != 0, "Exiting spin lock that is not held");
+ Volatile.Write(ref _myLock, 0);
+ }
+
+#if DEBUG
+ private bool MyLockHeld { get { return _myLock != 0; } }
+#endif
+
+ private static void SpinWait(int SpinCount)
+ {
+ //Exponential back-off
+ if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
+ {
+ RuntimeThread.SpinWait(LockSpinCycles * SpinCount);
+ }
+ else
+ {
+ RuntimeThread.Sleep(0);
+ }
+
+ // Don't want to Sleep(1) in this spin wait:
+ // - Don't want to spin for that long, since a proper wait will follow when the spin wait fails. The artifical
+ // delay introduced by Sleep(1) will in some cases be much longer than desired.
+ // - Sleep(1) would put the thread into a wait state, and a proper wait will follow when the spin wait fails
+ // anyway, so it's preferable to put the thread into the proper wait state
+ }
+
+ public void Dispose()
+ {
+ Dispose(true);
+ }
+
+ private void Dispose(bool disposing)
+ {
+ if (disposing && !_fDisposed)
+ {
+ if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0)
+ throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
+
+ if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld)
+ throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose);
+
+ if (_writeEvent != null)
+ {
+ _writeEvent.Dispose();
+ _writeEvent = null;
+ }
+
+ if (_readEvent != null)
+ {
+ _readEvent.Dispose();
+ _readEvent = null;
+ }
+
+ if (_upgradeEvent != null)
+ {
+ _upgradeEvent.Dispose();
+ _upgradeEvent = null;
+ }
+
+ if (_waitUpgradeEvent != null)
+ {
+ _waitUpgradeEvent.Dispose();
+ _waitUpgradeEvent = null;
+ }
+
+ _fDisposed = true;
+ }
+ }
+
+ public bool IsReadLockHeld
+ {
+ get
+ {
+ if (RecursiveReadCount > 0)
+ return true;
+ else
+ return false;
+ }
+ }
+
+ public bool IsUpgradeableReadLockHeld
+ {
+ get
+ {
+ if (RecursiveUpgradeCount > 0)
+ return true;
+ else
+ return false;
+ }
+ }
+
+ public bool IsWriteLockHeld
+ {
+ get
+ {
+ if (RecursiveWriteCount > 0)
+ return true;
+ else
+ return false;
+ }
+ }
+
+ public LockRecursionPolicy RecursionPolicy
+ {
+ get
+ {
+ if (_fIsReentrant)
+ {
+ return LockRecursionPolicy.SupportsRecursion;
+ }
+ else
+ {
+ return LockRecursionPolicy.NoRecursion;
+ }
+ }
+ }
+
+ public int CurrentReadCount
+ {
+ get
+ {
+ int numreaders = (int)GetNumReaders();
+
+ if (_upgradeLockOwnerId != -1)
+ return numreaders - 1;
+ else
+ return numreaders;
+ }
+ }
+
+
+ public int RecursiveReadCount
+ {
+ get
+ {
+ int count = 0;
+ ReaderWriterCount lrwc = GetThreadRWCount(true);
+ if (lrwc != null)
+ count = lrwc.readercount;
+
+ return count;
+ }
+ }
+
+ public int RecursiveUpgradeCount
+ {
+ get
+ {
+ if (_fIsReentrant)
+ {
+ int count = 0;
+
+ ReaderWriterCount lrwc = GetThreadRWCount(true);
+ if (lrwc != null)
+ count = lrwc.upgradecount;
+
+ return count;
+ }
+ else
+ {
+ if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId)
+ return 1;
+ else
+ return 0;
+ }
+ }
+ }
+
+ public int RecursiveWriteCount
+ {
+ get
+ {
+ if (_fIsReentrant)
+ {
+ int count = 0;
+
+ ReaderWriterCount lrwc = GetThreadRWCount(true);
+ if (lrwc != null)
+ count = lrwc.writercount;
+
+ return count;
+ }
+ else
+ {
+ if (Environment.CurrentManagedThreadId == _writeLockOwnerId)
+ return 1;
+ else
+ return 0;
+ }
+ }
+ }
+
+ public int WaitingReadCount
+ {
+ get
+ {
+ return (int)_numReadWaiters;
+ }
+ }
+
+ public int WaitingUpgradeCount
+ {
+ get
+ {
+ return (int)_numUpgradeWaiters;
+ }
+ }
+
+ public int WaitingWriteCount
+ {
+ get
+ {
+ return (int)_numWriteWaiters;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Threading/Semaphore.cs b/src/mscorlib/src/System/Threading/Semaphore.cs
index 1eac4aaaeb..ae353cc3e3 100644
--- a/src/mscorlib/src/System/Threading/Semaphore.cs
+++ b/src/mscorlib/src/System/Threading/Semaphore.cs
@@ -20,17 +20,17 @@ namespace System.Threading
{
if (initialCount < 0)
{
- throw new ArgumentOutOfRangeException(nameof(initialCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (maximumCount < 1)
{
- throw new ArgumentOutOfRangeException(nameof(maximumCount), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
+ throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedPosNum);
}
if (initialCount > maximumCount)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_SemaphoreInitialMaximum"));
+ throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum);
}
SafeWaitHandle myHandle = CreateSemaphone(initialCount, maximumCount, name);
@@ -41,7 +41,7 @@ namespace System.Threading
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(
- Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
+ SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
__Error.WinIOError();
}
@@ -52,17 +52,17 @@ namespace System.Threading
{
if (initialCount < 0)
{
- throw new ArgumentOutOfRangeException(nameof(initialCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(initialCount), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (maximumCount < 1)
{
- throw new ArgumentOutOfRangeException(nameof(maximumCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maximumCount), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (initialCount > maximumCount)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_SemaphoreInitialMaximum"));
+ throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum);
}
SafeWaitHandle myHandle = CreateSemaphone(initialCount, maximumCount, name);
@@ -72,7 +72,7 @@ namespace System.Threading
{
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(
- Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
+ SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
__Error.WinIOError();
}
createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
@@ -89,10 +89,10 @@ namespace System.Threading
if (name != null)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (name.Length > Path.MaxPath)
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
#endif
}
@@ -111,7 +111,7 @@ namespace System.Threading
case OpenExistingResult.NameNotFound:
throw new WaitHandleCannotBeOpenedException();
case OpenExistingResult.NameInvalid:
- throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", name));
+ throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
throw new IOException(Win32Native.GetMessage(Win32Native.ERROR_PATH_NOT_FOUND));
default:
@@ -127,14 +127,14 @@ namespace System.Threading
private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
+ throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#else
if (name == null)
- throw new ArgumentNullException(nameof(name), Environment.GetResourceString("ArgumentNull_WithParamName"));
+ throw new ArgumentNullException(nameof(name), SR.ArgumentNull_WithParamName);
if (name.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(name));
+ throw new ArgumentException(SR.Argument_EmptyName, nameof(name));
if (name.Length > Path.MaxPath)
- throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), nameof(name));
+ throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
const int SYNCHRONIZE = 0x00100000;
const int SEMAPHORE_MODIFY_STATE = 0x00000002;
@@ -173,7 +173,7 @@ namespace System.Threading
{
if (releaseCount < 1)
{
- throw new ArgumentOutOfRangeException(nameof(releaseCount), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(releaseCount), SR.ArgumentOutOfRange_NeedNonNegNum);
}
//If ReleaseSempahore returns false when the specified value would cause
diff --git a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs b/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
deleted file mode 100644
index 01c5040b7e..0000000000
--- a/src/mscorlib/src/System/Threading/SemaphoreFullException.cs
+++ /dev/null
@@ -1,27 +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.
-
-namespace System.Threading {
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
-
- [Serializable]
- [ComVisibleAttribute(false)]
- public class SemaphoreFullException : SystemException {
-
- public SemaphoreFullException() : base(Environment.GetResourceString("Threading_SemaphoreFullException")){
- }
-
- public SemaphoreFullException(String message) : base(message) {
- }
-
- public SemaphoreFullException(String message, Exception innerException) : base(message, innerException) {
- }
-
- protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
index c3b43d9585..97bbae18cc 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.
@@ -21,6 +21,7 @@ using System.Diagnostics.Contracts;
using System.Threading.Tasks;
// The class will be part of the current System.Threading namespace
+
namespace System.Threading
{
/// <summary>
@@ -84,7 +85,7 @@ namespace System.Threading
private sealed class TaskNode : Task<bool>, IThreadPoolWorkItem
{
internal TaskNode Prev, Next;
- internal TaskNode() : base() {}
+ internal TaskNode() : base() { }
void IThreadPoolWorkItem.ExecuteWorkItem()
{
@@ -177,13 +178,13 @@ namespace System.Threading
if (initialCount < 0 || initialCount > maxCount)
{
throw new ArgumentOutOfRangeException(
- nameof(initialCount), initialCount, GetResourceString("SemaphoreSlim_ctor_InitialCountWrong"));
+ nameof(initialCount), initialCount, SR.SemaphoreSlim_ctor_InitialCountWrong);
}
//validate input
if (maxCount <= 0)
{
- throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, GetResourceString("SemaphoreSlim_ctor_MaxCountWrong"));
+ throw new ArgumentOutOfRangeException(nameof(maxCount), maxCount, SR.SemaphoreSlim_ctor_MaxCountWrong);
}
m_maxCount = maxCount;
@@ -240,7 +241,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- nameof(timeout), timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong);
}
// Call wait with the timeout milliseconds
@@ -270,7 +271,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- nameof(timeout), timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong);
}
// Call wait with the timeout milliseconds
@@ -313,7 +314,7 @@ namespace System.Threading
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
- nameof(millisecondsTimeout), millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(millisecondsTimeout), millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong);
}
cancellationToken.ThrowIfCancellationRequested();
@@ -370,7 +371,7 @@ namespace System.Threading
Debug.Assert(m_asyncTail != null, "tail should not be null if head isn't");
asyncWaitTask = WaitAsync(millisecondsTimeout, cancellationToken);
}
- // There are no async waiters, so we can proceed with normal synchronous waiting.
+ // There are no async waiters, so we can proceed with normal synchronous waiting.
else
{
// If the count > 0 we are good to move on.
@@ -399,7 +400,7 @@ namespace System.Threading
// defer to synchronous waiters in priority, which means that if it's possible an asynchronous
// waiter didn't get released because a synchronous waiter was present, we need to ensure
// that synchronous waiter succeeds so that they have a chance to release.
- Debug.Assert(!waitSuccessful || m_currentCount > 0,
+ Debug.Assert(!waitSuccessful || m_currentCount > 0,
"If the wait was successful, there should be count available.");
if (m_currentCount > 0)
{
@@ -574,7 +575,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- nameof(timeout), timeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(timeout), timeout, SR.SemaphoreSlim_Wait_TimeoutWrong);
}
// Call wait with the timeout milliseconds
@@ -607,7 +608,7 @@ namespace System.Threading
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
- nameof(millisecondsTimeout), millisecondsTimeout, GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"));
+ nameof(millisecondsTimeout), millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong);
}
// Bail early for cancellation
@@ -628,9 +629,9 @@ namespace System.Threading
// No counts, if timeout is zero fail fast
return s_falseTask;
}
- // If there aren't, create and return a task to the caller.
- // The task will be completed either when they've successfully acquired
- // the semaphore or when the timeout expired or cancellation was requested.
+ // If there aren't, create and return a task to the caller.
+ // The task will be completed either when they've successfully acquired
+ // the semaphore or when the timeout expired or cancellation was requested.
else
{
Debug.Assert(m_currentCount == 0, "m_currentCount should never be negative");
@@ -771,7 +772,7 @@ namespace System.Threading
if (releaseCount < 1)
{
throw new ArgumentOutOfRangeException(
- nameof(releaseCount), releaseCount, GetResourceString("SemaphoreSlim_Release_CountWrong"));
+ nameof(releaseCount), releaseCount, SR.SemaphoreSlim_Release_CountWrong);
}
int returnCount;
@@ -882,7 +883,7 @@ namespace System.Threading
}
-
+
/// <summary>
/// Private helper method to wake up waiters when a cancellationToken gets canceled.
/// </summary>
@@ -905,7 +906,7 @@ namespace System.Threading
{
if (m_lockObj == null)
{
- throw new ObjectDisposedException(null, GetResourceString("SemaphoreSlim_Disposed"));
+ throw new ObjectDisposedException(null, SR.SemaphoreSlim_Disposed);
}
}
@@ -915,7 +916,7 @@ namespace System.Threading
/// <param name="str">The key string</param>
private static string GetResourceString(string str)
{
- return Environment.GetResourceString(str);
+ return SR.GetResourceString(str);
}
#endregion
}
diff --git a/src/mscorlib/src/System/Threading/SendOrPostCallback.cs b/src/mscorlib/src/System/Threading/SendOrPostCallback.cs
deleted file mode 100644
index b81d2bff64..0000000000
--- a/src/mscorlib/src/System/Threading/SendOrPostCallback.cs
+++ /dev/null
@@ -1,16 +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: Represents a method to be called when a message is to be dispatched to a synchronization context.
-**
-**
-===========================================================*/
-
-namespace System.Threading
-{
- public delegate void SendOrPostCallback(Object state);
-}
diff --git a/src/mscorlib/src/System/Threading/SpinWait.cs b/src/mscorlib/src/System/Threading/SpinWait.cs
index 8431f6564f..30d7aa679c 100644
--- a/src/mscorlib/src/System/Threading/SpinWait.cs
+++ b/src/mscorlib/src/System/Threading/SpinWait.cs
@@ -51,7 +51,7 @@ namespace System.Threading
/// <remarks>
/// <para>
/// <see cref="SpinWait"/> encapsulates common spinning logic. On single-processor machines, yields are
- /// always used instead of busy waits, and on computers with Intel™ processors employing Hyper-Threading™
+ /// always used instead of busy waits, and on computers with Intel processors employing Hyper-Threading
/// technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of
/// spinning and true yielding.
/// </para>
@@ -71,7 +71,6 @@ namespace System.Threading
/// </remarks>
public struct SpinWait
{
-
// These constants determine the frequency of yields versus spinning. The
// 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
@@ -188,7 +187,7 @@ namespace System.Threading
public static void SpinUntil(Func<bool> condition)
{
#if DEBUG
- bool result =
+ bool result =
#endif
SpinUntil(condition, Timeout.Infinite);
#if DEBUG
@@ -215,7 +214,7 @@ namespace System.Threading
if (totalMilliseconds < -1 || totalMilliseconds > Int32.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
- nameof(timeout), timeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong"));
+ nameof(timeout), timeout, SR.SpinWait_SpinUntil_TimeoutWrong);
}
// Call wait with the timeout milliseconds
@@ -237,11 +236,11 @@ namespace System.Threading
if (millisecondsTimeout < Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(
- nameof(millisecondsTimeout), millisecondsTimeout, Environment.GetResourceString("SpinWait_SpinUntil_TimeoutWrong"));
+ nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong);
}
if (condition == null)
{
- throw new ArgumentNullException(nameof(condition), Environment.GetResourceString("SpinWait_SpinUntil_ArgumentNull"));
+ throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull);
}
uint startTime = 0;
if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite)
@@ -267,7 +266,6 @@ namespace System.Threading
}
}
return true;
-
}
#endregion
@@ -314,51 +312,4 @@ namespace System.Threading
get { return ProcessorCount == 1; }
}
}
-
- /// <summary>
- /// A helper class to capture a start time using Environment.TickCout as a time in milliseconds, also updates a given timeout bu subtracting the current time from
- /// the start time
- /// </summary>
- 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
- /// 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>
- public static uint GetTime()
- {
- return (uint)Environment.TickCount;
- }
-
- /// <summary>
- /// 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>
- /// <returns>The new wait time in milliseconds, -1 if the time expired</returns>
- public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
- {
- // The function must be called in case the time out is not infinite
- Debug.Assert(originalWaitMillisecondsTimeout != Timeout.Infinite);
-
- uint elapsedMilliseconds = (GetTime() - startTime);
-
- // Check the elapsed milliseconds is greater than max int because this property is uint
- if (elapsedMilliseconds > int.MaxValue)
- {
- return 0;
- }
-
- // Subtract the elapsed time from the current wait time
- int currentWaitTimeout = originalWaitMillisecondsTimeout - (int)elapsedMilliseconds; ;
- if (currentWaitTimeout <= 0)
- {
- return 0;
- }
-
- return currentWaitTimeout;
- }
- }
-
}
diff --git a/src/mscorlib/src/System/Threading/SynchronizationContext.cs b/src/mscorlib/src/System/Threading/SynchronizationContext.cs
index f4b3c79409..676a198ee7 100644
--- a/src/mscorlib/src/System/Threading/SynchronizationContext.cs
+++ b/src/mscorlib/src/System/Threading/SynchronizationContext.cs
@@ -11,7 +11,7 @@
===========================================================*/
namespace System.Threading
-{
+{
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
@@ -27,7 +27,7 @@ namespace System.Threading
[Flags]
- enum SynchronizationContextProperties
+ internal enum SynchronizationContextProperties
{
None = 0,
RequireWaitNotification = 0x1
@@ -41,27 +41,27 @@ namespace System.Threading
[FriendAccessAllowed]
internal class WinRTSynchronizationContextFactoryBase
{
- public virtual SynchronizationContext Create(object coreDispatcher) {return null;}
+ public virtual SynchronizationContext Create(object coreDispatcher) { return null; }
}
#endif //FEATURE_COMINTEROP
public class SynchronizationContext
{
- SynchronizationContextProperties _props = SynchronizationContextProperties.None;
-
+ private SynchronizationContextProperties _props = SynchronizationContextProperties.None;
+
public SynchronizationContext()
{
}
-
+
// helper delegate to statically bind to Wait method
private delegate int WaitDelegate(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout);
- static Type s_cachedPreparedType1;
- static Type s_cachedPreparedType2;
- static Type s_cachedPreparedType3;
- static Type s_cachedPreparedType4;
- static Type s_cachedPreparedType5;
+ private static Type s_cachedPreparedType1;
+ private static Type s_cachedPreparedType2;
+ private static Type s_cachedPreparedType3;
+ private static Type s_cachedPreparedType4;
+ private static Type s_cachedPreparedType5;
// protected so that only the derived sync context class can enable these flags
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "We never dereference s_cachedPreparedType*, so ordering is unimportant")]
@@ -87,11 +87,11 @@ namespace System.Threading
{
RuntimeHelpers.PrepareDelegate(new WaitDelegate(this.Wait));
- if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type;
- else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type;
- else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type;
- else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type;
- else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type;
+ if (s_cachedPreparedType1 == null) s_cachedPreparedType1 = type;
+ else if (s_cachedPreparedType2 == null) s_cachedPreparedType2 = type;
+ else if (s_cachedPreparedType3 == null) s_cachedPreparedType3 = type;
+ else if (s_cachedPreparedType4 == null) s_cachedPreparedType4 = type;
+ else if (s_cachedPreparedType5 == null) s_cachedPreparedType5 = type;
}
_props |= SynchronizationContextProperties.RequireWaitNotification;
@@ -99,10 +99,10 @@ namespace System.Threading
public bool IsWaitNotificationRequired()
{
- return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0);
+ return ((_props & SynchronizationContextProperties.RequireWaitNotification) != 0);
}
-
+
public virtual void Send(SendOrPostCallback d, Object state)
{
d(state);
@@ -113,7 +113,7 @@ namespace System.Threading
ThreadPool.QueueUserWorkItem(new WaitCallback(d), state);
}
-
+
/// <summary>
/// Optional override for subclasses, for responding to notification that operation is starting.
/// </summary>
@@ -159,9 +159,9 @@ namespace System.Threading
Thread.CurrentThread.SynchronizationContext = syncContext;
}
- public static SynchronizationContext Current
+ public static SynchronizationContext Current
{
- get
+ get
{
SynchronizationContext context = Thread.CurrentThread.SynchronizationContext;
@@ -189,7 +189,7 @@ namespace System.Threading
{
Debug.Assert(Environment.IsWinRTSupported);
Debug.Assert(AppDomain.IsAppXModel());
-
+
//
// We call into the VM to get the dispatcher. This is because:
//
@@ -207,7 +207,7 @@ namespace System.Threading
return null;
}
- static WinRTSynchronizationContextFactoryBase s_winRTContextFactory;
+ private static WinRTSynchronizationContextFactoryBase s_winRTContextFactory;
private static WinRTSynchronizationContextFactoryBase GetWinRTSynchronizationContextFactory()
{
diff --git a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs b/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
deleted file mode 100644
index de42c1f232..0000000000
--- a/src/mscorlib/src/System/Threading/SynchronizationLockException.cs
+++ /dev/null
@@ -1,43 +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: Wait(), Notify() or NotifyAll() was called from an unsynchronized
-** block of code.
-**
-**
-=============================================================================*/
-
-namespace System.Threading {
-
- using System;
- using System.Runtime.Serialization;
- [Serializable]
- public class SynchronizationLockException : SystemException {
- public SynchronizationLockException()
- : base(Environment.GetResourceString("Arg_SynchronizationLockException")) {
- SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK);
- }
-
- public SynchronizationLockException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK);
- }
-
- public SynchronizationLockException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_SYNCHRONIZATIONLOCK);
- }
-
- protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-
-}
-
-
diff --git a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
index ec7c5aaeea..ec154f9efb 100644
--- a/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/AsyncCausalityTracer.cs
@@ -21,7 +21,6 @@ using WFD = Windows.Foundation.Diagnostics;
namespace System.Threading.Tasks
{
-
[FriendAccessAllowed]
internal enum CausalityTraceLevel
{
@@ -85,13 +84,13 @@ namespace System.Threading.Tasks
[FriendAccessAllowed]
internal static class AsyncCausalityTracer
{
- static internal void EnableToETW(bool enabled)
+ static internal void EnableToETW(bool enabled)
{
#if FEATURE_COMINTEROP
if (enabled)
- f_LoggingOn |= Loggers.ETW;
- else
- f_LoggingOn &= ~Loggers.ETW;
+ f_LoggingOn |= Loggers.ETW;
+ else
+ f_LoggingOn &= ~Loggers.ETW;
#endif
}
@@ -121,7 +120,8 @@ namespace System.Threading.Tasks
// The loggers that this Tracer knows about.
[Flags]
- private enum Loggers : byte {
+ private enum Loggers : byte
+ {
CausalityTracer = 1,
ETW = 2
}
@@ -148,7 +148,7 @@ namespace System.Threading.Tasks
int hresult = Microsoft.Win32.UnsafeNativeMethods.RoGetActivationFactory(ClassId, ref guid, out factory);
if (hresult < 0 || factory == null) return; //This prevents having an exception thrown in case IAsyncCausalityTracerStatics isn't registered.
-
+
s_TracerFactory = (WFD.IAsyncCausalityTracerStatics)factory;
EventRegistrationToken token = s_TracerFactory.add_TracingStatusChanged(new EventHandler<WFD.TracingStatusChangedEventArgs>(TracingStatusChangedHandler));
@@ -161,15 +161,14 @@ namespace System.Threading.Tasks
// doing here depends on internal state.
LogAndDisable(ex);
}
-
}
private static void TracingStatusChangedHandler(Object sender, WFD.TracingStatusChangedEventArgs args)
{
if (args.Enabled)
- f_LoggingOn |= Loggers.CausalityTracer;
- else
- f_LoggingOn &= ~Loggers.CausalityTracer;
+ f_LoggingOn |= Loggers.CausalityTracer;
+ else
+ f_LoggingOn &= ~Loggers.CausalityTracer;
}
#endif
@@ -185,11 +184,11 @@ namespace System.Threading.Tasks
try
{
if ((f_LoggingOn & Loggers.ETW) != 0)
- TplEtwProvider.Log.TraceOperationBegin(taskId, operationName, (long) relatedContext);
+ TplEtwProvider.Log.TraceOperationBegin(taskId, operationName, (long)relatedContext);
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationCreation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), operationName, relatedContext);
}
- catch(Exception ex)
+ catch (Exception ex)
{
//view function comment
LogAndDisable(ex);
@@ -209,7 +208,7 @@ namespace System.Threading.Tasks
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.AsyncCausalityStatus)status);
}
- catch(Exception ex)
+ catch (Exception ex)
{
//view function comment
LogAndDisable(ex);
@@ -228,7 +227,7 @@ namespace System.Threading.Tasks
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceOperationRelation((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalityRelation)relation);
}
- catch(Exception ex)
+ catch (Exception ex)
{
//view function comment
LogAndDisable(ex);
@@ -247,7 +246,7 @@ namespace System.Threading.Tasks
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceSynchronousWorkStart((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, s_PlatformId, GetOperationId((uint)taskId), (WFD.CausalitySynchronousWork)work);
}
- catch(Exception ex)
+ catch (Exception ex)
{
//view function comment
LogAndDisable(ex);
@@ -266,7 +265,7 @@ namespace System.Threading.Tasks
if ((f_LoggingOn & Loggers.CausalityTracer) != 0)
s_TracerFactory.TraceSynchronousWorkCompletion((WFD.CausalityTraceLevel)traceLevel, s_CausalitySource, (WFD.CausalitySynchronousWork)work);
}
- catch(Exception ex)
+ catch (Exception ex)
{
//view function comment
LogAndDisable(ex);
@@ -288,6 +287,5 @@ namespace System.Threading.Tasks
{
return (((ulong)AppDomain.CurrentDomain.Id) << 32) + taskId;
}
-
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
index a87406a493..07a673bf4e 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
@@ -72,22 +72,25 @@ namespace System.Threading.Tasks
/// Initializes the ConcurrentExclusiveSchedulerPair.
/// </summary>
public ConcurrentExclusiveSchedulerPair() :
- this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { }
+ this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK)
+ { }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler.
/// </summary>
/// <param name="taskScheduler">The target scheduler on which this pair should execute.</param>
public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) :
- this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { }
+ this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK)
+ { }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level.
/// </summary>
/// <param name="taskScheduler">The target scheduler on which this pair should execute.</param>
/// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param>
- public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) :
- this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { }
+ public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) :
+ this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK)
+ { }
/// <summary>
/// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum
@@ -141,7 +144,7 @@ namespace System.Threading.Tasks
}
/// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary>
- public Task Completion
+ public Task Completion
{
// ValueLock not needed, but it's ok if it's held
get { return EnsureCompletionStateInitialized().Task; }
@@ -162,7 +165,7 @@ namespace System.Threading.Tasks
}
/// <summary>Sets that completion has been requested.</summary>
- private void RequestCompletion()
+ private void RequestCompletion()
{
ContractAssertMonitorStatus(ValueLock, held: true);
EnsureCompletionStateInitialized().m_completionRequested = true;
@@ -190,9 +193,9 @@ namespace System.Threading.Tasks
// Now, only allow shutdown if an exception occurred or if there are no more tasks to process.
var cs = EnsureCompletionStateInitialized();
- return
+ return
(cs.m_exceptions != null && cs.m_exceptions.Count > 0) ||
- (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty);
+ (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty);
}
}
@@ -330,7 +333,7 @@ namespace System.Threading.Tasks
}
}
}
-
+
// Check to see if all tasks have completed and if completion has been requested.
CleanupStateIfCompletingAndQuiesced();
}
@@ -370,7 +373,7 @@ namespace System.Threading.Tasks
// We're no longer processing exclusive tasks on the current thread
ProcessingMode currentMode;
m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode);
- Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
+ Debug.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask,
"Somehow we ended up escaping exclusive mode.");
lock (ValueLock)
@@ -720,7 +723,7 @@ namespace System.Threading.Tasks
return mode;
}
}
-
+
/// <summary>Asserts that a given synchronization object is either held or not held.</summary>
/// <param name="syncObj">The monitor to check.</param>
/// <param name="held">Whether we want to assert that it's currently held or not held.</param>
@@ -748,7 +751,7 @@ namespace System.Threading.Tasks
Debug.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed.");
#endif
}
-
+
/// <summary>Gets the options to use for tasks.</summary>
/// <param name="isReplacementReplica">If this task is being created to replace another.</param>
/// <remarks>
@@ -758,7 +761,7 @@ namespace System.Threading.Tasks
/// <returns>The options to use.</returns>
internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false)
{
- TaskCreationOptions options =
+ TaskCreationOptions options =
#if PRENET45
TaskCreationOptions.None;
#else
@@ -784,5 +787,4 @@ namespace System.Threading.Tasks
Completed = 0x8
}
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
index 137afa11f5..60a7c81dcf 100644
--- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
@@ -568,8 +568,6 @@ namespace System.Threading.Tasks
promise.DangerousSetResult(result);
}
}
-
-
}
}
@@ -691,7 +689,7 @@ namespace System.Threading.Tasks
// RespectParentCancellation.
Task t = new Task(new Action<object>(delegate
{
- FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization:true);
+ FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: true);
}),
(object)null, null,
default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null);
@@ -706,7 +704,7 @@ namespace System.Threading.Tasks
if (asyncResult.IsCompleted)
{
- try { t.InternalRunSynchronously(scheduler, waitForCompletion:false); }
+ try { t.InternalRunSynchronously(scheduler, waitForCompletion: false); }
catch (Exception e) { promise.TrySetException(e); } // catch and log any scheduler exceptions
}
else
@@ -792,7 +790,7 @@ namespace System.Threading.Tasks
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod);
Contract.Requires((endFunction != null) != (endAction != null), "Both endFunction and endAction were non-null");
-
+
TaskFactory.CheckFromAsyncOptions(creationOptions, true);
Task<TResult> promise = new Task<TResult>(state, creationOptions);
@@ -943,7 +941,6 @@ namespace System.Threading.Tasks
}
catch
{
-
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCompletion(CausalityTraceLevel.Required, promise.Id, AsyncCausalityStatus.Error);
@@ -1241,7 +1238,7 @@ namespace System.Threading.Tasks
internal static Task<TResult> FromAsyncTrim<TInstance, TArgs>(
TInstance thisRef, TArgs args,
Func<TInstance, TArgs, AsyncCallback, object, IAsyncResult> beginMethod,
- Func<TInstance, IAsyncResult, TResult> endMethod)
+ Func<TInstance, IAsyncResult, TResult> endMethod)
where TInstance : class
{
// Validate arguments, but only with asserts, as this is an internal only implementation.
@@ -1319,7 +1316,7 @@ namespace System.Threading.Tasks
// we'll instead complete the promise at the call site.
if (!asyncResult.CompletedSynchronously)
{
- promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization:true);
+ promise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: true);
}
}
@@ -1661,7 +1658,7 @@ namespace System.Threading.Tasks
return ContinueWhenAllImpl<TAntecedentResult>(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler);
}
-
+
// Core implementation of ContinueWhenAll -- the generic version
// Note: if you make any changes to this method, please do the same to the non-generic version too.
internal static Task<TResult> ContinueWhenAllImpl<TAntecedentResult>(Task<TAntecedentResult>[] tasks,
@@ -1744,10 +1741,10 @@ namespace System.Threading.Tasks
//the following delegate avoids closure capture as much as possible
//completedTasks.Result == tasksCopy;
//state == continuationFunction
- (completedTasks, state) =>
+ (completedTasks, state) =>
{
completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
- return ((Func<Task[], TResult>)state)(completedTasks.Result);
+ return ((Func<Task[], TResult>)state)(completedTasks.Result);
},
continuationFunction, scheduler, cancellationToken, continuationOptions);
}
@@ -1755,13 +1752,13 @@ namespace System.Threading.Tasks
{
Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
- //the following delegate avoids closure capture as much as possible
- //completedTasks.Result == tasksCopy;
- //state == continuationAction
- (completedTasks, state) =>
+ //the following delegate avoids closure capture as much as possible
+ //completedTasks.Result == tasksCopy;
+ //state == continuationAction
+ (completedTasks, state) =>
{
completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary();
- ((Action<Task[]>)state)(completedTasks.Result); return default(TResult);
+ ((Action<Task[]>)state)(completedTasks.Result); return default(TResult);
},
continuationAction, scheduler, cancellationToken, continuationOptions);
}
@@ -2054,7 +2051,7 @@ namespace System.Threading.Tasks
// check arguments
TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions);
if (tasks == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks);
- if(tasks.Length == 0) ThrowHelper.ThrowArgumentException( ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks);
+ if (tasks.Length == 0) ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks);
//ArgumentNullException of continuationFunction or continuationAction is checked by the caller
Contract.Requires((continuationFunction != null) != (continuationAction != null), "Expected exactly one of endFunction/endAction to be non-null");
@@ -2076,8 +2073,8 @@ namespace System.Threading.Tasks
if (continuationFunction != null)
{
return starter.ContinueWith(
- //the following delegate avoids closure capture as much as possible
- //completedTask.Result is the winning task; state == continuationAction
+ //the following delegate avoids closure capture as much as possible
+ //completedTask.Result is the winning task; state == continuationAction
(completedTask, state) => { return ((Func<Task, TResult>)state)(completedTask.Result); },
continuationFunction, scheduler, cancellationToken, continuationOptions);
}
@@ -2132,7 +2129,7 @@ namespace System.Threading.Tasks
Debug.Assert(continuationAction != null);
return starter.ContinueWith<TResult>(
// Use a cached delegate
- GenericDelegateCache<TAntecedentResult,TResult>.CWAnyActionDelegate,
+ GenericDelegateCache<TAntecedentResult, TResult>.CWAnyActionDelegate,
continuationAction, scheduler, cancellationToken, continuationOptions);
}
}
@@ -2180,7 +2177,5 @@ namespace System.Threading.Tasks
action(wrappedAntecedents.Result);
return default(TResult);
};
-
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs b/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs
index 32efd771a0..17dd1f8bde 100644
--- a/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/IAsyncCausalityTracerStatics.cs
@@ -13,6 +13,7 @@ using System.Runtime.InteropServices.WindowsRuntime;
// Windows.Foundation.Diagnostics cannot be referenced from managed code because
// they're hidden by the metadata adapter. We redeclare the interfaces manually
// to be able to talk to native WinRT objects.
+
namespace Windows.Foundation.Diagnostics
{
[ComImport]
@@ -47,16 +48,16 @@ namespace Windows.Foundation.Diagnostics
[WindowsRuntimeImport]
internal sealed class TracingStatusChangedEventArgs : ITracingStatusChangedEventArgs
{
- public extern bool Enabled
+ public extern bool Enabled
{
[MethodImpl(MethodImplOptions.InternalCall)]
get;
}
-
- public extern CausalityTraceLevel TraceLevel
+
+ public extern CausalityTraceLevel TraceLevel
{
[MethodImpl(MethodImplOptions.InternalCall)]
- get;
+ get;
}
}
@@ -97,5 +98,4 @@ namespace Windows.Foundation.Diagnostics
Error = 3,
Started = 0
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
index 545bf9a5e5..f9d5f89398 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
@@ -182,7 +182,8 @@ namespace System.Threading.Tasks
newSegment.m_state.m_last = 1;
newSegment.m_state.m_lastCopy = 1;
- try { } finally
+ try { }
+ finally
{
// Finally block to protect against corruption due to a thread abort
// between setting m_next and setting m_tail.
@@ -271,8 +272,8 @@ namespace System.Threading.Tasks
{
for (Segment segment = m_head; segment != null; segment = segment.m_next)
{
- for (int pt = segment.m_state.m_first;
- pt != segment.m_state.m_last;
+ for (int pt = segment.m_state.m_first;
+ pt != segment.m_state.m_last;
pt = (pt + 1) & (segment.m_array.Length - 1))
{
yield return segment.m_array[pt];
@@ -307,7 +308,7 @@ namespace System.Threading.Tasks
}
/// <summary>A segment in the queue containing one or more items.</summary>
- [StructLayout(LayoutKind.Sequential)]
+ [StructLayout(LayoutKind.Sequential)]
private sealed class Segment
{
/// <summary>The next segment in the linked list of segments.</summary>
@@ -367,7 +368,7 @@ namespace System.Threading.Tasks
}
/// <summary>A placeholder class for common padding constants and eventually routines.</summary>
- static class PaddingHelpers
+ 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;
@@ -375,8 +376,7 @@ namespace System.Threading.Tasks
/// <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
- struct PaddingFor32
+ internal struct PaddingFor32
{
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
index 12cc1daa63..33bf792370 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
@@ -16,21 +16,21 @@ using System.Text;
using System.Security;
using System.Runtime.CompilerServices;
+using System.Diagnostics.Tracing;
+
namespace System.Threading.Tasks
{
- using System.Diagnostics.Tracing;
-
/// <summary>Provides an event source for tracing TPL information.</summary>
[EventSource(
Name = "System.Threading.Tasks.TplEventSource",
- Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5",
- LocalizationResources = System.CoreLib.Name)]
+ Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5",
+ LocalizationResources = "FxResources.System.Private.CoreLib.SR")]
internal sealed class TplEtwProvider : EventSource
{
/// Used to determine if tasks should generate Activity IDs for themselves
internal bool TasksSetActivityIds; // This keyword is set
internal bool Debug;
- private bool DebugActivityId;
+ private bool DebugActivityId;
/// <summary>
/// Get callbacks when the ETW sends us commands`
@@ -42,11 +42,11 @@ namespace System.Threading.Tasks
AsyncCausalityTracer.EnableToETW(true);
else if (command.Command == EventCommand.Disable)
AsyncCausalityTracer.EnableToETW(false);
-
- if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds))
+
+ if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds))
ActivityTracker.Instance.Enable();
- else
- TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds);
+ else
+ TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds);
Debug = IsEnabled(EventLevel.Informational, Keywords.Debug);
DebugActivityId = IsEnabled(EventLevel.Informational, Keywords.DebugActivityId);
@@ -99,49 +99,49 @@ namespace System.Threading.Tasks
/// This sets activity IDS and logs when tasks are schedules (or waits begin)
/// But are otherwise silent
/// </summary>
- public const EventKeywords TaskTransfer = (EventKeywords) 1;
+ public const EventKeywords TaskTransfer = (EventKeywords)1;
/// <summary>
/// TaskTranser events plus events when tasks start and stop
/// </summary>
- public const EventKeywords Tasks = (EventKeywords) 2;
+ public const EventKeywords Tasks = (EventKeywords)2;
/// <summary>
/// Events associted with the higher level parallel APIs
/// </summary>
- public const EventKeywords Parallel = (EventKeywords) 4;
+ public const EventKeywords Parallel = (EventKeywords)4;
/// <summary>
/// These are relatively verbose events that effectively just redirect
/// the windows AsyncCausalityTracer to ETW
/// </summary>
- public const EventKeywords AsyncCausalityOperation = (EventKeywords) 8;
- public const EventKeywords AsyncCausalityRelation = (EventKeywords) 0x10;
- public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords) 0x20;
+ public const EventKeywords AsyncCausalityOperation = (EventKeywords)8;
+ public const EventKeywords AsyncCausalityRelation = (EventKeywords)0x10;
+ public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords)0x20;
/// <summary>
/// Emit the stops as well as the schedule/start events
/// </summary>
- public const EventKeywords TaskStops = (EventKeywords) 0x40;
+ public const EventKeywords TaskStops = (EventKeywords)0x40;
/// <summary>
/// TasksFlowActivityIds indicate that activity ID flow from one task
/// to any task created by it.
/// </summary>
- public const EventKeywords TasksFlowActivityIds = (EventKeywords) 0x80;
+ public const EventKeywords TasksFlowActivityIds = (EventKeywords)0x80;
/// <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
/// </summary>
- public const EventKeywords TasksSetActivityIds = (EventKeywords) 0x10000;
+ public const EventKeywords TasksSetActivityIds = (EventKeywords)0x10000;
/// <summary>
/// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future
/// </summary>
- public const EventKeywords Debug = (EventKeywords) 0x20000;
+ public const EventKeywords Debug = (EventKeywords)0x20000;
/// <summary>
/// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future
/// </summary>
- public const EventKeywords DebugActivityId = (EventKeywords) 0x40000;
+ public const EventKeywords DebugActivityId = (EventKeywords)0x40000;
}
/// <summary>Enabled for all keywords.</summary>
@@ -182,18 +182,18 @@ namespace System.Threading.Tasks
/// <summary>A continuation of a taskWaitEnd is complete </summary>
private const int TASKWAITCONTINUATIONSTARTED_ID = 19;
- private const int TRACEOPERATIONSTART_ID = 14;
- private const int TRACEOPERATIONSTOP_ID = 15;
- private const int TRACEOPERATIONRELATION_ID = 16;
+ private const int TRACEOPERATIONSTART_ID = 14;
+ private const int TRACEOPERATIONSTOP_ID = 15;
+ private const int TRACEOPERATIONRELATION_ID = 16;
private const int TRACESYNCHRONOUSWORKSTART_ID = 17;
- private const int TRACESYNCHRONOUSWORKSTOP_ID = 18;
+ private const int TRACESYNCHRONOUSWORKSTOP_ID = 18;
+
-
//-----------------------------------------------------------------------------------
//
// Task Events
//
-
+
// These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS)
// call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want
// to incur this cost when instrumentation is enabled. So the Task codepaths that call these
@@ -208,36 +208,36 @@ namespace System.Threading.Tasks
/// <param name="TaskID">The task ID.</param>
/// <param name="CreatingTaskID">The task ID</param>
/// <param name="TaskCreationOptions">The options used to create the task.</param>
- [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version=1, Opcode = EventOpcode.Send,
- Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
+ [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version = 1, Opcode = EventOpcode.Send,
+ Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)]
public void TaskScheduled(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain)
{
// IsEnabled() call is an inlined quick check that makes this very fast when provider is off
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks))
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks))
{
unsafe
{
EventData* eventPayload = stackalloc EventData[6];
eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID));
+ eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(int);
- eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID));
+ eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(int);
- eventPayload[2].DataPointer = ((IntPtr) (&TaskID));
+ eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
eventPayload[3].Size = sizeof(int);
- eventPayload[3].DataPointer = ((IntPtr) (&CreatingTaskID));
+ eventPayload[3].DataPointer = ((IntPtr)(&CreatingTaskID));
eventPayload[4].Size = sizeof(int);
- eventPayload[4].DataPointer = ((IntPtr) (&TaskCreationOptions));
+ eventPayload[4].DataPointer = ((IntPtr)(&TaskCreationOptions));
eventPayload[5].Size = sizeof(int);
- eventPayload[5].DataPointer = ((IntPtr) (&appDomain));
+ eventPayload[5].DataPointer = ((IntPtr)(&appDomain));
if (TasksSetActivityIds)
{
Guid childActivityId = CreateGuidForTaskID(TaskID);
WriteEventWithRelatedActivityIdCore(TASKSCHEDULED_ID, &childActivityId, 6, eventPayload);
}
- else
+ else
WriteEventCore(TASKSCHEDULED_ID, 6, eventPayload);
}
}
@@ -251,13 +251,13 @@ namespace System.Threading.Tasks
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
- [Event(TASKSTARTED_ID,
+ [Event(TASKSTARTED_ID,
Level = EventLevel.Informational, Keywords = Keywords.Tasks)]
public void TaskStarted(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID)
{
- if (IsEnabled(EventLevel.Informational, Keywords.Tasks))
+ if (IsEnabled(EventLevel.Informational, Keywords.Tasks))
WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID);
}
#endregion
@@ -270,33 +270,33 @@ namespace System.Threading.Tasks
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
/// <param name="IsExceptional">Whether the task completed due to an error.</param>
- [Event(TASKCOMPLETED_ID, Version=1,
+ [Event(TASKCOMPLETED_ID, Version = 1,
Level = EventLevel.Informational, Keywords = Keywords.TaskStops)]
public void TaskCompleted(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID, bool IsExceptional)
{
- if (IsEnabled(EventLevel.Informational, Keywords.Tasks))
+ if (IsEnabled(EventLevel.Informational, Keywords.Tasks))
{
unsafe
{
EventData* eventPayload = stackalloc EventData[4];
Int32 isExceptionalInt = IsExceptional ? 1 : 0;
eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID));
+ eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(int);
- eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID));
+ eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(int);
- eventPayload[2].DataPointer = ((IntPtr) (&TaskID));
+ eventPayload[2].DataPointer = ((IntPtr)(&TaskID));
eventPayload[3].Size = sizeof(int);
- eventPayload[3].DataPointer = ((IntPtr) (&isExceptionalInt));
+ eventPayload[3].DataPointer = ((IntPtr)(&isExceptionalInt));
WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload);
}
- }
+ }
}
#endregion
- #region TaskWaitBegin
+ #region TaskWaitBegin
/// <summary>
/// Fired when starting to wait for a taks's completion explicitly or implicitly.
/// </summary>
@@ -307,13 +307,13 @@ namespace System.Threading.Tasks
/// <param name="ContinueWithTaskID">If known, if 'TaskID' has a 'continueWith' task, mention give its ID here.
/// 0 means unknown. This allows better visualization of the common sequential chaining case.</param>
/// </summary>
- [Event(TASKWAITBEGIN_ID, Version=3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send,
- Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
+ [Event(TASKWAITBEGIN_ID, Version = 3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send,
+ Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)]
public void TaskWaitBegin(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks))
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks))
{
unsafe
{
@@ -348,7 +348,7 @@ namespace System.Threading.Tasks
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The task ID.</param>
- [Event(TASKWAITEND_ID,
+ [Event(TASKWAITEND_ID,
Level = EventLevel.Verbose, Keywords = Keywords.Tasks)]
public void TaskWaitEnd(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
@@ -395,23 +395,23 @@ namespace System.Threading.Tasks
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
/// <param name="TaskID">The activityId for the continuation.</param>
- [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send,
- Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)]
+ [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send,
+ Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer | Keywords.Tasks)]
public void AwaitTaskContinuationScheduled(
int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER
int ContinuwWithTaskId)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks))
- {
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer | Keywords.Tasks))
+ {
unsafe
{
EventData* eventPayload = stackalloc EventData[3];
eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID));
+ eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID));
eventPayload[1].Size = sizeof(int);
- eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID));
+ eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID));
eventPayload[2].Size = sizeof(int);
- eventPayload[2].DataPointer = ((IntPtr) (&ContinuwWithTaskId));
+ eventPayload[2].DataPointer = ((IntPtr)(&ContinuwWithTaskId));
if (TasksSetActivityIds)
{
Guid continuationActivityId = CreateGuidForTaskID(ContinuwWithTaskId);
@@ -423,116 +423,116 @@ namespace System.Threading.Tasks
}
}
- [Event(TRACEOPERATIONSTART_ID, Version=1,
+ [Event(TRACEOPERATIONSTART_ID, Version = 1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation))
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation))
{
unsafe
{
- fixed(char* operationNamePtr = OperationName)
+ fixed (char* operationNamePtr = OperationName)
{
EventData* eventPayload = stackalloc EventData[3];
eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&TaskID));
+ eventPayload[0].DataPointer = ((IntPtr)(&TaskID));
eventPayload[1].Size = ((OperationName.Length + 1) * 2);
- eventPayload[1].DataPointer = ((IntPtr) operationNamePtr);
+ eventPayload[1].DataPointer = ((IntPtr)operationNamePtr);
eventPayload[2].Size = sizeof(long);
- eventPayload[2].DataPointer = ((IntPtr) (&RelatedContext));
+ eventPayload[2].DataPointer = ((IntPtr)(&RelatedContext));
WriteEventCore(TRACEOPERATIONSTART_ID, 3, eventPayload);
}
}
- }
+ }
}
- [Event(TRACEOPERATIONRELATION_ID, Version=1,
+ [Event(TRACEOPERATIONRELATION_ID, Version = 1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)]
public void TraceOperationRelation(int TaskID, CausalityRelation Relation)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation))
- WriteEvent(TRACEOPERATIONRELATION_ID, TaskID,(int) Relation); // optmized overload for this exists
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation))
+ WriteEvent(TRACEOPERATIONRELATION_ID, TaskID, (int)Relation); // optmized overload for this exists
}
- [Event(TRACEOPERATIONSTOP_ID, Version=1,
+ [Event(TRACEOPERATIONSTOP_ID, Version = 1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)]
public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation))
- WriteEvent(TRACEOPERATIONSTOP_ID, TaskID,(int) Status); // optmized overload for this exists
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation))
+ WriteEvent(TRACEOPERATIONSTOP_ID, TaskID, (int)Status); // optmized overload for this exists
}
- [Event(TRACESYNCHRONOUSWORKSTART_ID, Version=1,
+ [Event(TRACESYNCHRONOUSWORKSTART_ID, Version = 1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork))
- WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID,(int) Work); // optmized overload for this exists
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork))
+ WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID, (int)Work); // optmized overload for this exists
}
- [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version=1,
+ [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version = 1,
Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)]
public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work)
{
- if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork))
+ if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork))
{
unsafe
{
EventData* eventPayload = stackalloc EventData[1];
eventPayload[0].Size = sizeof(int);
- eventPayload[0].DataPointer = ((IntPtr) (&Work));
+ eventPayload[0].DataPointer = ((IntPtr)(&Work));
WriteEventCore(TRACESYNCHRONOUSWORKSTOP_ID, 1, eventPayload);
}
- }
+ }
}
[NonEvent]
- unsafe public void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); }
+ unsafe public void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref Object))); }
[Event(20, Keywords = Keywords.Debug)]
- private void RunningContinuation(int TaskID, long Object)
- {
+ private void RunningContinuation(int TaskID, long Object)
+ {
if (Debug)
- WriteEvent(20, TaskID, Object);
+ WriteEvent(20, TaskID, Object);
}
[NonEvent]
- unsafe public void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); }
+ unsafe public void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long)*((void**)JitHelpers.UnsafeCastToStackPointer(ref Object))); }
[Event(21, Keywords = Keywords.Debug)]
- public void RunningContinuationList(int TaskID, int Index, long Object)
- {
+ public void RunningContinuationList(int TaskID, int Index, long Object)
+ {
if (Debug)
- WriteEvent(21, TaskID, Index, Object);
- }
+ WriteEvent(21, TaskID, Index, Object);
+ }
[Event(23, Keywords = Keywords.Debug)]
- public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); }
+ public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); }
[Event(24, Keywords = Keywords.Debug)]
- public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); }
+ public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); }
[Event(25, Keywords = Keywords.DebugActivityId)]
public void SetActivityId(Guid NewId)
{
if (DebugActivityId)
- WriteEvent(25, NewId);
- }
+ WriteEvent(25, NewId);
+ }
[Event(26, Keywords = Keywords.Debug)]
- public void NewID(int TaskID)
- {
+ public void NewID(int TaskID)
+ {
if (Debug)
- WriteEvent(26, TaskID);
- }
+ WriteEvent(26, TaskID);
+ }
/// <summary>
/// Activity IDs are GUIDS but task IDS are integers (and are not unique across appdomains
/// This routine creates a process wide unique GUID given a task ID
/// </summary>
- internal static Guid CreateGuidForTaskID(int taskID)
+ internal static Guid CreateGuidForTaskID(int taskID)
{
// The thread pool generated a process wide unique GUID from a task GUID by
// using the taskGuid, the appdomain ID, and 8 bytes of 'randomization' chosen by
@@ -540,9 +540,9 @@ namespace System.Threading.Tasks
// These were generated by CreateGuid, and are reasonably random (and thus unlikley to collide
uint pid = EventSource.s_currentPid;
int appDomainID = System.Threading.Thread.GetDomainID();
- return new Guid(taskID,
- (short) appDomainID , (short) (appDomainID >> 16),
- (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24),
+ return new Guid(taskID,
+ (short)appDomainID, (short)(appDomainID >> 16),
+ (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24),
0xff, 0xdc, 0xd7, 0xb5);
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs
index 7013c5c5e0..8e2e6a4cb0 100644
--- a/src/mscorlib/src/System/Threading/Tasks/Task.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs
@@ -29,7 +29,6 @@ using System.Diagnostics.Tracing;
namespace System.Threading.Tasks
{
-
/// <summary>
/// Utility class for allocating structs as heap variables
/// </summary>
@@ -41,7 +40,6 @@ namespace System.Threading.Tasks
{
this.Value = value;
}
-
}
/// <summary>
@@ -271,7 +269,7 @@ namespace System.Threading.Tasks
// but haven't yet been waited on by the parent, lazily initialized.
internal volatile List<Task> m_exceptionalChildren;
// A task's parent, or null if parent-less. Only set during Task construction.
- internal Task m_parent;
+ internal Task m_parent;
/// <summary>
/// Sets the internal completion event.
@@ -569,8 +567,8 @@ namespace System.Threading.Tasks
#if DEBUG
// Check the validity of internalOptions
- int illegalInternalOptions =
- (int) (internalOptions &
+ int illegalInternalOptions =
+ (int)(internalOptions &
~(InternalTaskOptions.PromiseTask |
InternalTaskOptions.ContinuationTask |
InternalTaskOptions.LazyCancellation |
@@ -581,27 +579,26 @@ namespace System.Threading.Tasks
// Assign options to m_stateAndOptionsFlag.
Debug.Assert(m_stateFlags == 0, "TaskConstructorCore: non-zero m_stateFlags");
Debug.Assert((((int)creationOptions) | OptionsMask) == OptionsMask, "TaskConstructorCore: options take too many bits");
- var tmpFlags = (int)creationOptions | (int)internalOptions;
- if ((m_action == null) || ((internalOptions & InternalTaskOptions.ContinuationTask) != 0))
- {
- // For continuation tasks or TaskCompletionSource.Tasks, begin life in the
- // WaitingForActivation state rather than the Created state.
- tmpFlags |= TASK_STATE_WAITINGFORACTIVATION;
- }
- m_stateFlags = tmpFlags; // one write to the volatile m_stateFlags instead of two when setting the above options
+ int tmpFlags = (int)creationOptions | (int)internalOptions; // one write to the volatile m_stateFlags instead of two when setting the above options
+ m_stateFlags = m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0 ?
+ tmpFlags | TASK_STATE_WAITINGFORACTIVATION :
+ tmpFlags;
// Now is the time to add the new task to the children list
// of the creating task if the options call for it.
// We can safely call the creator task's AddNewChild() method to register it,
// because at this point we are already on its thread of execution.
- Task parent = m_contingentProperties?.m_parent;
- if (parent != null
- && ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
- && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0)
- )
+ ContingentProperties props = m_contingentProperties;
+ if (props != null)
{
- parent.AddNewChild();
+ Task parent = props.m_parent;
+ if (parent != null
+ && ((creationOptions & TaskCreationOptions.AttachedToParent) != 0)
+ && ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0))
+ {
+ parent.AddNewChild();
+ }
}
// if we have a non-null cancellationToken, allocate the contingent properties to save it
@@ -716,14 +713,7 @@ namespace System.Threading.Tasks
}
// Internal property to process TaskCreationOptions access and mutation.
- internal TaskCreationOptions Options
- {
- get
- {
- int stateFlags = m_stateFlags; // "cast away" volatility to enable inlining of OptionsMethod
- return OptionsMethod(stateFlags);
- }
- }
+ internal TaskCreationOptions Options => OptionsMethod(m_stateFlags);
// Similar to Options property, but allows for the use of a cached flags value rather than
// a read of the volatile m_stateFlags field.
@@ -737,11 +727,16 @@ namespace System.Threading.Tasks
// no illegalBits are set. Returns true on success, false on failure.
internal bool AtomicStateUpdate(int newBits, int illegalBits)
{
- // This could be implemented in terms of:
- // internal bool AtomicStateUpdate(int newBits, int illegalBits, ref int oldFlags);
- // but for high-throughput perf, that delegation's cost is noticeable.
+ int oldFlags = m_stateFlags;
+ return
+ (oldFlags & illegalBits) == 0 &&
+ (Interlocked.CompareExchange(ref m_stateFlags, oldFlags | newBits, oldFlags) == oldFlags ||
+ AtomicStateUpdateSlow(newBits, illegalBits));
+ }
- SpinWait sw = new SpinWait();
+ private bool AtomicStateUpdateSlow(int newBits, int illegalBits)
+ {
+ var sw = new SpinWait();
do
{
int oldFlags = m_stateFlags;
@@ -900,7 +895,6 @@ namespace System.Threading.Tasks
return AtomicStateUpdate(TASK_STATE_STARTED, TASK_STATE_CANCELED | TASK_STATE_STARTED);
}
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool FireTaskScheduledIfNeeded(TaskScheduler ts)
{
var etwLog = TplEtwProvider.Log;
@@ -1789,7 +1783,7 @@ namespace System.Threading.Tasks
catch (ThreadAbortException tae)
{
AddException(tae);
- FinishThreadAbortedTask(delegateRan:false);
+ FinishThreadAbortedTask(delegateRan: false);
}
catch (Exception e)
{
@@ -2041,32 +2035,45 @@ namespace System.Threading.Tasks
/// <summary>
/// Signals completion of this particular task.
///
- /// The bUserDelegateExecuted parameter indicates whether this Finish() call comes following the
+ /// The userDelegateExecute parameter indicates whether this Finish() call comes following the
/// full execution of the user delegate.
///
- /// If bUserDelegateExecuted is false, it mean user delegate wasn't invoked at all (either due to
+ /// If userDelegateExecute is false, it mean user delegate wasn't invoked at all (either due to
/// a cancellation request, or because this task is a promise style Task). In this case, the steps
/// involving child tasks (i.e. WaitForChildren) will be skipped.
///
/// </summary>
- internal void Finish(bool bUserDelegateExecuted)
+ internal void Finish(bool userDelegateExecute)
+ {
+ if (m_contingentProperties == null)
+ {
+ FinishStageTwo();
+ }
+ else
+ {
+ FinishSlow(userDelegateExecute);
+ }
+ }
+
+ private void FinishSlow(bool userDelegateExecute)
{
- if (!bUserDelegateExecuted)
+ Debug.Assert(userDelegateExecute || m_contingentProperties != null);
+
+ if (!userDelegateExecute)
{
// delegate didn't execute => no children. We can safely call the remaining finish stages
FinishStageTwo();
}
else
{
- var props = Volatile.Read(ref m_contingentProperties);
+ ContingentProperties props = m_contingentProperties;
- if (props == null || // no contingent properties means no children, so it's safe to complete ourselves
- (props.m_completionCountdown == 1) ||
- // Count of 1 => either all children finished, or there were none. Safe to complete ourselves
- // without paying the price of an Interlocked.Decrement.
+ // Count of 1 => either all children finished, or there were none. Safe to complete ourselves
+ // without paying the price of an Interlocked.Decrement.
+ if ((props.m_completionCountdown == 1) ||
Interlocked.Decrement(ref props.m_completionCountdown) == 0) // Reaching this sub clause means there may be remaining active children,
- // and we could be racing with one of them to call FinishStageTwo().
- // So whoever does the final Interlocked.Dec is responsible to finish.
+ // and we could be racing with one of them to call FinishStageTwo().
+ // So whoever does the final Interlocked.Dec is responsible to finish.
{
FinishStageTwo();
}
@@ -2086,8 +2093,7 @@ namespace System.Threading.Tasks
// Now is the time to prune exceptional children. We'll walk the list and removes the ones whose exceptions we might have observed after they threw.
// we use a local variable for exceptional children here because some other thread may be nulling out m_contingentProperties.m_exceptionalChildren
- List<Task> exceptionalChildren = props != null ? props.m_exceptionalChildren : null;
-
+ List<Task> exceptionalChildren = props.m_exceptionalChildren;
if (exceptionalChildren != null)
{
lock (exceptionalChildren)
@@ -2106,12 +2112,17 @@ namespace System.Threading.Tasks
/// It can happen i) either on the thread that originally executed this task (if no children were spawned, or they all completed by the time this task's delegate quit)
/// ii) or on the thread that executed the last child.
/// </summary>
- internal void FinishStageTwo()
+ private void FinishStageTwo()
{
- AddExceptionsFromChildren();
-
// At this point, the task is done executing and waiting for its children,
// we can transition our task to a completion state.
+
+ ContingentProperties cp = Volatile.Read(ref m_contingentProperties);
+ if (cp != null)
+ {
+ AddExceptionsFromChildren(cp);
+ }
+
int completionState;
if (ExceptionRecorded)
{
@@ -2160,7 +2171,7 @@ namespace System.Threading.Tasks
// Set the completion event if it's been lazy allocated.
// And if we made a cancellation registration, it's now unnecessary.
- var cp = Volatile.Read(ref m_contingentProperties);
+ cp = Volatile.Read(ref m_contingentProperties); // need to re-read after updating state
if (cp != null)
{
cp.SetCompleted();
@@ -2187,6 +2198,17 @@ namespace System.Threading.Tasks
m_action = null;
// Notify parent if this was an attached task
+ if (m_contingentProperties != null)
+ {
+ NotifyParentIfPotentiallyAttachedTask();
+ }
+
+ // Activate continuations (if any).
+ FinishContinuations();
+ }
+
+ internal void NotifyParentIfPotentiallyAttachedTask()
+ {
Task parent = m_contingentProperties?.m_parent;
if (parent != null
&& ((parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0)
@@ -2194,9 +2216,6 @@ namespace System.Threading.Tasks
{
parent.ProcessChildCompletion(this);
}
-
- // Activate continuations (if any).
- FinishContinuations();
}
/// <summary>
@@ -2232,7 +2251,6 @@ namespace System.Threading.Tasks
tmp.Add(childTask);
}
}
-
}
if (Interlocked.Decrement(ref props.m_completionCountdown) == 0)
@@ -2248,14 +2266,15 @@ namespace System.Threading.Tasks
/// This is to be called just before the task does its final state transition.
/// It traverses the list of exceptional children, and appends their aggregate exceptions into this one's exception list
/// </summary>
- internal void AddExceptionsFromChildren()
+ internal void AddExceptionsFromChildren(ContingentProperties props)
{
+ Debug.Assert(props != null);
+
// In rare occurences during AppDomainUnload() processing, it is possible for this method to be called
// simultaneously on the same task from two different contexts. This can result in m_exceptionalChildren
// being nulled out while it is being processed, which could lead to a NullReferenceException. To
// protect ourselves, we'll cache m_exceptionalChildren in a local variable.
- var props = Volatile.Read(ref m_contingentProperties);
- List<Task> exceptionalChildren = props?.m_exceptionalChildren;
+ List<Task> exceptionalChildren = props.m_exceptionalChildren;
if (exceptionalChildren != null)
{
@@ -2310,40 +2329,13 @@ namespace System.Threading.Tasks
Finish(delegateRan);
}
-
- /// <summary>
- /// Executes the task. This method will only be called once, and handles any necessary exception marshaling.
- /// </summary>
- private void Execute()
- {
- try
- {
- InnerInvoke();
- }
- catch (ThreadAbortException tae)
- {
- // Record this exception in the task's exception list
- HandleException(tae);
-
- // This is a ThreadAbortException and it will be rethrown from this catch clause, causing us to
- // skip the regular Finish codepath. In order not to leave the task unfinished, we now call
- // FinishThreadAbortedTask here.
- FinishThreadAbortedTask(delegateRan: true);
- }
- catch (Exception exn)
- {
- // Record this exception in the task's exception list
- HandleException(exn);
- }
- }
-
/// <summary>
/// IThreadPoolWorkItem override, which is the entry function for this task when the TP scheduler decides to run it.
///
/// </summary>
void IThreadPoolWorkItem.ExecuteWorkItem()
{
- ExecuteEntry(false);
+ ExecuteEntryUnsafe();
}
/// <summary>
@@ -2357,46 +2349,58 @@ namespace System.Threading.Tasks
if (!IsCompleted)
{
HandleException(tae);
- FinishThreadAbortedTask(delegateRan:false);
+ FinishThreadAbortedTask(delegateRan: false);
}
}
/// <summary>
/// Outermost entry function to execute this task. Handles all aspects of executing a task on the caller thread.
- /// Currently this is called by IThreadPoolWorkItem.ExecuteWorkItem(), and TaskManager.TryExecuteInline.
- ///
/// </summary>
- /// <param name="bPreventDoubleExecution"> Performs atomic updates to prevent double execution. Should only be set to true
- /// in codepaths servicing user provided TaskSchedulers. The ThreadPool scheduler doesn't need this. </param>
- internal bool ExecuteEntry(bool bPreventDoubleExecution)
+ internal bool ExecuteEntry()
{
- if (bPreventDoubleExecution)
+ // Do atomic state transition from queued to invoked. If we observe a task that's already invoked,
+ // we will return false so that TaskScheduler.ExecuteTask can throw an exception back to the custom scheduler.
+ // However we don't want this exception to be throw if the task was already canceled, because it's a
+ // legitimate scenario for custom schedulers to dequeue a task and mark it as canceled (example: throttling scheduler)
+ int previousState = 0;
+ if (!AtomicStateUpdate(TASK_STATE_DELEGATE_INVOKED,
+ TASK_STATE_DELEGATE_INVOKED | TASK_STATE_COMPLETED_MASK,
+ ref previousState) && (previousState & TASK_STATE_CANCELED) == 0)
{
- int previousState = 0;
+ // This task has already been invoked. Don't invoke it again.
+ return false;
+ }
- // Do atomic state transition from queued to invoked. If we observe a task that's already invoked,
- // we will return false so that TaskScheduler.ExecuteTask can throw an exception back to the custom scheduler.
- // However we don't want this exception to be throw if the task was already canceled, because it's a
- // legitimate scenario for custom schedulers to dequeue a task and mark it as canceled (example: throttling scheduler)
- if (!AtomicStateUpdate(TASK_STATE_DELEGATE_INVOKED,
- TASK_STATE_DELEGATE_INVOKED | TASK_STATE_COMPLETED_MASK,
- ref previousState) && (previousState & TASK_STATE_CANCELED) == 0)
- {
- // This task has already been invoked. Don't invoke it again.
- return false;
- }
+ if (!IsCancellationRequested & !IsCanceled)
+ {
+ ExecuteWithThreadLocal(ref t_currentTask);
}
else
{
- // Remember that we started running the task delegate.
- m_stateFlags |= TASK_STATE_DELEGATE_INVOKED;
+ ExecuteEntryCancellationRequestedOrCanceled();
}
- if (!IsCancellationRequested && !IsCanceled)
+ return true;
+ }
+
+ internal void ExecuteEntryUnsafe() // used instead of ExecuteEntry() when we don't have to worry about double-execution prevent
+ {
+ // Remember that we started running the task delegate.
+ m_stateFlags |= TASK_STATE_DELEGATE_INVOKED;
+
+ if (!IsCancellationRequested & !IsCanceled)
{
ExecuteWithThreadLocal(ref t_currentTask);
}
- else if (!IsCanceled)
+ else
+ {
+ ExecuteEntryCancellationRequestedOrCanceled();
+ }
+ }
+
+ internal void ExecuteEntryCancellationRequestedOrCanceled()
+ {
+ if (!IsCanceled)
{
int prevState = Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_CANCELED);
if ((prevState & TASK_STATE_CANCELED) == 0)
@@ -2404,8 +2408,6 @@ namespace System.Threading.Tasks
CancellationCleanupLogic();
}
}
-
- return true;
}
// A trick so we can refer to the TLS slot with a byref.
@@ -2429,30 +2431,44 @@ namespace System.Threading.Tasks
etwLog.TaskStarted(TaskScheduler.Current.Id, 0, this.Id);
}
- if (AsyncCausalityTracer.LoggingOn)
+ bool loggingOn = AsyncCausalityTracer.LoggingOn;
+ if (loggingOn)
AsyncCausalityTracer.TraceSynchronousWorkStart(CausalityTraceLevel.Required, this.Id, CausalitySynchronousWork.Execution);
-
try
{
// place the current task into TLS.
currentTaskSlot = this;
- ExecutionContext ec = CapturedContext;
- if (ec == null)
+ // Execute the task body
+ try
{
- // No context, just run the task directly.
- Execute();
+ ExecutionContext ec = CapturedContext;
+ if (ec == null)
+ {
+ // No context, just run the task directly.
+ InnerInvoke();
+ }
+ else
+ {
+ // Invoke it under the captured ExecutionContext
+ ExecutionContext.Run(ec, s_ecCallback, this);
+ }
}
- else
+ catch (Exception exn)
{
- // Run the task. We need a simple shim that converts the
- // object back into a Task object, so that we can Execute it.
-
- ExecutionContext.Run(ec, s_ecCallback, this);
+ // Record this exception in the task's exception list
+ HandleException(exn);
+ if (exn is ThreadAbortException)
+ {
+ // This is a ThreadAbortException and it will be rethrown from this catch clause, causing us to
+ // skip the regular Finish codepath. In order not to leave the task unfinished, we now call
+ // FinishThreadAbortedTask here.
+ FinishThreadAbortedTask(delegateRan: true);
+ }
}
- if (AsyncCausalityTracer.LoggingOn)
+ if (loggingOn)
AsyncCausalityTracer.TraceSynchronousWorkCompletion(CausalityTraceLevel.Required, CausalitySynchronousWork.Execution);
Finish(true);
@@ -2460,7 +2476,7 @@ namespace System.Threading.Tasks
finally
{
currentTaskSlot = previousTask;
-
+
// ETW event for Task Completed
if (etwIsEnabled)
{
@@ -2476,7 +2492,7 @@ namespace System.Threading.Tasks
}
}
- private static readonly ContextCallback s_ecCallback = obj => ((Task)obj).Execute();
+ 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.
@@ -2973,7 +2989,6 @@ namespace System.Threading.Tasks
{
Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
}
-
}
return IsCompleted;
@@ -3031,12 +3046,10 @@ namespace System.Threading.Tasks
// So we need to remeber whether we actually did the flip, so we can do clean up (finish continuations etc)
mustCleanup = AtomicStateUpdate(TASK_STATE_CANCELED, TASK_STATE_DELEGATE_INVOKED | TASK_STATE_CANCELED);
-
// PS: This is slightly different from the regular cancellation codepath
// since we record the cancellation request *after* doing the state transition.
// However that shouldn't matter too much because the task was never invoked, thus can't have children
}
-
}
if (!bCancelNonExecutingOnly || bPopSucceeded || mustCleanup)
@@ -3125,7 +3138,7 @@ namespace System.Threading.Tasks
oce = edi.SourceException as OperationCanceledException;
Debug.Assert(oce != null, "Expected EDI to contain an OCE");
}
- Debug.Assert(oce.CancellationToken == tokenToRecord,
+ Debug.Assert(oce.CancellationToken == tokenToRecord,
"Expected OCE's token to match the provided token.");
#endif
AddException(cancellationException, representsCancellation: true);
@@ -3191,7 +3204,18 @@ namespace System.Threading.Tasks
{
// Atomically store the fact that this task is completing. From this point on, the adding of continuations will
// result in the continuations being run/launched directly rather than being added to the continuation list.
+ // Then if we grabbed any continuations, run them.
object continuationObject = Interlocked.Exchange(ref m_continuationObject, s_taskCompletionSentinel);
+ if (continuationObject != null)
+ {
+ RunContinuations(continuationObject);
+ }
+ }
+
+ private void RunContinuations(object continuationObject) // separated out of FinishContinuations to enable it to be inlined
+ {
+ Debug.Assert(continuationObject != null);
+
TplEtwProvider etw = TplEtwProvider.Log;
bool tplEtwProviderLoggingEnabled = etw.IsEnabled();
if (tplEtwProviderLoggingEnabled)
@@ -3199,136 +3223,125 @@ namespace System.Threading.Tasks
etw.RunningContinuation(Id, continuationObject);
}
- // If continuationObject == null, then we don't have any continuations to process
- if (continuationObject != null)
- {
-
- if (AsyncCausalityTracer.LoggingOn)
- AsyncCausalityTracer.TraceSynchronousWorkStart(CausalityTraceLevel.Required, this.Id, CausalitySynchronousWork.CompletionNotification);
+ if (AsyncCausalityTracer.LoggingOn)
+ AsyncCausalityTracer.TraceSynchronousWorkStart(CausalityTraceLevel.Required, this.Id, CausalitySynchronousWork.CompletionNotification);
- // 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) ||
- ((m_stateFlags & (int)TaskCreationOptions.RunContinuationsAsynchronously) != 0));
+ // 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) ||
+ ((m_stateFlags & (int)TaskCreationOptions.RunContinuationsAsynchronously) != 0));
- // Handle the single-Action case
- Action singleAction = continuationObject as Action;
- if (singleAction != null)
- {
- AwaitTaskContinuation.RunOrScheduleAction(singleAction, bCanInlineContinuations, ref t_currentTask);
- LogFinishCompletionNotification();
- return;
- }
+ // Handle the single-Action case
+ Action singleAction = continuationObject as Action;
+ if (singleAction != null)
+ {
+ AwaitTaskContinuation.RunOrScheduleAction(singleAction, bCanInlineContinuations, ref t_currentTask);
+ LogFinishCompletionNotification();
+ return;
+ }
- // Handle the single-ITaskCompletionAction case
- ITaskCompletionAction singleTaskCompletionAction = continuationObject as ITaskCompletionAction;
- if (singleTaskCompletionAction != null)
+ // Handle the single-ITaskCompletionAction case
+ ITaskCompletionAction singleTaskCompletionAction = continuationObject as ITaskCompletionAction;
+ if (singleTaskCompletionAction != null)
+ {
+ if (bCanInlineContinuations || !singleTaskCompletionAction.InvokeMayRunArbitraryCode)
{
- if (bCanInlineContinuations || !singleTaskCompletionAction.InvokeMayRunArbitraryCode)
- {
- singleTaskCompletionAction.Invoke(this);
- }
- else
- {
- ThreadPool.UnsafeQueueCustomWorkItem(new CompletionActionInvoker(singleTaskCompletionAction, this), forceGlobal: false);
- }
- LogFinishCompletionNotification();
- return;
+ singleTaskCompletionAction.Invoke(this);
}
-
- // Handle the single-TaskContinuation case
- TaskContinuation singleTaskContinuation = continuationObject as TaskContinuation;
- if (singleTaskContinuation != null)
+ else
{
- singleTaskContinuation.Run(this, bCanInlineContinuations);
- LogFinishCompletionNotification();
- return;
+ ThreadPool.UnsafeQueueCustomWorkItem(new CompletionActionInvoker(singleTaskCompletionAction, this), forceGlobal: false);
}
+ LogFinishCompletionNotification();
+ return;
+ }
- // Not a single; attempt to cast as list
- List<object> continuations = continuationObject as List<object>;
+ // Handle the single-TaskContinuation case
+ TaskContinuation singleTaskContinuation = continuationObject as TaskContinuation;
+ if (singleTaskContinuation != null)
+ {
+ singleTaskContinuation.Run(this, bCanInlineContinuations);
+ LogFinishCompletionNotification();
+ return;
+ }
- if (continuations == null)
- {
- LogFinishCompletionNotification();
- return; // Not a single or a list; just return
- }
+ // Not a single; it must be a list.
+ List<object> continuations = (List<object>)continuationObject;
- //
- // Begin processing of continuation list
- //
+ //
+ // Begin processing of continuation list
+ //
- // Wait for any concurrent adds or removes to be retired
- lock (continuations) { }
- int continuationCount = continuations.Count;
+ // Wait for any concurrent adds or removes to be retired
+ lock (continuations) { }
+ int continuationCount = continuations.Count;
- // Fire the asynchronous continuations first ...
- for (int i = 0; i < continuationCount; i++)
+ // Fire the asynchronous continuations first ...
+ for (int i = 0; i < continuationCount; i++)
+ {
+ // Synchronous continuation tasks will have the ExecuteSynchronously option,
+ // and we're looking for asynchronous tasks...
+ var tc = continuations[i] as StandardTaskContinuation;
+ if (tc != null && (tc.m_options & TaskContinuationOptions.ExecuteSynchronously) == 0)
{
- // Synchronous continuation tasks will have the ExecuteSynchronously option,
- // and we're looking for asynchronous tasks...
- var tc = continuations[i] as StandardTaskContinuation;
- if (tc != null && (tc.m_options & TaskContinuationOptions.ExecuteSynchronously) == 0)
+ if (tplEtwProviderLoggingEnabled)
{
- if (tplEtwProviderLoggingEnabled)
- {
- etw.RunningContinuationList(Id, i, tc);
- }
- continuations[i] = null; // so that we can skip this later
- tc.Run(this, bCanInlineContinuations);
+ etw.RunningContinuationList(Id, i, tc);
}
+ continuations[i] = null; // so that we can skip this later
+ tc.Run(this, bCanInlineContinuations);
}
+ }
- // ... and then fire the synchronous continuations (if there are any).
- // This includes ITaskCompletionAction, AwaitTaskContinuations, and
- // Action delegates, which are all by default implicitly synchronous.
- for (int i = 0; i < continuationCount; i++)
+ // ... and then fire the synchronous continuations (if there are any).
+ // This includes ITaskCompletionAction, AwaitTaskContinuations, and
+ // Action delegates, which are all by default implicitly synchronous.
+ for (int i = 0; i < continuationCount; i++)
+ {
+ object currentContinuation = continuations[i];
+ if (currentContinuation == null) continue;
+ continuations[i] = null; // to enable free'ing up memory earlier
+ if (tplEtwProviderLoggingEnabled)
{
- object currentContinuation = continuations[i];
- if (currentContinuation == null) continue;
- continuations[i] = null; // to enable free'ing up memory earlier
- if (tplEtwProviderLoggingEnabled)
- {
- etw.RunningContinuationList(Id, i, currentContinuation);
- }
+ etw.RunningContinuationList(Id, i, currentContinuation);
+ }
- // If the continuation is an Action delegate, it came from an await continuation,
- // and we should use AwaitTaskContinuation to run it.
- Action ad = currentContinuation as Action;
- if (ad != null)
+ // If the continuation is an Action delegate, it came from an await continuation,
+ // and we should use AwaitTaskContinuation to run it.
+ Action ad = currentContinuation as Action;
+ if (ad != null)
+ {
+ AwaitTaskContinuation.RunOrScheduleAction(ad, bCanInlineContinuations, ref t_currentTask);
+ }
+ else
+ {
+ // If it's a TaskContinuation object of some kind, invoke it.
+ TaskContinuation tc = currentContinuation as TaskContinuation;
+ if (tc != null)
{
- AwaitTaskContinuation.RunOrScheduleAction(ad, bCanInlineContinuations, ref t_currentTask);
+ // We know that this is a synchronous continuation because the
+ // asynchronous ones have been weeded out
+ tc.Run(this, bCanInlineContinuations);
}
+ // Otherwise, it must be an ITaskCompletionAction, so invoke it.
else
{
- // If it's a TaskContinuation object of some kind, invoke it.
- TaskContinuation tc = currentContinuation as TaskContinuation;
- if (tc != null)
+ Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
+ var action = (ITaskCompletionAction)currentContinuation;
+
+ if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode)
{
- // We know that this is a synchronous continuation because the
- // asynchronous ones have been weeded out
- tc.Run(this, bCanInlineContinuations);
+ action.Invoke(this);
}
- // Otherwise, it must be an ITaskCompletionAction, so invoke it.
else
{
- Debug.Assert(currentContinuation is ITaskCompletionAction, "Expected continuation element to be Action, TaskContinuation, or ITaskContinuationAction");
- var action = (ITaskCompletionAction)currentContinuation;
-
- if (bCanInlineContinuations || !action.InvokeMayRunArbitraryCode)
- {
- action.Invoke(this);
- }
- else
- {
- ThreadPool.UnsafeQueueCustomWorkItem(new CompletionActionInvoker(action, this), forceGlobal: false);
- }
+ ThreadPool.UnsafeQueueCustomWorkItem(new CompletionActionInvoker(action, this), forceGlobal: false);
}
}
}
-
- LogFinishCompletionNotification();
}
+
+ LogFinishCompletionNotification();
}
private void LogFinishCompletionNotification()
@@ -4140,29 +4153,29 @@ namespace System.Threading.Tasks
out InternalTaskOptions internalOptions)
{
// This is used a couple of times below
- TaskContinuationOptions NotOnAnything =
+ const TaskContinuationOptions NotOnAnything =
TaskContinuationOptions.NotOnCanceled |
TaskContinuationOptions.NotOnFaulted |
TaskContinuationOptions.NotOnRanToCompletion;
- TaskContinuationOptions creationOptionsMask =
+ const TaskContinuationOptions CreationOptionsMask =
TaskContinuationOptions.PreferFairness |
TaskContinuationOptions.LongRunning |
TaskContinuationOptions.DenyChildAttach |
TaskContinuationOptions.HideScheduler |
- TaskContinuationOptions.AttachedToParent|
+ TaskContinuationOptions.AttachedToParent |
TaskContinuationOptions.RunContinuationsAsynchronously;
// Check that LongRunning and ExecuteSynchronously are not specified together
- TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
- if ((continuationOptions & illegalMask) == illegalMask)
+ const TaskContinuationOptions IllegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
+ if ((continuationOptions & IllegalMask) == IllegalMask)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions, ExceptionResource.Task_ContinueWith_ESandLR);
}
// Check that no illegal options were specified
if ((continuationOptions &
- ~(creationOptionsMask | NotOnAnything |
+ ~(CreationOptionsMask | NotOnAnything |
TaskContinuationOptions.LazyCancellation | TaskContinuationOptions.ExecuteSynchronously)) != 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions);
@@ -4175,14 +4188,12 @@ namespace System.Threading.Tasks
}
// This passes over all but LazyCancellation, which has no representation in TaskCreationOptions
- creationOptions = (TaskCreationOptions)(continuationOptions & creationOptionsMask);
-
- // internalOptions has at least ContinuationTask ...
- internalOptions = InternalTaskOptions.ContinuationTask;
+ creationOptions = (TaskCreationOptions)(continuationOptions & CreationOptionsMask);
- // ... and possibly LazyCancellation
- if ((continuationOptions & TaskContinuationOptions.LazyCancellation) != 0)
- internalOptions |= InternalTaskOptions.LazyCancellation;
+ // internalOptions has at least ContinuationTask and possibly LazyCancellation
+ internalOptions = (continuationOptions & TaskContinuationOptions.LazyCancellation) != 0 ?
+ InternalTaskOptions.ContinuationTask | InternalTaskOptions.LazyCancellation :
+ InternalTaskOptions.ContinuationTask;
}
@@ -4417,7 +4428,6 @@ namespace System.Threading.Tasks
{
// null out that TaskContinuation entry, which will be interpreted as "to be cleaned up"
continuationsLocalListRef[index] = null;
-
}
}
}
@@ -4500,7 +4510,6 @@ namespace System.Threading.Tasks
}
return WaitAll(tasks, (int)totalMilliseconds);
-
}
/// <summary>
@@ -5020,6 +5029,10 @@ namespace System.Threading.Tasks
signaledTaskIndex = Array.IndexOf(tasks, firstCompleted.Result);
Debug.Assert(signaledTaskIndex >= 0);
}
+ else
+ {
+ TaskFactory.CommonCWAnyLogicCleanup(firstCompleted);
+ }
}
// We need to prevent the tasks array from being GC'ed until we come out of the wait.
@@ -5103,7 +5116,7 @@ namespace System.Threading.Tasks
Debug.Assert(succeeded, "This should always succeed on a new task.");
return task;
}
-
+
/// <summary>Creates a <see cref="Task"/> that's completed due to cancellation with the specified token.</summary>
/// <param name="cancellationToken">The token with which to complete the task.</param>
/// <returns>The canceled task.</returns>
@@ -5112,7 +5125,7 @@ namespace System.Threading.Tasks
{
return FromCanceled(cancellationToken);
}
-
+
/// <summary>Creates a <see cref="Task{TResult}"/> that's completed due to cancellation with the specified token.</summary>
/// <typeparam name="TResult">The type of the result returned by the task.</typeparam>
/// <param name="cancellationToken">The token with which to complete the task.</param>
@@ -5122,7 +5135,7 @@ namespace System.Threading.Tasks
{
return FromCanceled<TResult>(cancellationToken);
}
-
+
#endregion
#region Run methods
@@ -6120,8 +6133,8 @@ namespace System.Threading.Tasks
internal virtual Delegate[] GetDelegateContinuationsForDebugger()
{
//Avoid an infinite loop by making sure the continuation object is not a reference to istelf.
- if (this.m_continuationObject != this)
- return GetDelegatesFromContinuationObject(this.m_continuationObject);
+ if (m_continuationObject != this)
+ return GetDelegatesFromContinuationObject(m_continuationObject);
else
return null;
}
@@ -6192,11 +6205,8 @@ namespace System.Threading.Tasks
private static Task[] GetActiveTasks()
{
-
return new List<Task>(s_currentActiveTasks.Values).ToArray();
}
-
-
}
internal sealed class CompletionActionInvoker : IThreadPoolWorkItem
@@ -6715,5 +6725,4 @@ namespace System.Threading.Tasks
public bool InvokeMayRunArbitraryCode { get { return true; } }
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs
deleted file mode 100644
index f15e3e783a..0000000000
--- a/src/mscorlib/src/System/Threading/Tasks/TaskCanceledException.cs
+++ /dev/null
@@ -1,93 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// An exception for task cancellations.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-
-namespace System.Threading.Tasks
-{
-
- /// <summary>
- /// Represents an exception used to communicate task cancellation.
- /// </summary>
- [Serializable]
- public class TaskCanceledException : OperationCanceledException
- {
-
- [NonSerialized]
- private Task m_canceledTask; // The task which has been canceled.
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/> class.
- /// </summary>
- public TaskCanceledException() : base(Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage"))
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/>
- /// class with a specified error message.
- /// </summary>
- /// <param name="message">The error message that explains the reason for the exception.</param>
- public TaskCanceledException(string message) : base(message)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/>
- /// class with a specified error message and a reference to the inner exception that is the cause of
- /// this exception.
- /// </summary>
- /// <param name="message">The error message that explains the reason for the exception.</param>
- /// <param name="innerException">The exception that is the cause of the current exception.</param>
- public TaskCanceledException(string message, Exception innerException) : base(message, innerException)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/> class
- /// with a reference to the <see cref="T:System.Threading.Tasks.Task"/> that has been canceled.
- /// </summary>
- /// <param name="task">A task that has been canceled.</param>
- public TaskCanceledException(Task task) :
- base(Environment.GetResourceString("TaskCanceledException_ctor_DefaultMessage"), task!=null ? task.CancellationToken:new CancellationToken())
- {
- m_canceledTask = task;
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskCanceledException"/>
- /// class with serialized data.
- /// </summary>
- /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
- /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination. </param>
- protected TaskCanceledException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- }
-
- /// <summary>
- /// Gets the task associated with this exception.
- /// </summary>
- /// <remarks>
- /// It is permissible for no Task to be associated with a
- /// <see cref="T:System.Threading.Tasks.TaskCanceledException"/>, in which case
- /// this property will return null.
- /// </remarks>
- public Task Task
- {
- get { return m_canceledTask; }
- }
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
index bf9f9cbb2c..0c80afd22c 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskCompletionSource.cs
@@ -131,7 +131,7 @@ namespace System.Threading.Tasks
{
// Spin wait until the completion is finalized by another thread.
var sw = new SpinWait();
- while (!m_task.IsCompleted)
+ while (!m_task.IsCompleted)
sw.SpinOnce();
}
@@ -185,7 +185,7 @@ namespace System.Threading.Tasks
public bool TrySetException(IEnumerable<Exception> exceptions)
{
if (exceptions == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exceptions);
-
+
List<Exception> defensiveCopy = new List<Exception>();
foreach (Exception e in exceptions)
{
@@ -276,7 +276,7 @@ namespace System.Threading.Tasks
public bool TrySetResult(TResult result)
{
bool rval = m_task.TrySetResult(result);
- if (!rval && !m_task.IsCompleted) SpinUntilCompleted();
+ if (!rval) SpinUntilCompleted();
return rval;
}
@@ -346,7 +346,7 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The <see cref="Task"/> was disposed.</exception>
public void SetCanceled()
{
- if(!TrySetCanceled())
+ if (!TrySetCanceled())
ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted);
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
index 3c6ccd8dd4..848a0ecbc2 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskContinuation.cs
@@ -32,7 +32,7 @@ namespace System.Threading.Tasks
Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
- Contract.Requires(action is Action<Task> || action is Action<Task, object>,
+ Contract.Requires(action is Action<Task> || action is Action<Task, object>,
"Invalid delegate type in ContinuationTaskFromTask");
m_antecedent = antecedent;
}
@@ -45,7 +45,7 @@ namespace System.Threading.Tasks
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Debug.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromTask.");
m_antecedent = null;
@@ -79,7 +79,7 @@ namespace System.Threading.Tasks
Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
- Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
+ Contract.Requires(function is Func<Task, TResult> || function is Func<Task, object, TResult>,
"Invalid delegate type in ContinuationResultTaskFromTask");
m_antecedent = antecedent;
}
@@ -92,7 +92,7 @@ namespace System.Threading.Tasks
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Debug.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromTask.");
m_antecedent = null;
@@ -126,7 +126,7 @@ namespace System.Threading.Tasks
Task<TAntecedentResult> antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) :
base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null)
{
- Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
+ Contract.Requires(action is Action<Task<TAntecedentResult>> || action is Action<Task<TAntecedentResult>, object>,
"Invalid delegate type in ContinuationTaskFromResultTask");
m_antecedent = antecedent;
}
@@ -139,7 +139,7 @@ namespace System.Threading.Tasks
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Debug.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationTaskFromResultTask.");
m_antecedent = null;
@@ -186,7 +186,7 @@ namespace System.Threading.Tasks
// Get and null out the antecedent. This is crucial to avoid a memory
// leak with long chains of continuations.
var antecedent = m_antecedent;
- Debug.Assert(antecedent != null,
+ Debug.Assert(antecedent != null,
"No antecedent was set for the ContinuationResultTaskFromResultTask.");
m_antecedent = null;
@@ -276,7 +276,6 @@ namespace System.Threading.Tasks
}
internal abstract Delegate[] GetDelegateContinuationsForDebugger();
-
}
/// <summary>Provides the standard implementation of a task continuation.</summary>
@@ -505,7 +504,8 @@ namespace System.Threading.Tasks
// Create the continuation task task. If we're allowed to inline, try to do so.
// The target scheduler may still deny us from executing on this thread, in which case this'll be queued.
- var task = CreateTask(state => {
+ var task = CreateTask(state =>
+ {
try { ((Action)state)(); }
catch (Exception exc) { ThrowAsyncIfNecessary(exc); }
}, m_action, m_scheduler);
@@ -558,10 +558,10 @@ namespace System.Threading.Tasks
Contract.Requires(scheduler != null);
return new Task(
- action, state, null, default(CancellationToken),
- TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler)
- {
- CapturedContext = m_capturedContext
+ action, state, null, default(CancellationToken),
+ TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler)
+ {
+ CapturedContext = m_capturedContext
};
}
@@ -590,7 +590,7 @@ namespace System.Threading.Tasks
// We couldn't inline, so now we need to schedule it
ThreadPool.UnsafeQueueCustomWorkItem(this, forceGlobal: false);
- }
+ }
}
/// <summary>
@@ -626,7 +626,7 @@ namespace System.Threading.Tasks
}
/// <summary>IThreadPoolWorkItem override, which is the entry function for this when the ThreadPool scheduler decides to run it.</summary>
- void ExecuteWorkItemHelper()
+ private void ExecuteWorkItemHelper()
{
var etwLog = TplEtwProvider.Log;
Guid savedActivityId = Guid.Empty;
@@ -645,7 +645,7 @@ namespace System.Threading.Tasks
{
m_action();
}
- // If there is an execution context, get the cached delegate and run the action under the context.
+ // If there is an execution context, get the cached delegate and run the action under the context.
else
{
ExecutionContext.Run(m_capturedContext, GetInvokeActionCallback(), m_action);
@@ -815,5 +815,4 @@ namespace System.Threading.Tasks
return new Delegate[] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) };
}
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
index ee1112a93f..1385d907e0 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskExceptionHolder.cs
@@ -70,9 +70,9 @@ namespace System.Threading.Tasks
private static void EnsureADUnloadCallbackRegistered()
{
- if (s_adUnloadEventHandler == null &&
- Interlocked.CompareExchange( ref s_adUnloadEventHandler,
- AppDomainUnloadCallback,
+ if (s_adUnloadEventHandler == null &&
+ Interlocked.CompareExchange(ref s_adUnloadEventHandler,
+ AppDomainUnloadCallback,
null) == null)
{
AppDomain.CurrentDomain.DomainUnload += s_adUnloadEventHandler;
@@ -93,7 +93,7 @@ namespace System.Threading.Tasks
// We need to do this filtering because all TaskExceptionHolders will be finalized during shutdown or unload
// regardles of reachability of the task (i.e. even if the user code was about to observe the task's exception),
// which can otherwise lead to spurious crashes during shutdown.
- if (m_faultExceptions != null && !m_isHandled &&
+ if (m_faultExceptions != null && !m_isHandled &&
!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload() && !s_domainUnloadStarted)
{
// We don't want to crash the finalizer thread if any ThreadAbortExceptions
@@ -124,14 +124,14 @@ namespace System.Threading.Tasks
// will have been marked as handled before even getting here.
// Give users a chance to keep this exception from crashing the process
-
+
// First, publish the unobserved exception and allow users to observe it
AggregateException exceptionToThrow = new AggregateException(
- Environment.GetResourceString("TaskExceptionHolder_UnhandledException"),
+ SR.TaskExceptionHolder_UnhandledException,
m_faultExceptions);
UnobservedTaskExceptionEventArgs ueea = new UnobservedTaskExceptionEventArgs(exceptionToThrow);
TaskScheduler.PublishUnobservedTaskException(m_task, ueea);
-
+
// Now, if we are still unobserved and we're configured to crash on unobserved, throw the exception.
// We need to publish the event above even if we're not going to crash, hence
// why this check doesn't come at the beginning of the method.
@@ -164,7 +164,7 @@ namespace System.Threading.Tasks
{
Contract.Requires(exceptionObject != null, "TaskExceptionHolder.Add(): Expected a non-null exceptionObject");
Contract.Requires(
- exceptionObject is Exception || exceptionObject is IEnumerable<Exception> ||
+ exceptionObject is Exception || exceptionObject is IEnumerable<Exception> ||
exceptionObject is ExceptionDispatchInfo || exceptionObject is IEnumerable<ExceptionDispatchInfo>,
"TaskExceptionHolder.Add(): Expected Exception, IEnumerable<Exception>, ExceptionDispatchInfo, or IEnumerable<ExceptionDispatchInfo>");
@@ -180,16 +180,16 @@ namespace System.Threading.Tasks
private void SetCancellationException(object exceptionObject)
{
Contract.Requires(exceptionObject != null, "Expected exceptionObject to be non-null.");
-
- Debug.Assert(m_cancellationException == null,
+
+ Debug.Assert(m_cancellationException == null,
"Expected SetCancellationException to be called only once.");
- // Breaking this assumption will overwrite a previously OCE,
- // and implies something may be wrong elsewhere, since there should only ever be one.
+ // Breaking this assumption will overwrite a previously OCE,
+ // and implies something may be wrong elsewhere, since there should only ever be one.
- Debug.Assert(m_faultExceptions == null,
+ Debug.Assert(m_faultExceptions == null,
"Expected SetCancellationException to be called before any faults were added.");
- // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
- // If this changes, make sure to only conditionally mark as handled below.
+ // Breaking this assumption shouldn't hurt anything here, but it implies something may be wrong elsewhere.
+ // If this changes, make sure to only conditionally mark as handled below.
// Store the cancellation exception
var oce = exceptionObject as OperationCanceledException;
@@ -267,21 +267,21 @@ namespace System.Threading.Tasks
exceptions.AddRange(ediColl);
#if DEBUG
Debug.Assert(exceptions.Count > 0, "There should be at least one dispatch info.");
- foreach(var tmp in exceptions)
+ foreach (var tmp in exceptions)
{
Debug.Assert(tmp != null, "No dispatch infos should be null");
}
#endif
}
- // Anything else is a programming error
+ // Anything else is a programming error
else
{
- throw new ArgumentException(Environment.GetResourceString("TaskExceptionHolder_UnknownExceptionType"), nameof(exceptionObject));
+ throw new ArgumentException(SR.TaskExceptionHolder_UnknownExceptionType, nameof(exceptionObject));
}
}
}
}
-
+
// If all of the exceptions are ThreadAbortExceptions and/or
// AppDomainUnloadExceptions, we do not want the finalization
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
index 89ba2988ca..e193d0e4e2 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskFactory.cs
@@ -40,30 +40,20 @@ namespace System.Threading.Tasks
public class TaskFactory
{
// member variables
- private CancellationToken m_defaultCancellationToken;
- private TaskScheduler m_defaultScheduler;
- private TaskCreationOptions m_defaultCreationOptions;
- private TaskContinuationOptions m_defaultContinuationOptions;
+ private readonly CancellationToken m_defaultCancellationToken;
+ private readonly TaskScheduler m_defaultScheduler;
+ private readonly TaskCreationOptions m_defaultCreationOptions;
+ private readonly TaskContinuationOptions m_defaultContinuationOptions;
-
- private TaskScheduler DefaultScheduler
- {
- get
- {
- if (m_defaultScheduler == null) return TaskScheduler.Current;
- else return m_defaultScheduler;
- }
- }
+ private TaskScheduler DefaultScheduler => m_defaultScheduler ?? TaskScheduler.Current;
// sister method to above property -- avoids a TLS lookup
private TaskScheduler GetDefaultScheduler(Task currTask)
{
- if (m_defaultScheduler != null) return m_defaultScheduler;
- else if ((currTask != null)
- && ((currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0)
- )
- return currTask.ExecutingTaskScheduler;
- else return TaskScheduler.Default;
+ return
+ m_defaultScheduler ??
+ (currTask != null && (currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0 ? currTask.ExecutingTaskScheduler :
+ TaskScheduler.Default);
}
/* Constructors */
@@ -1528,9 +1518,9 @@ namespace System.Threading.Tasks
{
// Options detected here cause exceptions in FromAsync methods that take beginMethod as a parameter
if ((creationOptions & TaskCreationOptions.LongRunning) != 0)
- throw new ArgumentOutOfRangeException(nameof(creationOptions), Environment.GetResourceString("Task_FromAsync_LongRunning"));
+ throw new ArgumentOutOfRangeException(nameof(creationOptions), SR.Task_FromAsync_LongRunning);
if ((creationOptions & TaskCreationOptions.PreferFairness) != 0)
- throw new ArgumentOutOfRangeException(nameof(creationOptions), Environment.GetResourceString("Task_FromAsync_PreferFairness"));
+ throw new ArgumentOutOfRangeException(nameof(creationOptions), SR.Task_FromAsync_PreferFairness);
}
// Check for general validity of options
@@ -2325,7 +2315,7 @@ namespace System.Threading.Tasks
{
Contract.Requires(tasks != null, "Expected non-null collection of tasks");
_tasks = tasks;
-
+
if (AsyncCausalityTracer.LoggingOn)
AsyncCausalityTracer.TraceOperationCreation(CausalityTraceLevel.Required, this.Id, "TaskFactory.ContinueWhenAny", 0);
@@ -2337,7 +2327,8 @@ namespace System.Threading.Tasks
public void Invoke(Task completingTask)
{
- if (Interlocked.CompareExchange(ref m_firstTaskAlreadyCompleted, 1, 0) == 0)
+ if (m_firstTaskAlreadyCompleted == 0 &&
+ Interlocked.Exchange(ref m_firstTaskAlreadyCompleted, 1) == 0)
{
if (AsyncCausalityTracer.LoggingOn)
{
@@ -2367,7 +2358,6 @@ namespace System.Threading.Tasks
!task.IsCompleted) task.RemoveContinuation(this);
}
_tasks = null;
-
}
}
@@ -2382,17 +2372,18 @@ namespace System.Threading.Tasks
{
Contract.Requires(tasks != null);
- // Create a promise task to be returned to the user
+ // Create a promise task to be returned to the user.
+ // (If this logic ever changes, also update CommonCWAnyLogicCleanup.)
var promise = new CompleteOnInvokePromise(tasks);
// At the completion of any of the tasks, complete the promise.
bool checkArgsOnly = false;
int numTasks = tasks.Count;
- for(int i=0; i<numTasks; i++)
+ for (int i = 0; i < numTasks; i++)
{
var task = tasks[i];
- if (task == null) throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks));
+ if (task == null) throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks));
if (checkArgsOnly) continue;
@@ -2430,6 +2421,17 @@ namespace System.Threading.Tasks
return promise;
}
+ /// <summary>
+ /// Cleans up the operations performed by CommonCWAnyLogic in a case where
+ /// the created continuation task is being discarded.
+ /// </summary>
+ /// <param name="continuation">The task returned from CommonCWAnyLogic.</param>
+ internal static void CommonCWAnyLogicCleanup(Task<Task> continuation)
+ {
+ // Force cleanup of the promise (e.g. removing continuations from each
+ // constituent task), by completing the promise with any value.
+ ((CompleteOnInvokePromise)continuation).Invoke(null);
+ }
/// <summary>
/// Creates a continuation <see cref="T:System.Threading.Tasks.Task">Task</see>
@@ -2663,7 +2665,7 @@ namespace System.Threading.Tasks
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null,continuationOptions, m_defaultCancellationToken, DefaultScheduler);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler);
}
/// <summary>
@@ -2775,7 +2777,7 @@ namespace System.Threading.Tasks
if (continuationFunction == null) throw new ArgumentNullException(nameof(continuationFunction));
Contract.EndContractBlock();
- return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
+ return TaskFactory<TResult>.ContinueWhenAnyImpl<TAntecedentResult>(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler);
}
/// <summary>
@@ -3018,7 +3020,7 @@ namespace System.Threading.Tasks
if (tasks == null)
throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), nameof(tasks));
+ throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks));
Contract.EndContractBlock();
Task[] tasksCopy = new Task[tasks.Length];
@@ -3027,7 +3029,7 @@ namespace System.Threading.Tasks
tasksCopy[i] = tasks[i];
if (tasksCopy[i] == null)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks));
+ throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks));
}
return tasksCopy;
@@ -3038,7 +3040,7 @@ namespace System.Threading.Tasks
if (tasks == null)
throw new ArgumentNullException(nameof(tasks));
if (tasks.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"), nameof(tasks));
+ throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, nameof(tasks));
Contract.EndContractBlock();
Task<TResult>[] tasksCopy = new Task<TResult>[tasks.Length];
@@ -3047,7 +3049,7 @@ namespace System.Threading.Tasks
tasksCopy[i] = tasks[i];
if (tasksCopy[i] == null)
- throw new ArgumentException(Environment.GetResourceString("Task_MultiTaskContinuation_NullTask"), nameof(tasks));
+ throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, nameof(tasks));
}
return tasksCopy;
@@ -3066,7 +3068,7 @@ namespace System.Threading.Tasks
const TaskContinuationOptions illegalMask = TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.LongRunning;
if ((continuationOptions & illegalMask) == illegalMask)
{
- throw new ArgumentOutOfRangeException(nameof(continuationOptions), Environment.GetResourceString("Task_ContinueWith_ESandLR"));
+ throw new ArgumentOutOfRangeException(nameof(continuationOptions), SR.Task_ContinueWith_ESandLR);
}
// Check that no nonsensical options are specified.
@@ -3085,9 +3087,8 @@ namespace System.Threading.Tasks
// Check that no "fire" options are specified.
if ((continuationOptions & NotOnAny) != 0)
- throw new ArgumentOutOfRangeException(nameof(continuationOptions), Environment.GetResourceString("Task_MultiTaskContinuation_FireOptions"));
+ throw new ArgumentOutOfRangeException(nameof(continuationOptions), SR.Task_MultiTaskContinuation_FireOptions);
Contract.EndContractBlock();
}
}
-
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
index d68c3fedc4..45d398f0eb 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
@@ -11,6 +11,7 @@
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// Disable the "reference to volatile field not treated as volatile" error.
#pragma warning disable 0420
+
using System;
using System.Collections.Generic;
using System.Globalization;
@@ -23,7 +24,6 @@ using System.Runtime.CompilerServices;
namespace System.Threading.Tasks
{
-
/// <summary>
/// Represents an abstract scheduler for tasks.
/// </summary>
@@ -46,7 +46,7 @@ namespace System.Threading.Tasks
//
// User Provided Methods and Properties
//
-
+
/// <summary>
/// Queues a <see cref="T:System.Threading.Tasks.Task">Task</see> to the scheduler.
/// </summary>
@@ -168,7 +168,7 @@ namespace System.Threading.Tasks
//
// Internal overridable methods
//
-
+
/// <summary>
/// Attempts to execute the target task synchronously.
@@ -183,14 +183,14 @@ namespace System.Threading.Tasks
// Do not inline TaskCompletionSource-style (a.k.a. "promise") tasks.
// No need to attempt inlining if the task body was already run (i.e. either TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bits set)
TaskScheduler ets = task.ExecutingTaskScheduler;
-
+
// Delegate cross-scheduler inlining requests to target scheduler
- if(ets != this && ets !=null) return ets.TryRunInline(task, taskWasPreviouslyQueued);
+ if (ets != this && ets != null) return ets.TryRunInline(task, taskWasPreviouslyQueued);
StackGuard currentStackGuard;
- if( (ets == null) ||
+ if ((ets == null) ||
(task.m_action == null) ||
- task.IsDelegateInvoked ||
+ task.IsDelegateInvoked ||
task.IsCanceled ||
(currentStackGuard = Task.CurrentStackGuard).TryBeginInliningScope() == false)
{
@@ -203,7 +203,10 @@ namespace System.Threading.Tasks
bool bInlined = false;
try
{
- task.FireTaskScheduledIfNeeded(this);
+ if (TplEtwProvider.Log.IsEnabled())
+ {
+ task.FireTaskScheduledIfNeeded(this);
+ }
bInlined = TryExecuteTaskInline(task, taskWasPreviouslyQueued);
}
finally
@@ -213,9 +216,9 @@ namespace System.Threading.Tasks
// If the custom scheduler returned true, we should either have the TASK_STATE_DELEGATE_INVOKED or TASK_STATE_CANCELED bit set
// Otherwise the scheduler is buggy
- if (bInlined && !(task.IsDelegateInvoked || task.IsCanceled))
+ if (bInlined && !(task.IsDelegateInvoked || task.IsCanceled))
{
- throw new InvalidOperationException(Environment.GetResourceString("TaskScheduler_InconsistentStateAfterTryExecuteTaskInline"));
+ throw new InvalidOperationException(SR.TaskScheduler_InconsistentStateAfterTryExecuteTaskInline);
}
return bInlined;
@@ -237,7 +240,7 @@ namespace System.Threading.Tasks
/// Notifies the scheduler that a work item has made progress.
/// </summary>
internal virtual void NotifyWorkItemProgress()
- {
+ {
}
/// <summary>
@@ -256,7 +259,10 @@ namespace System.Threading.Tasks
{
Contract.Requires(task != null);
- task.FireTaskScheduledIfNeeded(this);
+ if (TplEtwProvider.Log.IsEnabled())
+ {
+ task.FireTaskScheduledIfNeeded(this);
+ }
this.QueueTask(task);
}
@@ -269,7 +275,7 @@ namespace System.Threading.Tasks
// The global container that keeps track of TaskScheduler instances for debugging purposes.
private static ConditionalWeakTable<TaskScheduler, object> s_activeTaskSchedulers;
-
+
// An AppDomain-wide default manager.
private static readonly TaskScheduler s_defaultTaskScheduler = new ThreadPoolTaskScheduler();
@@ -316,7 +322,7 @@ namespace System.Threading.Tasks
/// <summary>
/// Gets the default <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instance.
/// </summary>
- public static TaskScheduler Default
+ public static TaskScheduler Default
{
get
{
@@ -331,7 +337,7 @@ namespace System.Threading.Tasks
/// <remarks>
/// When not called from within a task, <see cref="Current"/> will return the <see cref="Default"/> scheduler.
/// </remarks>
- public static TaskScheduler Current
+ public static TaskScheduler Current
{
get
{
@@ -352,7 +358,7 @@ namespace System.Threading.Tasks
get
{
Task currentTask = Task.InternalCurrent;
- return ( (currentTask != null)
+ return ((currentTask != null)
&& ((currentTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0)
) ? currentTask.ExecutingTaskScheduler : null;
}
@@ -398,7 +404,7 @@ namespace System.Threading.Tasks
{
newId = Interlocked.Increment(ref s_taskSchedulerIdCounter);
} while (newId == 0);
-
+
Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0);
}
@@ -437,10 +443,10 @@ namespace System.Threading.Tasks
{
if (task.ExecutingTaskScheduler != this)
{
- throw new InvalidOperationException(Environment.GetResourceString("TaskScheduler_ExecuteTask_WrongTaskScheduler"));
+ throw new InvalidOperationException(SR.TaskScheduler_ExecuteTask_WrongTaskScheduler);
}
- return task.ExecuteEntry(true);
+ return task.ExecuteEntry();
}
////////////////////////////////////////////////////////////
@@ -477,12 +483,12 @@ namespace System.Threading.Tasks
lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value;
}
}
-
-
+
+
////////////////////////////////////////////////////////////
//
// Internal methods
@@ -588,19 +594,18 @@ namespace System.Threading.Tasks
m_taskScheduler = scheduler;
}
- // returns the scheduler’s Id
+ // returns the scheduler�s Id
public Int32 Id
- {
- get { return m_taskScheduler.Id; }
+ {
+ get { return m_taskScheduler.Id; }
}
- // returns the scheduler’s GetScheduledTasks
- public IEnumerable<Task> ScheduledTasks
+ // returns the scheduler�s GetScheduledTasks
+ public IEnumerable<Task> ScheduledTasks
{
get { return m_taskScheduler.GetScheduledTasks(); }
}
}
-
}
@@ -626,11 +631,10 @@ namespace System.Threading.Tasks
// make sure we have a synccontext to work with
if (synContext == null)
{
- throw new InvalidOperationException(Environment.GetResourceString("TaskScheduler_FromCurrentSynchronizationContext_NoCurrent"));
+ throw new InvalidOperationException(SR.TaskScheduler_FromCurrentSynchronizationContext_NoCurrent);
}
m_synchronizationContext = synContext;
-
}
/// <summary>
@@ -684,16 +688,7 @@ namespace System.Threading.Tasks
}
// preallocated SendOrPostCallback delegate
- private static SendOrPostCallback s_postCallback = new SendOrPostCallback(PostCallback);
-
- // this is where the actual task invocation occures
- private static void PostCallback(object obj)
- {
- Task task = (Task) obj;
-
- // calling ExecuteEntry with double execute check enabled because a user implemented SynchronizationContext could be buggy
- task.ExecuteEntry(true);
- }
+ private static readonly SendOrPostCallback s_postCallback = s => ((Task)s).ExecuteEntry(); // with double-execute check because SC could be buggy
}
/// <summary>
@@ -728,7 +723,7 @@ namespace System.Threading.Tasks
/// Gets whether this exception has been marked as "observed."
/// </summary>
public bool Observed { get { return m_observed; } }
-
+
/// <summary>
/// The Exception that went unobserved.
/// </summary>
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs b/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs
deleted file mode 100644
index 1d85e49342..0000000000
--- a/src/mscorlib/src/System/Threading/Tasks/TaskSchedulerException.cs
+++ /dev/null
@@ -1,81 +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.
-
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// An exception for task schedulers.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
-using System;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-
-namespace System.Threading.Tasks
-{
-
- /// <summary>
- /// Represents an exception used to communicate an invalid operation by a
- /// <see cref="T:System.Threading.Tasks.TaskScheduler"/>.
- /// </summary>
- [Serializable]
- public class TaskSchedulerException : Exception
- {
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskSchedulerException"/> class.
- /// </summary>
- public TaskSchedulerException() : base(Environment.GetResourceString("TaskSchedulerException_ctor_DefaultMessage")) //
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskSchedulerException"/>
- /// class with a specified error message.
- /// </summary>
- /// <param name="message">The error message that explains the reason for the exception.</param>
- public TaskSchedulerException(string message) : base(message)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskSchedulerException"/>
- /// class using the default error message and a reference to the inner exception that is the cause of
- /// this exception.
- /// </summary>
- /// <param name="innerException">The exception that is the cause of the current exception.</param>
- public TaskSchedulerException(Exception innerException)
- : base(Environment.GetResourceString("TaskSchedulerException_ctor_DefaultMessage"), innerException)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskSchedulerException"/>
- /// class with a specified error message and a reference to the inner exception that is the cause of
- /// this exception.
- /// </summary>
- /// <param name="message">The error message that explains the reason for the exception.</param>
- /// <param name="innerException">The exception that is the cause of the current exception.</param>
- public TaskSchedulerException(string message, Exception innerException) : base(message, innerException)
- {
- }
-
- /// <summary>
- /// Initializes a new instance of the <see cref="T:System.Threading.Tasks.TaskSchedulerException"/>
- /// class with serialized data.
- /// </summary>
- /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds
- /// the serialized object data about the exception being thrown.</param>
- /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that
- /// contains contextual information about the source or destination. </param>
- protected TaskSchedulerException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
-
-
- }
-
-}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
index 90743aeec5..fdd62c95f5 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskToApm.cs
@@ -60,7 +60,7 @@ namespace System.Threading.Tasks
{
// Asynchronous completion
asyncResult = task.AsyncState == state ? (IAsyncResult)task : new TaskWrapperAsyncResult(task, state, completedSynchronously: false);
- if (callback != null)
+ if (callback != null)
InvokeCallbackWhenTaskCompletes(task, callback, asyncResult);
}
return asyncResult;
@@ -129,7 +129,7 @@ namespace System.Threading.Tasks
// We use OnCompleted rather than ContinueWith in order to avoid running synchronously
// if the task has already completed by the time we get here. This is separated out into
// its own method currently so that we only pay for the closure if necessary.
- antecedent.ConfigureAwait(continueOnCapturedContext:false)
+ antecedent.ConfigureAwait(continueOnCapturedContext: false)
.GetAwaiter()
.OnCompleted(() => callback(asyncResult));
@@ -167,7 +167,7 @@ namespace System.Threading.Tasks
/// <param name="task">The Task to wrap.</param>
/// <param name="state">The new AsyncState value</param>
/// <param name="completedSynchronously">The new CompletedSynchronously value.</param>
- internal TaskWrapperAsyncResult(Task task, object state, bool completedSynchronously)
+ internal TaskWrapperAsyncResult(Task task, object state, bool completedSynchronously)
{
Contract.Requires(task != null);
Contract.Requires(!completedSynchronously || task.IsCompleted, "If completedSynchronously is true, the task must be completed.");
diff --git a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
index 5c6ca9bb76..e69a89fe66 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ThreadPoolTaskScheduler.cs
@@ -23,7 +23,7 @@ namespace System.Threading.Tasks
/// <summary>
/// An implementation of TaskScheduler that uses the ThreadPool scheduler
/// </summary>
- internal sealed class ThreadPoolTaskScheduler: TaskScheduler
+ internal sealed class ThreadPoolTaskScheduler : TaskScheduler
{
/// <summary>
/// Constructs a new ThreadPool task scheduler object
@@ -34,15 +34,7 @@ namespace System.Threading.Tasks
}
// static delegate for threads allocated to handle LongRunning tasks.
- private static readonly ParameterizedThreadStart s_longRunningThreadWork = new ParameterizedThreadStart(LongRunningThreadWork);
-
- private static void LongRunningThreadWork(object obj)
- {
- Contract.Requires(obj != null, "TaskScheduler.LongRunningThreadWork: obj is null");
- Task t = obj as Task;
- Debug.Assert(t != null, "TaskScheduler.LongRunningThreadWork: t is null");
- t.ExecuteEntry(false);
- }
+ private static readonly ParameterizedThreadStart s_longRunningThreadWork = s => ((Task)s).ExecuteEntryUnsafe();
/// <summary>
/// Schedules a task to the ThreadPool.
@@ -64,11 +56,11 @@ namespace System.Threading.Tasks
ThreadPool.UnsafeQueueCustomWorkItem(task, forceToGlobalQueue);
}
}
-
+
/// <summary>
/// This internal function will do this:
/// (1) If the task had previously been queued, attempt to pop it and return false if that fails.
- /// (2) Propagate the return value from Task.ExecuteEntry() back to the caller.
+ /// (2) Return whether the task is executed
///
/// IMPORTANT NOTE: TryExecuteTaskInline will NOT throw task exceptions itself. Any wait code path using this function needs
/// to account for exceptions that need to be propagated, and throw themselves accordingly.
@@ -79,19 +71,17 @@ namespace System.Threading.Tasks
if (taskWasPreviouslyQueued && !ThreadPool.TryPopCustomWorkItem(task))
return false;
- // Propagate the return value of Task.ExecuteEntry()
- bool rval = false;
try
{
- rval = task.ExecuteEntry(false); // handles switching Task.Current etc.
+ task.ExecuteEntryUnsafe(); // handles switching Task.Current etc.
}
finally
{
// Only call NWIP() if task was previously queued
- if(taskWasPreviouslyQueued) NotifyWorkItemProgress();
+ if (taskWasPreviouslyQueued) NotifyWorkItemProgress();
}
- return rval;
+ return true;
}
protected internal override bool TryDequeue(Task task)
diff --git a/src/mscorlib/src/System/Threading/Tasks/future.cs b/src/mscorlib/src/System/Threading/Tasks/future.cs
index 15136f12bf..26c2388e6b 100644
--- a/src/mscorlib/src/System/Threading/Tasks/future.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/future.cs
@@ -82,20 +82,20 @@ namespace System.Threading.Tasks
internal static readonly Func<Task<Task>, Task<TResult>> TaskWhenAnyCast = completed => (Task<TResult>)completed.Result;
// Construct a promise-style task without any options.
- internal Task() :
+ internal Task() :
base()
{
}
// Construct a promise-style task with state and options.
internal Task(object state, TaskCreationOptions options) :
- base(state, options, promiseStyle:true)
+ base(state, options, promiseStyle: true)
{
}
// Construct a pre-completed Task<TResult>
- internal Task(TResult result) :
+ internal Task(TResult result) :
base(false, TaskCreationOptions.None, default(CancellationToken))
{
m_result = result;
@@ -372,9 +372,9 @@ namespace System.Threading.Tasks
// Debugger support
private string DebuggerDisplayResultDescription
{
- get
+ get
{
- return IsRanToCompletion ? "" + m_result : Environment.GetResourceString("TaskT_DebuggerNoResult");
+ return IsRanToCompletion ? "" + m_result : SR.TaskT_DebuggerNoResult;
}
}
@@ -392,7 +392,6 @@ namespace System.Threading.Tasks
// internal helper function breaks out logic used by TaskCompletionSource
internal bool TrySetResult(TResult result)
{
- if (IsCompleted) return false;
Debug.Assert(m_action == null, "Task<T>.TrySetResult(): non-null m_action");
// "Reserve" the completion for this task, while making sure that: (1) No prior reservation
@@ -413,12 +412,13 @@ namespace System.Threading.Tasks
// and which can be summarized more concisely with the following snippet from
// FinishStageTwo, omitting everything that doesn't pertain to TrySetResult.
Interlocked.Exchange(ref m_stateFlags, m_stateFlags | TASK_STATE_RAN_TO_COMPLETION);
-
- var cp = m_contingentProperties;
- if (cp != null) cp.SetCompleted();
-
- FinishStageThree();
-
+ ContingentProperties props = m_contingentProperties;
+ if (props != null)
+ {
+ NotifyParentIfPotentiallyAttachedTask();
+ props.SetCompleted();
+ }
+ FinishContinuations();
return true;
}
@@ -441,7 +441,7 @@ namespace System.Threading.Tasks
bool success = TrySetResult(result);
// Nobody else has had a chance to complete this Task yet, so we should succeed.
- Debug.Assert(success);
+ Debug.Assert(success);
}
else
{
@@ -477,7 +477,7 @@ namespace System.Threading.Tasks
{
Debug.Assert(!IsWaitNotificationEnabledOrNotRanToCompletion,
"Should only be used when the task completed successfully and there's no wait notification enabled");
- return m_result;
+ return m_result;
}
}
@@ -539,7 +539,6 @@ namespace System.Threading.Tasks
}
return returnValue;
-
}
// internal helper function breaks out logic used by TaskCompletionSource and AsyncMethodBuilder
@@ -879,7 +878,7 @@ namespace System.Threading.Tasks
/// <exception cref="T:System.ObjectDisposedException">The provided <see cref="System.Threading.CancellationToken">CancellationToken</see>
/// has already been disposed.
/// </exception>
- public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state,CancellationToken cancellationToken)
+ public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, CancellationToken cancellationToken)
{
return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None);
}
@@ -942,7 +941,7 @@ namespace System.Threading.Tasks
/// The <paramref name="continuationOptions"/> argument specifies an invalid value for <see
/// cref="T:System.Threading.Tasks.TaskContinuationOptions">TaskContinuationOptions</see>.
/// </exception>
- public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state,TaskContinuationOptions continuationOptions)
+ public Task ContinueWith(Action<Task<TResult>, Object> continuationAction, Object state, TaskContinuationOptions continuationOptions)
{
return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions);
}
@@ -1014,7 +1013,7 @@ namespace System.Threading.Tasks
out internalOptions);
Task continuationTask = new ContinuationTaskFromResultTask<TResult>(
- this, continuationAction, state,
+ this, continuationAction, state,
creationOptions, internalOptions
);
@@ -1229,7 +1228,7 @@ namespace System.Threading.Tasks
out creationOptions,
out internalOptions);
- Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult,TNewResult>(
+ Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult, TNewResult>(
this, continuationFunction, null,
creationOptions, internalOptions
);
@@ -1452,7 +1451,7 @@ namespace System.Threading.Tasks
out creationOptions,
out internalOptions);
- Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult,TNewResult>(
+ Task<TNewResult> continuationFuture = new ContinuationResultTaskFromResultTask<TResult, TNewResult>(
this, continuationFunction, state,
creationOptions, internalOptions
);
@@ -1467,7 +1466,7 @@ namespace System.Threading.Tasks
#endregion
#endregion
-
+
/// <summary>
/// Subscribes an <see cref="IObserver{TResult}"/> to receive notification of the final state of this <see cref="Task{TResult}"/>.
/// </summary>
@@ -1553,7 +1552,5 @@ namespace System.Threading.Tasks
public int Id { get { return m_task.Id; } }
public bool CancellationPending { get { return (m_task.Status == TaskStatus.WaitingToRun) && m_task.CancellationToken.IsCancellationRequested; } }
public TaskStatus Status { get { return m_task.Status; } }
-
-
}
}
diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs
index d28002729a..70a5d06f7a 100644
--- a/src/mscorlib/src/System/Threading/Thread.cs
+++ b/src/mscorlib/src/System/Threading/Thread.cs
@@ -14,7 +14,8 @@
using Internal.Runtime.Augments;
-namespace System.Threading {
+namespace System.Threading
+{
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
@@ -33,11 +34,9 @@ namespace System.Threading {
internal class ThreadHelper
{
- static ThreadHelper() {}
-
- Delegate _start;
- Object _startArg = null;
- ExecutionContext _executionContext = null;
+ private Delegate _start;
+ private Object _startArg = null;
+ private ExecutionContext _executionContext = null;
internal ThreadHelper(Delegate start)
{
_start = start;
@@ -49,7 +48,7 @@ namespace System.Threading {
}
static internal ContextCallback _ccb = new ContextCallback(ThreadStart_Context);
-
+
static private void ThreadStart_Context(Object state)
{
ThreadHelper t = (ThreadHelper)state;
@@ -65,9 +64,9 @@ namespace System.Threading {
// call back helper
internal void ThreadStart(object obj)
- {
+ {
_startArg = obj;
- if (_executionContext != null)
+ if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, _ccb, (Object)this);
}
@@ -80,7 +79,7 @@ namespace System.Threading {
// call back helper
internal void ThreadStart()
{
- if (_executionContext != null)
+ if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, _ccb, (Object)this);
}
@@ -101,7 +100,7 @@ namespace System.Threading {
}
}
- public sealed class Thread : RuntimeThread
+ internal sealed class Thread : RuntimeThread
{
/*=========================================================================
** Data accessed from managed code that needs to be defined in
@@ -111,10 +110,10 @@ namespace System.Threading {
private ExecutionContext m_ExecutionContext; // this call context follows the logical thread
private SynchronizationContext m_SynchronizationContext; // On CoreCLR, this is maintained separately from ExecutionContext
- private String m_Name;
- private Delegate m_Delegate; // Delegate
+ private String m_Name;
+ private Delegate m_Delegate; // Delegate
- private Object m_ThreadStartArg;
+ private Object m_ThreadStartArg;
/*=========================================================================
** The base implementation of Thread is all native. The following fields
@@ -126,10 +125,10 @@ namespace System.Threading {
#pragma warning disable 414 // These fields are not used from managed.
// IntPtrs need to be together, and before ints, because IntPtrs are 64-bit
// fields on 64-bit platforms, where they will be sorted together.
-
- private IntPtr DONT_USE_InternalThread; // Pointer
- private int m_Priority; // INT32
- private int m_ManagedThreadId; // INT32
+
+ private IntPtr DONT_USE_InternalThread; // Pointer
+ private int m_Priority; // INT32
+ private int m_ManagedThreadId; // INT32
#pragma warning restore 414
#pragma warning restore 169
@@ -143,25 +142,12 @@ namespace System.Threading {
// with native code
// See code:#threadCultureInfo
[ThreadStatic]
- internal static CultureInfo m_CurrentCulture;
+ internal static CultureInfo m_CurrentCulture;
[ThreadStatic]
- internal static CultureInfo m_CurrentUICulture;
-
- static AsyncLocal<CultureInfo> s_asyncLocalCurrentCulture;
- static AsyncLocal<CultureInfo> s_asyncLocalCurrentUICulture;
-
- static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs<CultureInfo> args)
- {
- m_CurrentCulture = args.CurrentValue;
- }
-
- static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs<CultureInfo> args)
- {
- m_CurrentUICulture = args.CurrentValue;
- }
+ internal static CultureInfo m_CurrentUICulture;
// Adding an empty default ctor for annotation purposes
- internal Thread(){}
+ internal Thread() { }
/*=========================================================================
** Creates a new Thread object which will begin execution at
@@ -169,37 +155,45 @@ namespace System.Threading {
**
** Exceptions: ArgumentNullException if start == null.
=========================================================================*/
- public Thread(ThreadStart start) {
- if (start == null) {
+ public Thread(ThreadStart start)
+ {
+ if (start == null)
+ {
throw new ArgumentNullException(nameof(start));
}
Contract.EndContractBlock();
- SetStartHelper((Delegate)start,0); //0 will setup Thread with default stackSize
+ SetStartHelper((Delegate)start, 0); //0 will setup Thread with default stackSize
}
- internal Thread(ThreadStart start, int maxStackSize) {
- if (start == null) {
+ internal Thread(ThreadStart start, int maxStackSize)
+ {
+ if (start == null)
+ {
throw new ArgumentNullException(nameof(start));
}
if (0 > maxStackSize)
- throw new ArgumentOutOfRangeException(nameof(maxStackSize),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
- public Thread(ParameterizedThreadStart start) {
- if (start == null) {
+ public Thread(ParameterizedThreadStart start)
+ {
+ if (start == null)
+ {
throw new ArgumentNullException(nameof(start));
}
Contract.EndContractBlock();
SetStartHelper((Delegate)start, 0);
}
- internal Thread(ParameterizedThreadStart start, int maxStackSize) {
- if (start == null) {
+ internal Thread(ParameterizedThreadStart start, int maxStackSize)
+ {
+ if (start == null)
+ {
throw new ArgumentNullException(nameof(start));
}
if (0 > maxStackSize)
- throw new ArgumentOutOfRangeException(nameof(maxStackSize),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
+ throw new ArgumentOutOfRangeException(nameof(maxStackSize), SR.ArgumentOutOfRange_NeedNonNegNum);
Contract.EndContractBlock();
SetStartHelper((Delegate)start, maxStackSize);
}
@@ -224,7 +218,7 @@ namespace System.Threading {
// There are ways how to create an unitialized objects through remoting, etc. Avoid AVing in the EE by throwing a nice
// exception here.
if (thread.IsNull())
- throw new ArgumentException(null, Environment.GetResourceString("Argument_InvalidHandle"));
+ throw new ArgumentException(null, SR.Argument_InvalidHandle);
return new ThreadHandle(thread);
}
@@ -237,24 +231,24 @@ namespace System.Threading {
**
** Exceptions: ThreadStateException if the thread has already been started.
=========================================================================*/
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public new void Start()
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
Start(ref stackMark);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public new void Start(object parameter)
{
//In the case of a null delegate (second call to start on same thread)
// StartInternal method will take care of the error reporting
- if(m_Delegate is ThreadStart)
+ if (m_Delegate is ThreadStart)
{
//We expect the thread to be setup with a ParameterizedThreadStart
// if this constructor is called.
//If we got here then that wasn't the case
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ThreadWrongThreadStart"));
+ throw new InvalidOperationException(SR.InvalidOperation_ThreadWrongThreadStart);
}
m_ThreadStartArg = parameter;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
@@ -285,7 +279,7 @@ namespace System.Threading {
internal ExecutionContext ExecutionContext
{
- get { return m_ExecutionContext; }
+ get { return m_ExecutionContext; }
set { m_ExecutionContext = value; }
}
@@ -320,15 +314,15 @@ namespace System.Threading {
{
SleepInternal(millisecondsTimeout);
// Ensure we don't return to app code when the pause is underway
- if(AppDomainPauseManager.IsPaused)
+ if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
}
public static void Sleep(TimeSpan timeout)
{
long tm = (long)timeout.TotalMilliseconds;
- if (tm < -1 || tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ if (tm < -1 || tm > (long)Int32.MaxValue)
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Sleep((int)tm);
}
@@ -353,9 +347,11 @@ namespace System.Threading {
{
return YieldInternal();
}
-
- public static new Thread CurrentThread {
- get {
+
+ public static new Thread CurrentThread
+ {
+ get
+ {
Contract.Ensures(Contract.Result<Thread>() != null);
return GetCurrentThreadNative();
}
@@ -368,14 +364,14 @@ namespace System.Threading {
Debug.Assert(maxStackSize >= 0);
ThreadHelper threadStartCallBack = new ThreadHelper(start);
- if(start is ThreadStart)
+ if (start is ThreadStart)
{
SetStart(new ThreadStart(threadStartCallBack.ThreadStart), maxStackSize);
}
else
{
SetStart(new ParameterizedThreadStart(threadStartCallBack.ThreadStart), maxStackSize);
- }
+ }
}
/*=========================================================================
@@ -437,72 +433,26 @@ namespace System.Threading {
// app domain get unloaded there is a code to clean up the culture from the thread
// using the code in AppDomain::ReleaseDomainStores.
- public CultureInfo CurrentUICulture {
- get {
+ public CultureInfo CurrentUICulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
-#if FEATURE_APPX && !FEATURE_COREFX_GLOBALIZATION
- if(AppDomain.IsAppXModel()) {
- return CultureInfo.GetCultureInfoForUserPreferredLanguageInAppX() ?? GetCurrentUICultureNoAppX();
- }
- else
-#endif
- {
- return GetCurrentUICultureNoAppX();
- }
+ return CultureInfo.CurrentUICulture;
}
- set {
- if (value == null) {
- throw new ArgumentNullException(nameof(value));
- }
- Contract.EndContractBlock();
-
- //If they're trying to use a Culture with a name that we can't use in resource lookup,
- //don't even let them set it on the thread.
- CultureInfo.VerifyCultureName(value, true);
-
+ set
+ {
// If you add more pre-conditions to this method, check to see if you also need to
// add them to CultureInfo.DefaultThreadCurrentUICulture.set.
if (m_CurrentUICulture == null && m_CurrentCulture == null)
nativeInitCultureAccessors();
- if (!AppContextSwitches.NoAsyncCurrentCulture)
- {
- if (s_asyncLocalCurrentUICulture == null)
- {
- Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentUICulture), null);
- }
-
- // this one will set m_CurrentUICulture too
- s_asyncLocalCurrentUICulture.Value = value;
- }
- else
- {
- m_CurrentUICulture = value;
- }
+ CultureInfo.CurrentUICulture = value;
}
}
- internal CultureInfo GetCurrentUICultureNoAppX() {
-
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
-#if FEATURE_COREFX_GLOBALIZATION
- return CultureInfo.CurrentUICulture;
-#else
-
- // Fetch a local copy of m_CurrentUICulture to
- // avoid race conditions that malicious user can introduce
- if (m_CurrentUICulture == null) {
- CultureInfo appDomainDefaultUICulture = CultureInfo.DefaultThreadCurrentUICulture;
- return (appDomainDefaultUICulture != null ? appDomainDefaultUICulture : CultureInfo.UserDefaultUICulture);
- }
-
- return m_CurrentUICulture;
-#endif
- }
-
// This returns the exposed context for a given context ID.
// As the culture can be customized object then we cannot hold any
@@ -517,25 +467,16 @@ namespace System.Threading {
// app domain get unloaded there is a code to clean up the culture from the thread
// using the code in AppDomain::ReleaseDomainStores.
- public CultureInfo CurrentCulture {
- get {
+ public CultureInfo CurrentCulture
+ {
+ get
+ {
Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
-#if FEATURE_APPX && !FEATURE_COREFX_GLOBALIZATION
- if(AppDomain.IsAppXModel()) {
- return CultureInfo.GetCultureInfoForUserPreferredLanguageInAppX() ?? GetCurrentCultureNoAppX();
- }
- else
-#endif
- {
- return GetCurrentCultureNoAppX();
- }
+ return CultureInfo.CurrentCulture;
}
- set {
- if (null==value) {
- throw new ArgumentNullException(nameof(value));
- }
+ set
+ {
Contract.EndContractBlock();
// If you add more pre-conditions to this method, check to see if you also need to
@@ -543,39 +484,9 @@ namespace System.Threading {
if (m_CurrentCulture == null && m_CurrentUICulture == null)
nativeInitCultureAccessors();
-
- if (!AppContextSwitches.NoAsyncCurrentCulture)
- {
- if (s_asyncLocalCurrentCulture == null)
- {
- Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal<CultureInfo>(AsyncLocalSetCurrentCulture), null);
- }
- // this one will set m_CurrentCulture too
- s_asyncLocalCurrentCulture.Value = value;
- }
- else
- {
- m_CurrentCulture = value;
- }
- }
- }
-
- private CultureInfo GetCurrentCultureNoAppX() {
-
-#if FEATURE_COREFX_GLOBALIZATION
- return CultureInfo.CurrentCulture;
-#else
- Contract.Ensures(Contract.Result<CultureInfo>() != null);
-
- // Fetch a local copy of m_CurrentCulture to
- // avoid race conditions that malicious user can introduce
- if (m_CurrentCulture == null) {
- CultureInfo appDomainDefaultCulture = CultureInfo.DefaultThreadCurrentCulture;
- return (appDomainDefaultCulture != null ? appDomainDefaultCulture : CultureInfo.UserDefaultCulture);
+
+ CultureInfo.CurrentCulture = value;
}
-
- return m_CurrentCulture;
-#endif
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
@@ -616,14 +527,18 @@ namespace System.Threading {
// Retrieves the name of the thread.
//
- public new String Name {
- get {
+ public new String Name
+ {
+ get
+ {
return m_Name;
}
- set {
- lock(this) {
+ set
+ {
+ lock (this)
+ {
if (m_Name != null)
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_WriteOnce"));
+ throw new InvalidOperationException(SR.InvalidOperation_WriteOnce);
m_Name = value;
InformThreadNameChange(GetNativeHandle(), value, (value != null) ? value.Length : 0);
@@ -635,9 +550,6 @@ namespace System.Threading {
[SuppressUnmanagedCodeSecurity]
private static extern void InformThreadNameChange(ThreadHandle t, String name, int len);
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern void MemoryBarrier();
-
} // End of class Thread
// declaring a local var of this enum type and passing it by ref into a function that needs to do a
@@ -651,5 +563,4 @@ namespace System.Threading {
LookForMyCallersCaller = 2,
LookForThread = 3
}
-
}
diff --git a/src/mscorlib/src/System/Threading/ThreadAbortException.cs b/src/mscorlib/src/System/Threading/ThreadAbortException.cs
deleted file mode 100644
index 25925048bf..0000000000
--- a/src/mscorlib/src/System/Threading/ThreadAbortException.cs
+++ /dev/null
@@ -1,39 +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: An exception class which is thrown into a thread to cause it to
-** abort. This is a special non-catchable exception and results in
-** the thread's death. This is thrown by the VM only and can NOT be
-** thrown by any user thread, and subclassing this is useless.
-**
-**
-=============================================================================*/
-
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.CompilerServices;
-
- [Serializable]
- public sealed class ThreadAbortException : SystemException
- {
- private ThreadAbortException()
- : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadAbort))
- {
- SetErrorCode(__HResults.COR_E_THREADABORTED);
- }
-
- //required for serialization
- internal ThreadAbortException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
index 71c09649e2..9122df0d3e 100644
--- a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
@@ -12,29 +12,36 @@
**
**
=============================================================================*/
-namespace System.Threading {
- using System.Threading;
- using System;
- using System.Runtime.Serialization;
+using System.Threading;
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Threading
+{
[Serializable]
- public class ThreadInterruptedException : SystemException {
- public ThreadInterruptedException()
- : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted)) {
- SetErrorCode(__HResults.COR_E_THREADINTERRUPTED);
+ public class ThreadInterruptedException : SystemException
+ {
+ public ThreadInterruptedException()
+ : base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted))
+ {
+ HResult = __HResults.COR_E_THREADINTERRUPTED;
}
-
- public ThreadInterruptedException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_THREADINTERRUPTED);
+
+ public ThreadInterruptedException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_THREADINTERRUPTED;
}
-
- public ThreadInterruptedException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_THREADINTERRUPTED);
+
+ public ThreadInterruptedException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_THREADINTERRUPTED;
}
- protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base (info, context) {
+ 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 eedf6d0c81..64b8a60196 100644
--- a/src/mscorlib/src/System/Threading/ThreadLocal.cs
+++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs
@@ -36,7 +36,6 @@ namespace System.Threading
[DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")]
public class ThreadLocal<T> : IDisposable
{
-
// a delegate that returns the created value, if null the created value will be default(T)
private Func<T> m_valueFactory;
@@ -48,10 +47,10 @@ namespace System.Threading
// the ThreadLocal<T> instance.
//
[ThreadStatic]
- static LinkedSlotVolatile[] ts_slotArray;
+ private static LinkedSlotVolatile[] ts_slotArray;
[ThreadStatic]
- static FinalizationHelper ts_finalizationHelper;
+ private static FinalizationHelper ts_finalizationHelper;
// Slot ID of this ThreadLocal<> instance. We store a bitwise complement of the ID (that is ~ID), which allows us to distinguish
// between the case when ID is 0 and an incompletely initialized object, either due to a thread abort in the constructor, or
@@ -276,7 +275,7 @@ namespace System.Threading
&& id < slotArray.Length // Is the table large enough?
&& (slot = slotArray[id].Value) != null // Has a LinkedSlot object has been allocated for this ID?
&& m_initialized // Has the instance *still* not been disposed (important for a race condition with Dispose)?
- )
+ )
{
// We verified that the instance has not been disposed *after* we got a reference to the slot.
// This guarantees that we have a reference to the right slot.
@@ -324,7 +323,7 @@ namespace System.Threading
int id = ~m_idComplement;
if (id < 0)
{
- throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
+ throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
Debugger.NotifyOfCrossThreadDependency();
@@ -341,7 +340,7 @@ namespace System.Threading
if (IsValueCreated)
{
- throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_Value_RecursiveCallsToValue"));
+ throw new InvalidOperationException(SR.ThreadLocal_Value_RecursiveCallsToValue);
}
}
@@ -357,7 +356,7 @@ namespace System.Threading
// If the object has been disposed, id will be -1.
if (id < 0)
{
- throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
+ throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
// If a slot array has not been created on this thread yet, create it.
@@ -395,7 +394,7 @@ namespace System.Threading
if (!m_initialized)
{
- throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
+ throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
slot.Value = value;
@@ -417,7 +416,7 @@ namespace System.Threading
// Dispose also executes under a lock.
if (!m_initialized)
{
- throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
+ throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlot firstRealNode = m_linkedSlot.Next;
@@ -455,11 +454,11 @@ namespace System.Threading
{
if (!m_trackAllValues)
{
- throw new InvalidOperationException(Environment.GetResourceString("ThreadLocal_ValuesNotAvailable"));
+ throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable);
}
var list = GetValuesAsList(); // returns null if disposed
- if (list == null) throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
+ if (list == null) throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
return list;
}
}
@@ -512,7 +511,7 @@ namespace System.Threading
int id = ~m_idComplement;
if (id < 0)
{
- throw new ObjectDisposedException(Environment.GetResourceString("ThreadLocal_Disposed"));
+ throw new ObjectDisposedException(SR.ThreadLocal_Disposed);
}
LinkedSlotVolatile[] slotArray = ts_slotArray;
diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs
index adf0615819..0084050c43 100644
--- a/src/mscorlib/src/System/Threading/ThreadPool.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -33,8 +33,6 @@ namespace System.Threading
public static readonly int processorCount = Environment.ProcessorCount;
- public static readonly bool tpHosted = ThreadPool.IsThreadPoolHosted();
-
public static volatile bool vmTpInitialized;
public static bool enableWorkerTracking;
@@ -124,7 +122,7 @@ namespace System.Threading
private volatile int m_headIndex = START_INDEX;
private volatile int m_tailIndex = START_INDEX;
- private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking:false);
+ private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false);
public void LocalPush(IThreadPoolWorkItem obj)
{
@@ -158,7 +156,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:true);
+ m_foreignLock.Exit(useMemoryBarrier: true);
}
}
@@ -200,7 +198,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
@@ -254,7 +252,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
@@ -321,7 +319,7 @@ namespace System.Threading
finally
{
if (lockTaken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
}
}
@@ -366,7 +364,7 @@ namespace System.Threading
finally
{
if (taken)
- m_foreignLock.Exit(useMemoryBarrier:false);
+ m_foreignLock.Exit(useMemoryBarrier: false);
}
missedSteal = true;
@@ -381,10 +379,10 @@ namespace System.Threading
internal readonly ConcurrentQueue<IThreadPoolWorkItem> workItems = new ConcurrentQueue<IThreadPoolWorkItem>();
private volatile int numOutstandingThreadRequests = 0;
-
+
public ThreadPoolWorkQueue()
{
- loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool|FrameworkEventSource.Keywords.ThreadTransfer);
+ loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
}
public ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() =>
@@ -401,7 +399,7 @@ namespace System.Threading
int count = numOutstandingThreadRequests;
while (count < ThreadPoolGlobals.processorCount)
{
- int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count+1, count);
+ int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
if (prev == count)
{
ThreadPool.RequestWorkerThread();
@@ -439,7 +437,7 @@ namespace System.Threading
ThreadPoolWorkQueueThreadLocals tl = null;
if (!forceGlobal)
tl = ThreadPoolWorkQueueThreadLocals.threadLocals;
-
+
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
@@ -511,7 +509,7 @@ namespace System.Threading
workQueue.MarkThreadRequestSatisfied();
// 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);
+ workQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
//
// Assume that we're going to need another thread if this one returns to the VM. We'll set this to
@@ -603,7 +601,7 @@ namespace System.Threading
// who waits for the task to complete.
//
workItem?.MarkAborted(tae);
-
+
//
// In this case, the VM is going to request another thread on our behalf. No need to do it twice.
//
@@ -707,7 +705,7 @@ namespace System.Threading
private volatile int m_lock = 0;
internal IntPtr GetHandle() => registeredWaitHandle;
-
+
internal void SetHandle(IntPtr handle)
{
registeredWaitHandle = handle;
@@ -731,7 +729,7 @@ namespace System.Threading
}
internal bool Unregister(
- WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
+ WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
)
{
bool result = false;
@@ -745,7 +743,7 @@ namespace System.Threading
// 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
+ do
{
if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
{
@@ -807,8 +805,8 @@ namespace System.Threading
// This will result in a "leak" of sorts (since the handle will not be cleaned up)
// but the process is exiting anyway.
//
- // During AD-unload, we don’t finalize live objects until all threads have been
- // aborted out of the AD. Since these locked regions are CERs, we won’t abort them
+ // During AD-unload, we don�t finalize live objects until all threads have been
+ // aborted out of the AD. Since these locked regions are CERs, we won�t abort them
// while the lock is held. So there should be no leak on AD-unload.
//
if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
@@ -841,9 +839,10 @@ namespace System.Threading
private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject);
}
- public sealed class RegisteredWaitHandle : MarshalByRefObject {
+ public sealed class RegisteredWaitHandle : MarshalByRefObject
+ {
private readonly RegisteredWaitHandleSafe internalRegisteredWait;
-
+
internal RegisteredWaitHandle()
{
internalRegisteredWait = new RegisteredWaitHandleSafe();
@@ -851,23 +850,23 @@ namespace System.Threading
internal void SetHandle(IntPtr handle)
{
- internalRegisteredWait.SetHandle(handle);
+ internalRegisteredWait.SetHandle(handle);
}
internal void SetWaitObject(WaitHandle waitObject)
{
- internalRegisteredWait.SetWaitObject(waitObject);
+ internalRegisteredWait.SetWaitObject(waitObject);
}
// This is the only public method on this class
public bool Unregister(
- WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
+ WaitHandle waitObject // object to be notified when all callbacks to delegates have completed
)
{
return internalRegisteredWait.Unregister(waitObject);
}
}
-
+
public delegate void WaitCallback(Object state);
public delegate void WaitOrTimerCallback(Object state, bool timedOut); // signalled or timed out
@@ -905,16 +904,16 @@ namespace System.Threading
private readonly Object state;
#if DEBUG
- volatile int executed;
+ private volatile int executed;
~QueueUserWorkItemCallback()
{
Debug.Assert(
- executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
+ executed != 0 || Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload(),
"A QueueUserWorkItemCallback was never called!");
}
- void MarkExecuted(bool aborted)
+ private void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
Debug.Assert(
@@ -933,7 +932,7 @@ namespace System.Threading
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
- MarkExecuted(aborted:false);
+ MarkExecuted(aborted: false);
#endif
// call directly if it is an unsafe call OR EC flow is suppressed
if (context == null)
@@ -953,7 +952,7 @@ namespace System.Threading
#if DEBUG
// this workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem.
// This counts as being executed for our purposes.
- MarkExecuted(aborted:true);
+ MarkExecuted(aborted: true);
#endif
}
@@ -983,7 +982,7 @@ namespace System.Threading
"A QueueUserWorkItemCallbackDefaultContext was never called!");
}
- void MarkExecuted(bool aborted)
+ private void MarkExecuted(bool aborted)
{
GC.SuppressFinalize(this);
Debug.Assert(
@@ -1001,7 +1000,7 @@ namespace System.Threading
void IThreadPoolWorkItem.ExecuteWorkItem()
{
#if DEBUG
- MarkExecuted(aborted:false);
+ MarkExecuted(aborted: false);
#endif
ExecutionContext.Run(ExecutionContext.Default, ccb, this);
}
@@ -1011,7 +1010,7 @@ namespace System.Threading
#if DEBUG
// this workitem didn't execute because we got a ThreadAbortException prior to the call to ExecuteWorkItem.
// This counts as being executed for our purposes.
- MarkExecuted(aborted:true);
+ MarkExecuted(aborted: true);
#endif
}
@@ -1029,9 +1028,9 @@ namespace System.Threading
internal class _ThreadPoolWaitOrTimerCallback
{
- WaitOrTimerCallback _waitOrTimerCallback;
- ExecutionContext _executionContext;
- Object _state;
+ private WaitOrTimerCallback _waitOrTimerCallback;
+ private ExecutionContext _executionContext;
+ private Object _state;
private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t);
private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f);
@@ -1046,23 +1045,23 @@ namespace System.Threading
_executionContext = ExecutionContext.Capture();
}
}
-
+
private static void WaitOrTimerCallback_Context_t(Object state) =>
- WaitOrTimerCallback_Context(state, timedOut:true);
+ WaitOrTimerCallback_Context(state, timedOut: true);
private static void WaitOrTimerCallback_Context_f(Object state) =>
- WaitOrTimerCallback_Context(state, timedOut:false);
+ WaitOrTimerCallback_Context(state, timedOut: false);
private static void WaitOrTimerCallback_Context(Object state, bool timedOut)
{
_ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
helper._waitOrTimerCallback(helper._state, timedOut);
}
-
+
// call back helper
internal static void PerformWaitOrTimerCallback(Object state, bool timedOut)
{
- _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
+ _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state;
Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!");
// call directly if it is an unsafe call OR EC flow is suppressed
if (helper._executionContext == null)
@@ -1074,15 +1073,14 @@ namespace System.Threading
{
ExecutionContext.Run(helper._executionContext, timedOut ? _ccbt : _ccbf, helper);
}
- }
-
+ }
}
[CLSCompliant(false)]
unsafe public delegate void IOCompletionCallback(uint errorCode, // Error code
uint numBytes, // No. of bytes transferred
NativeOverlapped* pOVERLAP // ptr to OVERLAP structure
- );
+ );
public static class ThreadPool
{
@@ -1112,42 +1110,42 @@ namespace System.Threading
}
[CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- uint millisecondsTimeOutInterval,
- bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ uint millisecondsTimeOutInterval,
+ bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true);
}
[CLSCompliant(false)]
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- uint millisecondsTimeOutInterval,
- bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ uint millisecondsTimeOutInterval,
+ bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false);
}
private static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- uint millisecondsTimeOutInterval,
- bool executeOnlyOnce, // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ uint millisecondsTimeOutInterval,
+ bool executeOnlyOnce, // NOTE: we do not allow other options that allow the callback to be queued as an APC
ref StackCrawlMark stackMark,
- bool compressStack
+ bool compressStack
)
{
RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle();
@@ -1160,7 +1158,7 @@ namespace System.Threading
// this could occur if callback were to fire before SetWaitObject does its addref
registeredWaitHandle.SetWaitObject(waitObject);
IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative(waitObject,
- state,
+ state,
millisecondsTimeOutInterval,
executeOnlyOnce,
registeredWaitHandle,
@@ -1176,104 +1174,104 @@ namespace System.Threading
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- int millisecondsTimeOutInterval,
- bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ int millisecondsTimeOutInterval,
+ bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- int millisecondsTimeOutInterval,
- bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ int millisecondsTimeOutInterval,
+ bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle RegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
+ WaitHandle waitObject,
WaitOrTimerCallback callBack,
- Object state,
- long millisecondsTimeOutInterval,
- bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ Object state,
+ long millisecondsTimeOutInterval,
+ bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,true);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, true);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( // throws RegisterWaitException
- WaitHandle waitObject,
+ WaitHandle waitObject,
WaitOrTimerCallback callBack,
- Object state,
- long millisecondsTimeOutInterval,
- bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
+ Object state,
+ long millisecondsTimeOutInterval,
+ bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC
)
{
if (millisecondsTimeOutInterval < -1)
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)millisecondsTimeOutInterval,executeOnlyOnce,ref stackMark,false);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)millisecondsTimeOutInterval, executeOnlyOnce, ref stackMark, false);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle RegisterWaitForSingleObject(
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- TimeSpan timeout,
- bool executeOnlyOnce
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ TimeSpan timeout,
+ bool executeOnlyOnce
)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
- if (tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
+ if (tm > (long)Int32.MaxValue)
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,true);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, ref stackMark, true);
}
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(
- WaitHandle waitObject,
- WaitOrTimerCallback callBack,
- Object state,
- TimeSpan timeout,
- bool executeOnlyOnce
+ WaitHandle waitObject,
+ WaitOrTimerCallback callBack,
+ Object state,
+ TimeSpan timeout,
+ bool executeOnlyOnce
)
{
long tm = (long)timeout.TotalMilliseconds;
if (tm < -1)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
- if (tm > (long) Int32.MaxValue)
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
+ if (tm > (long)Int32.MaxValue)
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal);
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RegisterWaitForSingleObject(waitObject,callBack,state,(UInt32)tm,executeOnlyOnce,ref stackMark,false);
+ return RegisterWaitForSingleObject(waitObject, callBack, state, (UInt32)tm, executeOnlyOnce, ref stackMark, false);
}
public static bool QueueUserWorkItem(WaitCallback callBack) =>
@@ -1428,7 +1426,7 @@ namespace System.Threading
EnsureVMInitializedCore(); // separate out to help with inlining
}
}
-
+
private static void EnsureVMInitializedCore()
{
ThreadPool.InitializeVMTp(ref ThreadPoolGlobals.enableWorkerTracking);
@@ -1436,7 +1434,7 @@ namespace System.Threading
}
// Native methods:
-
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads);
@@ -1468,22 +1466,19 @@ namespace System.Threading
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void NotifyWorkItemProgressNative();
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern bool IsThreadPoolHosted();
-
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void InitializeVMTp(ref bool enableWorkerTracking);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern IntPtr RegisterWaitForSingleObjectNative(
- WaitHandle waitHandle,
- Object state,
- uint timeOutInterval,
- bool executeOnlyOnce,
- RegisteredWaitHandle registeredWaitHandle,
- ref StackCrawlMark stackMark,
- bool compressStack
+ private static extern IntPtr RegisterWaitForSingleObjectNative(
+ WaitHandle waitHandle,
+ Object state,
+ uint timeOutInterval,
+ bool executeOnlyOnce,
+ RegisteredWaitHandle registeredWaitHandle,
+ ref StackCrawlMark stackMark,
+ bool compressStack
);
@@ -1497,15 +1492,17 @@ namespace System.Threading
{
if (osHandle == null)
throw new ArgumentNullException(nameof(osHandle));
-
+
bool ret = false;
bool mustReleaseSafeHandle = false;
RuntimeHelpers.PrepareConstrainedRegions();
- try {
+ try
+ {
osHandle.DangerousAddRef(ref mustReleaseSafeHandle);
ret = BindIOCompletionCallbackNative(osHandle.DangerousGetHandle());
}
- finally {
+ finally
+ {
if (mustReleaseSafeHandle)
osHandle.DangerousRelease();
}
diff --git a/src/mscorlib/src/System/Threading/ThreadPriority.cs b/src/mscorlib/src/System/Threading/ThreadPriority.cs
deleted file mode 100644
index 6303c2fd94..0000000000
--- a/src/mscorlib/src/System/Threading/ThreadPriority.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: Enums for the priorities of a Thread
-**
-**
-=============================================================================*/
-
-namespace System.Threading {
- using System.Threading;
-
- [Serializable]
- public enum ThreadPriority
- {
- /*=========================================================================
- ** Constants for thread priorities.
- =========================================================================*/
- Lowest = 0,
- BelowNormal = 1,
- Normal = 2,
- AboveNormal = 3,
- Highest = 4
-
- }
-}
diff --git a/src/mscorlib/src/System/Threading/ThreadStart.cs b/src/mscorlib/src/System/Threading/ThreadStart.cs
deleted file mode 100644
index e4beddcd75..0000000000
--- a/src/mscorlib/src/System/Threading/ThreadStart.cs
+++ /dev/null
@@ -1,23 +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 a Delegate which defines the start method
-** for starting a thread. That method must match this delegate.
-**
-**
-=============================================================================*/
-
-namespace System.Threading {
- using System.Threading;
-
- // Define the delegate
- // NOTE: If you change the signature here, there is code in COMSynchronization
- // that invokes this delegate in native.
- public delegate void ThreadStart();
-}
diff --git a/src/mscorlib/src/System/Threading/ThreadStartException.cs b/src/mscorlib/src/System/Threading/ThreadStartException.cs
deleted file mode 100644
index 33fb460b3d..0000000000
--- a/src/mscorlib/src/System/Threading/ThreadStartException.cs
+++ /dev/null
@@ -1,37 +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.
-
-//
-
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
-
- [Serializable]
- public sealed class ThreadStartException : SystemException
- {
- private ThreadStartException()
- : base(Environment.GetResourceString("Arg_ThreadStartException"))
- {
- SetErrorCode(__HResults.COR_E_THREADSTART);
- }
-
- private ThreadStartException(Exception reason)
- : base(Environment.GetResourceString("Arg_ThreadStartException"), reason)
- {
- SetErrorCode(__HResults.COR_E_THREADSTART);
- }
-
- //required for serialization
- internal ThreadStartException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- }
-
- }
-}
-
-
diff --git a/src/mscorlib/src/System/Threading/ThreadState.cs b/src/mscorlib/src/System/Threading/ThreadState.cs
deleted file mode 100644
index 2d953f384a..0000000000
--- a/src/mscorlib/src/System/Threading/ThreadState.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: Enum to represent the different thread states
-**
-**
-=============================================================================*/
-
-namespace System.Threading {
-
-[Serializable]
-[Flags]
- public enum ThreadState
- {
- /*=========================================================================
- ** Constants for thread states.
- =========================================================================*/
- Running = 0,
- StopRequested = 1,
- SuspendRequested = 2,
- Background = 4,
- Unstarted = 8,
- Stopped = 16,
- WaitSleepJoin = 32,
- Suspended = 64,
- AbortRequested = 128,
- Aborted = 256
- }
-}
diff --git a/src/mscorlib/src/System/Threading/ThreadStateException.cs b/src/mscorlib/src/System/Threading/ThreadStateException.cs
deleted file mode 100644
index 97c03ce06c..0000000000
--- a/src/mscorlib/src/System/Threading/ThreadStateException.cs
+++ /dev/null
@@ -1,40 +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: An exception class to indicate that the Thread class is in an
-** invalid state for the method.
-**
-**
-=============================================================================*/
-
-namespace System.Threading {
- using System;
- using System.Runtime.Serialization;
- [Serializable]
- public class ThreadStateException : SystemException {
- public ThreadStateException()
- : base(Environment.GetResourceString("Arg_ThreadStateException")) {
- SetErrorCode(__HResults.COR_E_THREADSTATE);
- }
-
- public ThreadStateException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_THREADSTATE);
- }
-
- public ThreadStateException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_THREADSTATE);
- }
-
- protected ThreadStateException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-
-}
diff --git a/src/mscorlib/src/System/Threading/Timeout.cs b/src/mscorlib/src/System/Threading/Timeout.cs
deleted file mode 100644
index 80bdbccf4e..0000000000
--- a/src/mscorlib/src/System/Threading/Timeout.cs
+++ /dev/null
@@ -1,19 +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.
-
-namespace System.Threading {
- using System.Threading;
- using System;
- // A constant used by methods that take a timeout (Object.Wait, Thread.Sleep
- // etc) to indicate that no timeout should occur.
- //
- public static class Timeout
- {
- public static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, Timeout.Infinite);
-
- public const int Infinite = -1;
- internal const uint UnsignedInfinite = unchecked((uint)-1);
- }
-
-}
diff --git a/src/mscorlib/src/System/Threading/Timer.cs b/src/mscorlib/src/System/Threading/Timer.cs
index 93d2922799..960f815d64 100644
--- a/src/mscorlib/src/System/Threading/Timer.cs
+++ b/src/mscorlib/src/System/Threading/Timer.cs
@@ -4,7 +4,7 @@
//
-namespace System.Threading
+namespace System.Threading
{
using System;
using System.Security;
@@ -19,7 +19,7 @@ namespace System.Threading
using Microsoft.Win32.SafeHandles;
-
+
public delegate void TimerCallback(Object state);
//
@@ -43,12 +43,12 @@ namespace System.Threading
//
// Note that all instance methods of this class require that the caller hold a lock on TimerQueue.Instance.
//
- class TimerQueue
+ internal class TimerQueue
{
#region singleton pattern implementation
// The one-and-only TimerQueue for the AppDomain.
- static TimerQueue s_queue = new TimerQueue();
+ private static TimerQueue s_queue = new TimerQueue();
public static TimerQueue Instance
{
@@ -100,7 +100,7 @@ namespace System.Threading
//
// We use a SafeHandle to ensure that the native timer is destroyed when the AppDomain is unloaded.
//
- class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
+ private class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
{
public AppDomainTimerSafeHandle()
: base(true)
@@ -113,11 +113,11 @@ namespace System.Threading
}
}
- AppDomainTimerSafeHandle m_appDomainTimer;
+ private AppDomainTimerSafeHandle m_appDomainTimer;
- bool m_isAppDomainTimerScheduled;
- int m_currentAppDomainTimerStartTicks;
- uint m_currentAppDomainTimerDuration;
+ private bool m_isAppDomainTimerScheduled;
+ private int m_currentAppDomainTimerStartTicks;
+ private uint m_currentAppDomainTimerDuration;
private bool EnsureAppDomainTimerFiresBy(uint requestedDuration)
{
@@ -145,13 +145,13 @@ namespace System.Threading
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
- if(m_pauseTicks != 0)
+ if (m_pauseTicks != 0)
{
Debug.Assert(!m_isAppDomainTimerScheduled);
Debug.Assert(m_appDomainTimer == null);
return true;
}
-
+
if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid)
{
Debug.Assert(!m_isAppDomainTimerScheduled);
@@ -195,15 +195,15 @@ namespace System.Threading
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
+ private static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
+ private static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- static extern bool DeleteAppDomainTimer(IntPtr handle);
+ private static extern bool DeleteAppDomainTimer(IntPtr handle);
#endregion
@@ -212,10 +212,10 @@ namespace System.Threading
//
// The list of timers
//
- TimerQueueTimer m_timers;
+ private TimerQueueTimer m_timers;
- volatile int m_pauseTicks = 0; // Time when Pause was called
+ private volatile int m_pauseTicks = 0; // Time when Pause was called
//
@@ -386,7 +386,7 @@ namespace System.Threading
//
// A timer in our TimerQueue.
//
- sealed class TimerQueueTimer
+ internal sealed class TimerQueueTimer
{
//
// All fields of this class are protected by a lock on TimerQueue.Instance.
@@ -414,9 +414,9 @@ namespace System.Threading
//
// Info about the user's callback
//
- readonly TimerCallback m_timerCallback;
- readonly Object m_state;
- readonly ExecutionContext m_executionContext;
+ private readonly TimerCallback m_timerCallback;
+ private readonly Object m_state;
+ private readonly ExecutionContext m_executionContext;
//
@@ -426,9 +426,9 @@ namespace System.Threading
// m_callbacksRunning. We set m_notifyWhenNoCallbacksRunning only when m_callbacksRunning
// reaches zero.
//
- int m_callbacksRunning;
- volatile bool m_canceled;
- volatile WaitHandle m_notifyWhenNoCallbacksRunning;
+ private int m_callbacksRunning;
+ private volatile bool m_canceled;
+ private volatile WaitHandle m_notifyWhenNoCallbacksRunning;
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period)
@@ -455,7 +455,7 @@ namespace System.Threading
lock (TimerQueue.Instance)
{
if (m_canceled)
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
// prevent ThreadAbort while updating state
try { }
@@ -612,17 +612,17 @@ namespace System.Threading
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
//
- sealed class TimerHolder
+ internal sealed class TimerHolder
{
internal TimerQueueTimer m_timer;
-
- public TimerHolder(TimerQueueTimer timer)
- {
- m_timer = timer;
+
+ public TimerHolder(TimerQueueTimer timer)
+ {
+ m_timer = timer;
}
- ~TimerHolder()
- {
+ ~TimerHolder()
+ {
//
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
@@ -636,7 +636,7 @@ namespace System.Threading
if (Environment.HasShutdownStarted || AppDomain.CurrentDomain.IsFinalizingForUnload())
return;
- m_timer.Close();
+ m_timer.Close();
}
public void Close()
@@ -651,7 +651,6 @@ namespace System.Threading
GC.SuppressFinalize(this);
return result;
}
-
}
@@ -661,64 +660,64 @@ namespace System.Threading
private TimerHolder m_timer;
- public Timer(TimerCallback callback,
- Object state,
- int dueTime,
- int period)
+ public Timer(TimerCallback callback,
+ Object state,
+ int dueTime,
+ int period)
{
if (dueTime < -1)
- throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
- if (period < -1 )
- throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
+ if (period < -1)
+ throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
- TimerSetup(callback,state,(UInt32)dueTime,(UInt32)period);
+ TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
- public Timer(TimerCallback callback,
- Object state,
- TimeSpan dueTime,
- TimeSpan period)
- {
+ public Timer(TimerCallback callback,
+ Object state,
+ TimeSpan dueTime,
+ TimeSpan period)
+ {
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
- throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTm > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(dueTm),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_TimeoutTooLarge);
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
- throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (periodTm > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(periodTm),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge);
- TimerSetup(callback,state,(UInt32)dueTm,(UInt32)periodTm);
+ TimerSetup(callback, state, (UInt32)dueTm, (UInt32)periodTm);
}
[CLSCompliant(false)]
- public Timer(TimerCallback callback,
- Object state,
- UInt32 dueTime,
- UInt32 period)
+ public Timer(TimerCallback callback,
+ Object state,
+ UInt32 dueTime,
+ UInt32 period)
{
- TimerSetup(callback,state,dueTime,period);
+ TimerSetup(callback, state, dueTime, period);
}
- public Timer(TimerCallback callback,
- Object state,
- long dueTime,
- long period)
+ public Timer(TimerCallback callback,
+ Object state,
+ long dueTime,
+ long period)
{
if (dueTime < -1)
- throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
- throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge);
Contract.EndContractBlock();
- TimerSetup(callback,state,(UInt32) dueTime, (UInt32) period);
+ TimerSetup(callback, state, (UInt32)dueTime, (UInt32)period);
}
public Timer(TimerCallback callback)
@@ -727,12 +726,12 @@ namespace System.Threading
int period = -1; // Change after a timer instance is created. This is to avoid the potential
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
-
+
TimerSetup(callback, this, (UInt32)dueTime, (UInt32)period);
}
private void TimerSetup(TimerCallback callback,
- Object state,
+ Object state,
UInt32 dueTime,
UInt32 period)
{
@@ -742,13 +741,13 @@ namespace System.Threading
m_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period));
}
-
+
public bool Change(int dueTime, int period)
{
- if (dueTime < -1 )
- throw new ArgumentOutOfRangeException(nameof(dueTime),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ if (dueTime < -1)
+ throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
- throw new ArgumentOutOfRangeException(nameof(period),Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
@@ -756,7 +755,7 @@ namespace System.Threading
public bool Change(TimeSpan dueTime, TimeSpan period)
{
- return Change((long) dueTime.TotalMilliseconds, (long) period.TotalMilliseconds);
+ return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
[CLSCompliant(false)]
@@ -767,28 +766,28 @@ namespace System.Threading
public bool Change(long dueTime, long period)
{
- if (dueTime < -1 )
- throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ if (dueTime < -1)
+ throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
- throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(dueTime), Environment.GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
- throw new ArgumentOutOfRangeException(nameof(period), Environment.GetResourceString("ArgumentOutOfRange_PeriodTooLarge"));
+ throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge);
Contract.EndContractBlock();
return m_timer.m_timer.Change((UInt32)dueTime, (UInt32)period);
}
-
+
public bool Dispose(WaitHandle notifyObject)
{
- if (notifyObject==null)
+ if (notifyObject == null)
throw new ArgumentNullException(nameof(notifyObject));
Contract.EndContractBlock();
return m_timer.Close(notifyObject);
}
-
+
public void Dispose()
{
m_timer.Close();
diff --git a/src/mscorlib/src/System/Threading/Volatile.cs b/src/mscorlib/src/System/Threading/Volatile.cs
index c94a69ab7b..6aac8d63cd 100644
--- a/src/mscorlib/src/System/Threading/Volatile.cs
+++ b/src/mscorlib/src/System/Threading/Volatile.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
//
+
using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
@@ -33,7 +34,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -45,7 +46,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -56,7 +57,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -67,7 +68,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -79,7 +80,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -90,7 +91,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -102,7 +103,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -114,7 +115,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -126,7 +127,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
#else
@@ -165,7 +166,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -177,7 +178,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -188,7 +189,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -211,7 +212,7 @@ namespace System.Threading
// The VM will replace this with a more efficient implementation.
//
var value = location;
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
return value;
}
@@ -224,7 +225,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -235,7 +236,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -245,7 +246,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -255,7 +256,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -266,7 +267,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -276,7 +277,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -287,7 +288,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -298,7 +299,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -309,7 +310,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
#else
@@ -353,7 +354,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -364,7 +365,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -374,7 +375,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
@@ -396,7 +397,7 @@ namespace System.Threading
//
// The VM will replace this with a more efficient implementation.
//
- Thread.MemoryBarrier();
+ Interlocked.MemoryBarrier();
location = value;
}
}
diff --git a/src/mscorlib/src/System/Threading/WaitHandle.cs b/src/mscorlib/src/System/Threading/WaitHandle.cs
index d4dcd710be..f3412d264f 100644
--- a/src/mscorlib/src/System/Threading/WaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/WaitHandle.cs
@@ -26,8 +26,9 @@ namespace System.Threading
using System.Diagnostics.CodeAnalysis;
using Win32Native = Microsoft.Win32.Win32Native;
- public abstract class WaitHandle : MarshalByRefObject, IDisposable {
- public const int WaitTimeout = 0x102;
+ public abstract class WaitHandle : MarshalByRefObject, IDisposable
+ {
+ public const int WaitTimeout = 0x102;
private const int MAX_WAITHANDLES = 64;
@@ -57,7 +58,7 @@ namespace System.Threading
NameInvalid
}
- protected WaitHandle()
+ protected WaitHandle()
{
Init();
}
@@ -68,12 +69,12 @@ namespace System.Threading
waitHandle = InvalidHandle;
hasThreadAffinity = false;
}
-
-
+
+
[Obsolete("Use the SafeWaitHandle property instead.")]
- public virtual IntPtr Handle
+ public virtual IntPtr Handle
{
- get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle();}
+ get { return safeWaitHandle == null ? InvalidHandle : safeWaitHandle.DangerousGetHandle(); }
set
{
if (value == InvalidHandle)
@@ -92,13 +93,13 @@ namespace System.Threading
}
else
{
- safeWaitHandle = new SafeWaitHandle(value, true);
+ safeWaitHandle = new SafeWaitHandle(value, true);
}
waitHandle = value;
}
}
- public SafeWaitHandle SafeWaitHandle
+ public SafeWaitHandle SafeWaitHandle
{
get
{
@@ -111,23 +112,23 @@ namespace System.Threading
set
{
- // Set safeWaitHandle and waitHandle in a CER so we won't take
- // a thread abort between the statements and leave the wait
- // handle in an invalid state. Note this routine is not thread
- // safe however.
- RuntimeHelpers.PrepareConstrainedRegions();
+ // Set safeWaitHandle and waitHandle in a CER so we won't take
+ // a thread abort between the statements and leave the wait
+ // handle in an invalid state. Note this routine is not thread
+ // safe however.
+ RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
if (value == null)
{
- safeWaitHandle = null;
- waitHandle = InvalidHandle;
+ safeWaitHandle = null;
+ waitHandle = InvalidHandle;
}
else
{
- safeWaitHandle = value;
- waitHandle = safeWaitHandle.DangerousGetHandle();
+ safeWaitHandle = value;
+ waitHandle = safeWaitHandle.DangerousGetHandle();
}
}
}
@@ -147,41 +148,41 @@ namespace System.Threading
safeWaitHandle = handle;
waitHandle = handle.DangerousGetHandle();
}
-
- public virtual bool WaitOne (int millisecondsTimeout, bool exitContext)
+
+ public virtual bool WaitOne(int millisecondsTimeout, bool exitContext)
{
if (millisecondsTimeout < -1)
{
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
- return WaitOne((long)millisecondsTimeout,exitContext);
+ return WaitOne((long)millisecondsTimeout, exitContext);
}
- public virtual bool WaitOne (TimeSpan timeout, bool exitContext)
+ public virtual bool WaitOne(TimeSpan timeout, bool exitContext)
{
long tm = (long)timeout.TotalMilliseconds;
- if (-1 > tm || (long) Int32.MaxValue < tm)
+ if (-1 > tm || (long)Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- return WaitOne(tm,exitContext);
+ return WaitOne(tm, exitContext);
}
- public virtual bool WaitOne ()
+ public virtual bool WaitOne()
{
//Infinite Timeout
- return WaitOne(-1,false);
+ return WaitOne(-1, false);
}
public virtual bool WaitOne(int millisecondsTimeout)
{
- return WaitOne(millisecondsTimeout, false);
+ return WaitOne(millisecondsTimeout, false);
}
public virtual bool WaitOne(TimeSpan timeout)
{
- return WaitOne(timeout, false);
+ return WaitOne(timeout, false);
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety.")]
@@ -194,28 +195,28 @@ namespace System.Threading
{
if (waitableSafeHandle == null)
{
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
int ret = WaitOneNative(waitableSafeHandle, (uint)millisecondsTimeout, hasThreadAffinity, exitContext);
- if(AppDomainPauseManager.IsPaused)
+ if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
-
+
if (ret == WAIT_ABANDONED)
{
ThrowAbandonedMutexException();
}
return (ret != WaitTimeout);
}
-
+
internal bool WaitOneWithoutFAS()
{
// version of waitone without fast application switch (FAS) support
// This is required to support the Wait which FAS needs (otherwise recursive dependency comes in)
if (safeWaitHandle == null)
{
- throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_Generic"));
+ throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
}
Contract.EndContractBlock();
@@ -226,11 +227,11 @@ namespace System.Threading
ThrowAbandonedMutexException();
}
return (ret != WaitTimeout);
- }
+ }
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int WaitOneNative(SafeHandle waitableSafeHandle, uint millisecondsTimeout, bool hasThreadAffinity, bool exitContext);
-
+
/*========================================================================
** Waits for signal from all the objects.
** timeout indicates how long to wait before the method returns.
@@ -239,17 +240,17 @@ namespace System.Threading
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
-
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
+
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int WaitMultiple(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext, bool WaitAll);
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
if (waitHandles == null)
{
- throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("ArgumentNull_Waithandles"));
+ throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles);
}
- if(waitHandles.Length == 0)
+ if (waitHandles.Length == 0)
{
//
// Some history: in CLR 1.0 and 1.1, we threw ArgumentException in this case, which was correct.
@@ -260,24 +261,24 @@ namespace System.Threading
// in CoreCLR, and ArgumentNullException in the desktop CLR. This is ugly, but so is breaking
// user code.
//
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray"));
+ throw new ArgumentException(SR.Argument_EmptyWaithandleArray);
}
if (waitHandles.Length > MAX_WAITHANDLES)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles"));
+ throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
- for (int i = 0; i < waitHandles.Length; i ++)
+ for (int i = 0; i < waitHandles.Length; i++)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
- throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement"));
+ throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement);
internalWaitHandles[i] = waitHandle;
}
@@ -288,51 +289,51 @@ namespace System.Threading
int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, true /* waitall*/ );
- if(AppDomainPauseManager.IsPaused)
+ if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
- if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret))
+ if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret))
{
//In the case of WaitAll the OS will only provide the
// information that mutex was abandoned.
// It won't tell us which one. So we can't set the Index or provide access to the Mutex
ThrowAbandonedMutexException();
- }
+ }
GC.KeepAlive(internalWaitHandles);
return (ret != WaitTimeout);
}
public static bool WaitAll(
- WaitHandle[] waitHandles,
+ WaitHandle[] waitHandles,
TimeSpan timeout,
bool exitContext)
{
long tm = (long)timeout.TotalMilliseconds;
- if (-1 > tm || (long) Int32.MaxValue < tm)
+ if (-1 > tm || (long)Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- return WaitAll(waitHandles,(int)tm, exitContext);
+ return WaitAll(waitHandles, (int)tm, exitContext);
}
-
+
/*========================================================================
** Shorthand for WaitAll with timeout = Timeout.Infinite and exitContext = true
========================================================================*/
public static bool WaitAll(WaitHandle[] waitHandles)
{
- return WaitAll(waitHandles, Timeout.Infinite, true);
+ return WaitAll(waitHandles, Timeout.Infinite, true);
}
public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout)
{
- return WaitAll(waitHandles, millisecondsTimeout, true);
+ return WaitAll(waitHandles, millisecondsTimeout, true);
}
public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout)
{
- return WaitAll(waitHandles, timeout, true);
+ return WaitAll(waitHandles, timeout, true);
}
@@ -344,33 +345,33 @@ namespace System.Threading
** If exitContext is true then the synchronization domain for the context
** (if in a synchronized context) is exited before the wait and reacquired
========================================================================*/
-
+
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext)
{
- if (waitHandles==null)
+ if (waitHandles == null)
{
- throw new ArgumentNullException(nameof(waitHandles), Environment.GetResourceString("ArgumentNull_Waithandles"));
+ throw new ArgumentNullException(nameof(waitHandles), SR.ArgumentNull_Waithandles);
}
- if(waitHandles.Length == 0)
+ if (waitHandles.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_EmptyWaithandleArray"));
+ throw new ArgumentException(SR.Argument_EmptyWaithandleArray);
}
if (MAX_WAITHANDLES < waitHandles.Length)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_MaxWaitHandles"));
+ throw new NotSupportedException(SR.NotSupported_MaxWaitHandles);
}
if (-1 > millisecondsTimeout)
{
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
WaitHandle[] internalWaitHandles = new WaitHandle[waitHandles.Length];
- for (int i = 0; i < waitHandles.Length; i ++)
+ for (int i = 0; i < waitHandles.Length; i++)
{
WaitHandle waitHandle = waitHandles[i];
if (waitHandle == null)
- throw new ArgumentNullException("waitHandles[" + i + "]", Environment.GetResourceString("ArgumentNull_ArrayElement"));
+ throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement);
internalWaitHandles[i] = waitHandle;
}
@@ -380,41 +381,41 @@ namespace System.Threading
#endif
int ret = WaitMultiple(internalWaitHandles, millisecondsTimeout, exitContext, false /* waitany*/ );
- if(AppDomainPauseManager.IsPaused)
+ if (AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
- if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED+internalWaitHandles.Length > ret))
+ if ((WAIT_ABANDONED <= ret) && (WAIT_ABANDONED + internalWaitHandles.Length > ret))
{
- int mutexIndex = ret -WAIT_ABANDONED;
- if(0 <= mutexIndex && mutexIndex < internalWaitHandles.Length)
+ int mutexIndex = ret - WAIT_ABANDONED;
+ if (0 <= mutexIndex && mutexIndex < internalWaitHandles.Length)
{
- ThrowAbandonedMutexException(mutexIndex,internalWaitHandles[mutexIndex]);
+ ThrowAbandonedMutexException(mutexIndex, internalWaitHandles[mutexIndex]);
}
else
{
ThrowAbandonedMutexException();
}
}
-
+
GC.KeepAlive(internalWaitHandles);
- return ret;
+ return ret;
}
public static int WaitAny(
- WaitHandle[] waitHandles,
+ WaitHandle[] waitHandles,
TimeSpan timeout,
bool exitContext)
{
long tm = (long)timeout.TotalMilliseconds;
- if (-1 > tm || (long) Int32.MaxValue < tm)
+ if (-1 > tm || (long)Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- return WaitAny(waitHandles,(int)tm, exitContext);
+ return WaitAny(waitHandles, (int)tm, exitContext);
}
public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout)
{
- return WaitAny(waitHandles, timeout, true);
+ return WaitAny(waitHandles, timeout, true);
}
@@ -428,7 +429,7 @@ namespace System.Threading
public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout)
{
- return WaitAny(waitHandles, millisecondsTimeout, true);
+ return WaitAny(waitHandles, millisecondsTimeout, true);
}
/*=================================================
@@ -436,20 +437,20 @@ namespace System.Threading
== SignalAndWait
==
==================================================*/
-#if !PLATFORM_UNIX
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal,SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
- bool hasThreadAffinity, bool exitContext);
-#endif // !PLATFORM_UNIX
+#if PLATFORM_WINDOWS
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private static extern int SignalAndWaitOne(SafeWaitHandle waitHandleToSignal, SafeWaitHandle waitHandleToWaitOn, int millisecondsTimeout,
+ bool hasThreadAffinity, bool exitContext);
+#endif // PLATFORM_WINDOWS
public static bool SignalAndWait(
WaitHandle toSignal,
WaitHandle toWaitOn)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // https://github.com/dotnet/coreclr/issues/10441
#else
- return SignalAndWait(toSignal,toWaitOn,-1,false);
+ return SignalAndWait(toSignal, toWaitOn, -1, false);
#endif
}
@@ -460,14 +461,14 @@ namespace System.Threading
bool exitContext)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // https://github.com/dotnet/coreclr/issues/10441
#else
long tm = (long)timeout.TotalMilliseconds;
- if (-1 > tm || (long) Int32.MaxValue < tm)
+ if (-1 > tm || (long)Int32.MaxValue < tm)
{
- throw new ArgumentOutOfRangeException(nameof(timeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
- return SignalAndWait(toSignal,toWaitOn,(int)tm,exitContext);
+ return SignalAndWait(toSignal, toWaitOn, (int)tm, exitContext);
#endif
}
@@ -479,38 +480,38 @@ namespace System.Threading
bool exitContext)
{
#if PLATFORM_UNIX
- throw new PlatformNotSupportedException();
+ throw new PlatformNotSupportedException(SR.Arg_PlatformNotSupported); // https://github.com/dotnet/coreclr/issues/10441
#else
- if(null == toSignal)
+ if (null == toSignal)
{
throw new ArgumentNullException(nameof(toSignal));
}
- if(null == toWaitOn)
+ if (null == toWaitOn)
{
throw new ArgumentNullException(nameof(toWaitOn));
}
if (-1 > millisecondsTimeout)
{
- throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"));
+ throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
Contract.EndContractBlock();
//NOTE: This API is not supporting Pause/Resume as it's not exposed in CoreCLR (not in WP or SL)
- int ret = SignalAndWaitOne(toSignal.safeWaitHandle,toWaitOn.safeWaitHandle,millisecondsTimeout,
- toWaitOn.hasThreadAffinity,exitContext);
+ int ret = SignalAndWaitOne(toSignal.safeWaitHandle, toWaitOn.safeWaitHandle, millisecondsTimeout,
+ toWaitOn.hasThreadAffinity, exitContext);
- if(WAIT_ABANDONED == ret)
+ if (WAIT_ABANDONED == ret)
{
ThrowAbandonedMutexException();
}
- if(ERROR_TOO_MANY_POSTS == ret)
+ if (ERROR_TOO_MANY_POSTS == ret)
{
- throw new InvalidOperationException(Environment.GetResourceString("Threading.WaitHandleTooManyPosts"));
+ throw new InvalidOperationException(SR.Threading_WaitHandleTooManyPosts);
}
//Object was signaled
- if(WAIT_OBJECT_0 == ret)
+ if (WAIT_OBJECT_0 == ret)
{
return true;
}
@@ -535,7 +536,7 @@ namespace System.Threading
Dispose(true);
GC.SuppressFinalize(this);
}
-
+
protected virtual void Dispose(bool explicitDisposing)
{
if (safeWaitHandle != null)
diff --git a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs b/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.cs
deleted file mode 100644
index 68445a78d9..0000000000
--- a/src/mscorlib/src/System/Threading/WaitHandleCannotBeOpenedException.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.
-
-//
-namespace System.Threading
-{
- using System;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
-
- [Serializable]
- [ComVisibleAttribute(false)]
-
- public class WaitHandleCannotBeOpenedException : ApplicationException {
- public WaitHandleCannotBeOpenedException() : base(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException"))
- {
- SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED);
- }
-
- public WaitHandleCannotBeOpenedException(String message) : base(message)
- {
- SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED);
- }
-
- public WaitHandleCannotBeOpenedException(String message, Exception innerException) : base(message, innerException)
- {
- SetErrorCode(__HResults.COR_E_WAITHANDLECANNOTBEOPENED);
- }
-
- protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base (info, context)
- {
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/ThrowHelper.cs b/src/mscorlib/src/System/ThrowHelper.cs
index 1ed8317633..4dcf8d4511 100644
--- a/src/mscorlib/src/System/ThrowHelper.cs
+++ b/src/mscorlib/src/System/ThrowHelper.cs
@@ -3,220 +3,261 @@
// See the LICENSE file in the project root for more information.
-namespace System {
- // This file defines an internal class used to throw exceptions in BCL code.
- // The main purpose is to reduce code size.
- //
- // The old way to throw an exception generates quite a lot IL code and assembly code.
- // Following is an example:
- // C# source
- // throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key"));
- // IL code:
- // IL_0003: ldstr "key"
- // IL_0008: ldstr "ArgumentNull_Key"
- // IL_000d: call string System.Environment::GetResourceString(string)
- // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
- // IL_0017: throw
- // which is 21bytes in IL.
- //
- // So we want to get rid of the ldstr and call to Environment.GetResource in IL.
- // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
- // argument name and resource name in a small integer. The source code will be changed to
- // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
- //
- // The IL code will be 7 bytes.
- // IL_0008: ldc.i4.4
- // IL_0009: ldc.i4.4
- // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
- // IL_000f: ldarg.0
- //
- // This will also reduce the Jitted code size a lot.
- //
- // It is very important we do this for generic classes because we can easily generate the same code
- // multiple times for different instantiation.
- //
-
- using Collections.Generic;
- using System.Runtime.CompilerServices;
- using System.Runtime.Serialization;
- using System.Diagnostics.Contracts;
-
+// This file defines an internal class used to throw exceptions in BCL code.
+// The main purpose is to reduce code size.
+//
+// The old way to throw an exception generates quite a lot IL code and assembly code.
+// Following is an example:
+// C# source
+// throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key);
+// IL code:
+// IL_0003: ldstr "key"
+// IL_0008: ldstr "ArgumentNull_Key"
+// IL_000d: call string System.Environment::GetResourceString(string)
+// IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
+// IL_0017: throw
+// which is 21bytes in IL.
+//
+// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
+// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
+// argument name and resource name in a small integer. The source code will be changed to
+// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
+//
+// The IL code will be 7 bytes.
+// IL_0008: ldc.i4.4
+// IL_0009: ldc.i4.4
+// IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
+// IL_000f: ldarg.0
+//
+// This will also reduce the Jitted code size a lot.
+//
+// It is very important we do this for generic classes because we can easily generate the same code
+// multiple times for different instantiation.
+//
+
+using System.Collections.Generic;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
[Pure]
- internal static class ThrowHelper {
- internal static void ThrowArrayTypeMismatchException() {
+ internal static class ThrowHelper
+ {
+ internal static void ThrowArrayTypeMismatchException()
+ {
throw new ArrayTypeMismatchException();
}
- internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) {
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidTypeWithPointersNotSupported", targetType));
+ internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType));
}
- internal static void ThrowIndexOutOfRangeException() {
+ internal static void ThrowIndexOutOfRangeException()
+ {
throw new IndexOutOfRangeException();
}
- internal static void ThrowArgumentOutOfRangeException() {
+ internal static void ThrowArgumentOutOfRangeException()
+ {
throw new ArgumentOutOfRangeException();
}
- internal static void ThrowArgumentException_DestinationTooShort() {
- throw new ArgumentException(Environment.GetResourceString("Argument_DestinationTooShort"));
- }
-
- internal static void ThrowNotSupportedException_CannotCallEqualsOnSpan() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallEqualsOnSpan"));
- }
-
- internal static void ThrowNotSupportedException_CannotCallGetHashCodeOnSpan() {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan"));
+ internal static void ThrowArgumentException_DestinationTooShort()
+ {
+ throw new ArgumentException(SR.Argument_DestinationTooShort);
}
- internal static void ThrowArgumentOutOfRange_IndexException() {
- throw GetArgumentOutOfRangeException(ExceptionArgument.index,
+ internal static void ThrowArgumentOutOfRange_IndexException()
+ {
+ throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_Index);
}
- internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() {
- throw GetArgumentOutOfRangeException(ExceptionArgument.index,
+ internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException()
+ {
+ throw GetArgumentOutOfRangeException(ExceptionArgument.index,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
- internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() {
+ internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum()
+ {
throw GetArgumentOutOfRangeException(ExceptionArgument.length,
ExceptionResource.ArgumentOutOfRange_NeedNonNegNum);
}
- internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() {
+ internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index()
+ {
throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex,
ExceptionResource.ArgumentOutOfRange_Index);
}
- internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() {
+ internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count()
+ {
throw GetArgumentOutOfRangeException(ExceptionArgument.count,
ExceptionResource.ArgumentOutOfRange_Count);
}
- internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) {
+ internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType)
+ {
throw GetWrongKeyTypeArgumentException(key, targetType);
}
- internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) {
+ internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType)
+ {
throw GetWrongValueTypeArgumentException(value, targetType);
}
- private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) {
- return new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicateWithKey", key));
+ private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key)
+ {
+ return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key));
}
- internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) {
+ internal static void ThrowAddingDuplicateWithKeyArgumentException(object key)
+ {
throw GetAddingDuplicateWithKeyArgumentException(key);
}
- internal static void ThrowKeyNotFoundException() {
+ internal static void ThrowKeyNotFoundException()
+ {
throw new System.Collections.Generic.KeyNotFoundException();
}
-
- internal static void ThrowArgumentException(ExceptionResource resource) {
+
+ internal static void ThrowArgumentException(ExceptionResource resource)
+ {
throw GetArgumentException(resource);
}
- internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) {
+ internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument)
+ {
throw GetArgumentException(resource, argument);
}
- private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) {
+ private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
+ {
return new ArgumentNullException(GetArgumentName(argument));
}
- internal static void ThrowArgumentNullException(ExceptionArgument argument) {
+ internal static void ThrowArgumentNullException(ExceptionArgument argument)
+ {
throw GetArgumentNullException(argument);
}
- internal static void ThrowArgumentNullException(ExceptionResource resource) {
+ internal static void ThrowArgumentNullException(ExceptionResource resource)
+ {
throw new ArgumentNullException(GetResourceString(resource));
}
- internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) {
+ internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource)
+ {
+ throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource));
+ }
+
+ internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
+ {
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
- internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
+ internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
+ {
throw GetArgumentOutOfRangeException(argument, resource);
}
- internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) {
+ internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
+ {
throw GetArgumentOutOfRangeException(argument, paramNumber, resource);
}
- internal static void ThrowInvalidOperationException(ExceptionResource resource) {
+ internal static void ThrowInvalidOperationException(ExceptionResource resource)
+ {
throw GetInvalidOperationException(resource);
}
- internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) {
+ internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e)
+ {
throw new InvalidOperationException(GetResourceString(resource), e);
}
- internal static void ThrowSerializationException(ExceptionResource resource) {
+ internal static void ThrowSerializationException(ExceptionResource resource)
+ {
throw new SerializationException(GetResourceString(resource));
}
- internal static void ThrowSecurityException(ExceptionResource resource) {
+ internal static void ThrowSecurityException(ExceptionResource resource)
+ {
throw new System.Security.SecurityException(GetResourceString(resource));
}
- internal static void ThrowRankException(ExceptionResource resource) {
+ internal static void ThrowRankException(ExceptionResource resource)
+ {
throw new RankException(GetResourceString(resource));
}
- internal static void ThrowNotSupportedException(ExceptionResource resource) {
+ internal static void ThrowNotSupportedException(ExceptionResource resource)
+ {
throw new NotSupportedException(GetResourceString(resource));
}
- internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) {
+ internal static void ThrowUnauthorizedAccessException(ExceptionResource resource)
+ {
throw new UnauthorizedAccessException(GetResourceString(resource));
}
- internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) {
+ internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource)
+ {
throw new ObjectDisposedException(objectName, GetResourceString(resource));
}
- internal static void ThrowObjectDisposedException(ExceptionResource resource) {
+ internal static void ThrowObjectDisposedException(ExceptionResource resource)
+ {
throw new ObjectDisposedException(null, GetResourceString(resource));
}
- internal static void ThrowNotSupportedException() {
+ internal static void ThrowNotSupportedException()
+ {
throw new NotSupportedException();
}
- internal static void ThrowAggregateException(List<Exception> exceptions) {
+ internal static void ThrowAggregateException(List<Exception> exceptions)
+ {
throw new AggregateException(exceptions);
}
- internal static void ThrowArgumentException_Argument_InvalidArrayType() {
+ internal static void ThrowArgumentException_Argument_InvalidArrayType()
+ {
throw GetArgumentException(ExceptionResource.Argument_InvalidArrayType);
}
- internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted() {
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted()
+ {
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted);
}
- internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded() {
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded()
+ {
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
}
- internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() {
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
+ {
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
}
- internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() {
+ internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen()
+ {
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen);
}
- internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) {
+ internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count)
+ {
throw GetArraySegmentCtorValidationFailedException(array, offset, count);
}
- private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) {
+ private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count)
+ {
if (array == null)
return GetArgumentNullException(ExceptionArgument.array);
if (offset < 0)
@@ -228,31 +269,38 @@ namespace System {
return GetArgumentException(ExceptionResource.Argument_InvalidOffLen);
}
- private static ArgumentException GetArgumentException(ExceptionResource resource) {
+ private static ArgumentException GetArgumentException(ExceptionResource resource)
+ {
return new ArgumentException(GetResourceString(resource));
}
- internal static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) {
+ internal static InvalidOperationException GetInvalidOperationException(ExceptionResource resource)
+ {
return new InvalidOperationException(GetResourceString(resource));
}
- private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) {
- return new ArgumentException(Environment.GetResourceString("Arg_WrongType", key, targetType), nameof(key));
+ private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType)
+ {
+ return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key));
}
- private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) {
- return new ArgumentException(Environment.GetResourceString("Arg_WrongType", value, targetType), nameof(value));
+ private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType)
+ {
+ return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value));
}
- internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
+ internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
+ {
return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
}
- private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument) {
+ private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument)
+ {
return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
}
- private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) {
+ private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource)
+ {
return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource));
}
@@ -260,25 +308,17 @@ namespace System {
// 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
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) {
+ internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName)
+ {
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
if (!(default(T) == null) && value == null)
ThrowHelper.ThrowArgumentNullException(argName);
}
// This function will convert an ExceptionArgument enum value to the argument name string.
- private static string GetArgumentName(ExceptionArgument argument) {
- // This is indirected through a second NoInlining function it has a special meaning
- // in System.Private.CoreLib of indicatating it takes a StackMark which cause
- // the caller to also be not inlined; so we can't mark it directly.
- // So is the effect of marking this function as non-inlining in a regular situation.
- return GetArgumentNameInner(argument);
- }
-
- // This function will convert an ExceptionArgument enum value to the argument name string.
- // Second function in chain so as to not propergate the non-inlining to outside caller
[MethodImpl(MethodImplOptions.NoInlining)]
- private static string GetArgumentNameInner(ExceptionArgument argument) {
+ private static string GetArgumentName(ExceptionArgument argument)
+ {
Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument),
"The enum value is not defined, please check the ExceptionArgument Enum.");
@@ -286,29 +326,21 @@ namespace System {
}
// This function will convert an ExceptionResource enum value to the resource string.
- private static string GetResourceString(ExceptionResource resource) {
- // This is indirected through a second NoInlining function it has a special meaning
- // in System.Private.CoreLib of indicatating it takes a StackMark which cause
- // the caller to also be not inlined; so we can't mark it directly.
- // So is the effect of marking this function as non-inlining in a regular situation.
- return GetResourceStringInner(resource);
- }
-
- // This function will convert an ExceptionResource enum value to the resource string.
- // Second function in chain so as to not propergate the non-inlining to outside caller
[MethodImpl(MethodImplOptions.NoInlining)]
- private static string GetResourceStringInner(ExceptionResource resource) {
+ private static string GetResourceString(ExceptionResource resource)
+ {
Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource),
"The enum value is not defined, please check the ExceptionResource Enum.");
- return Environment.GetResourceString(resource.ToString());
+ return SR.GetResourceString(resource.ToString());
}
}
//
// The convention for this enum is using the argument name as the enum name
//
- internal enum ExceptionArgument {
+ internal enum ExceptionArgument
+ {
obj,
dictionary,
dictionaryCreationThreshold,
@@ -382,28 +414,31 @@ namespace System {
text,
callBack,
type,
+ stateMachine,
+ pHandle,
}
//
// The convention for this enum is using the resource name as the enum name
//
- internal enum ExceptionResource {
+ internal enum ExceptionResource
+ {
Argument_ImplementIComparable,
- Argument_InvalidType,
+ Argument_InvalidType,
Argument_InvalidArgumentForComparison,
- Argument_InvalidRegistryKeyPermissionCheck,
+ Argument_InvalidRegistryKeyPermissionCheck,
ArgumentOutOfRange_NeedNonNegNum,
-
+
Arg_ArrayPlusOffTooSmall,
- Arg_NonZeroLowerBound,
- Arg_RankMultiDimNotSupported,
+ Arg_NonZeroLowerBound,
+ Arg_RankMultiDimNotSupported,
Arg_RegKeyDelHive,
- Arg_RegKeyStrLenBug,
+ Arg_RegKeyStrLenBug,
Arg_RegSetStrArrNull,
Arg_RegSetMismatchedKind,
- Arg_RegSubKeyAbsent,
+ Arg_RegSubKeyAbsent,
Arg_RegSubKeyValueAbsent,
-
+
Argument_AddingDuplicate,
Serialization_InvalidOnDeser,
Serialization_MissingKeys,
@@ -487,6 +522,8 @@ namespace System {
ConcurrentCollection_SyncRoot_NotSupported,
ArgumentOutOfRange_Enum,
InvalidOperation_HandleIsNotInitialized,
+ AsyncMethodBuilder_InstanceNotInitialized,
+ ArgumentNull_SafeHandle,
}
}
diff --git a/src/mscorlib/src/System/TimeSpan.cs b/src/mscorlib/src/System/TimeSpan.cs
index 7b71b48fed..9166656d0f 100644
--- a/src/mscorlib/src/System/TimeSpan.cs
+++ b/src/mscorlib/src/System/TimeSpan.cs
@@ -2,15 +2,16 @@
// 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 {
- using System.Text;
- using System;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
- using System.Globalization;
-
+using System.Text;
+using System;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+
+namespace System
+{
// TimeSpan represents a duration of time. A TimeSpan can be negative
// or positive.
//
@@ -28,14 +29,15 @@ namespace System {
// details of this type should change, or new fields added, we need to remember to add
// an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled.
//
- [Serializable] public struct TimeSpan : IComparable
+ [Serializable]
+ public struct TimeSpan : IComparable
, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable
{
- public const long TicksPerMillisecond = 10000;
+ public const long TicksPerMillisecond = 10000;
private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond;
public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000
- private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001
+ private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001
public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000
private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9
@@ -72,16 +74,18 @@ namespace System {
// _ticks = 0;
//}
- public TimeSpan(long ticks) {
+ public TimeSpan(long ticks)
+ {
this._ticks = ticks;
}
- public TimeSpan(int hours, int minutes, int seconds) {
+ public TimeSpan(int hours, int minutes, int seconds)
+ {
_ticks = TimeToTicks(hours, minutes, seconds);
}
public TimeSpan(int days, int hours, int minutes, int seconds)
- : this(days,hours,minutes,seconds,0)
+ : this(days, hours, minutes, seconds, 0)
{
}
@@ -89,44 +93,54 @@ namespace System {
{
Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds;
if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds)
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
- _ticks = (long)totalMilliSeconds * TicksPerMillisecond;
+ throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong);
+ _ticks = (long)totalMilliSeconds * TicksPerMillisecond;
}
- public long Ticks {
+ public long Ticks
+ {
get { return _ticks; }
}
- public int Days {
+ public int Days
+ {
get { return (int)(_ticks / TicksPerDay); }
}
- public int Hours {
+ public int Hours
+ {
get { return (int)((_ticks / TicksPerHour) % 24); }
}
- public int Milliseconds {
+ public int Milliseconds
+ {
get { return (int)((_ticks / TicksPerMillisecond) % 1000); }
}
- public int Minutes {
+ public int Minutes
+ {
get { return (int)((_ticks / TicksPerMinute) % 60); }
}
- public int Seconds {
+ public int Seconds
+ {
get { return (int)((_ticks / TicksPerSecond) % 60); }
}
- public double TotalDays {
+ public double TotalDays
+ {
get { return ((double)_ticks) * DaysPerTick; }
}
- public double TotalHours {
+ public double TotalHours
+ {
get { return (double)_ticks * HoursPerTick; }
}
- public double TotalMilliseconds {
- get {
+ public double TotalMilliseconds
+ {
+ get
+ {
double temp = (double)_ticks * MillisecondsPerTick;
if (temp > MaxMilliSeconds)
return (double)MaxMilliSeconds;
@@ -138,21 +152,24 @@ namespace System {
}
}
- public double TotalMinutes {
+ public double TotalMinutes
+ {
get { return (double)_ticks * MinutesPerTick; }
}
- public double TotalSeconds {
+ public double TotalSeconds
+ {
get { return (double)_ticks * SecondsPerTick; }
}
- public TimeSpan Add(TimeSpan ts) {
+ public TimeSpan Add(TimeSpan ts)
+ {
long result = _ticks + ts._ticks;
// Overflow if signs of operands was identical and result's
// sign was opposite.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
- throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
+ throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan(result);
}
@@ -160,43 +177,50 @@ namespace System {
// Compares two TimeSpan values, returning an integer that indicates their
// relationship.
//
- public static int Compare(TimeSpan t1, TimeSpan t2) {
+ public static int Compare(TimeSpan t1, TimeSpan t2)
+ {
if (t1._ticks > t2._ticks) return 1;
if (t1._ticks < t2._ticks) return -1;
return 0;
}
// Returns a value less than zero if this object
- public int CompareTo(Object value) {
+ public int CompareTo(Object value)
+ {
if (value == null) return 1;
if (!(value is TimeSpan))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeTimeSpan"));
+ throw new ArgumentException(SR.Arg_MustBeTimeSpan);
long t = ((TimeSpan)value)._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
- public int CompareTo(TimeSpan value) {
+ public int CompareTo(TimeSpan value)
+ {
long t = value._ticks;
if (_ticks > t) return 1;
if (_ticks < t) return -1;
return 0;
}
- public static TimeSpan FromDays(double value) {
+ public static TimeSpan FromDays(double value)
+ {
return Interval(value, MillisPerDay);
}
- public TimeSpan Duration() {
- if (Ticks==TimeSpan.MinValue.Ticks)
- throw new OverflowException(Environment.GetResourceString("Overflow_Duration"));
+ public TimeSpan Duration()
+ {
+ if (Ticks == TimeSpan.MinValue.Ticks)
+ throw new OverflowException(SR.Overflow_Duration);
Contract.EndContractBlock();
- return new TimeSpan(_ticks >= 0? _ticks: -_ticks);
+ return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks);
}
- public override bool Equals(Object value) {
- if (value is TimeSpan) {
+ public override bool Equals(Object value)
+ {
+ if (value is TimeSpan)
+ {
return _ticks == ((TimeSpan)value)._ticks;
}
return false;
@@ -207,169 +231,255 @@ namespace System {
return _ticks == obj._ticks;
}
- public static bool Equals(TimeSpan t1, TimeSpan t2) {
+ public static bool Equals(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks == t2._ticks;
}
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return (int)_ticks ^ (int)(_ticks >> 32);
}
- public static TimeSpan FromHours(double value) {
+ public static TimeSpan FromHours(double value)
+ {
return Interval(value, MillisPerHour);
}
- private static TimeSpan Interval(double value, int scale) {
+ private static TimeSpan Interval(double value, int scale)
+ {
if (Double.IsNaN(value))
- throw new ArgumentException(Environment.GetResourceString("Arg_CannotBeNaN"));
+ throw new ArgumentException(SR.Arg_CannotBeNaN);
Contract.EndContractBlock();
double tmp = value * scale;
- double millis = tmp + (value >= 0? 0.5: -0.5);
+ double millis = tmp + (value >= 0 ? 0.5 : -0.5);
if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond))
- throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
+ throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan((long)millis * TicksPerMillisecond);
}
- public static TimeSpan FromMilliseconds(double value) {
+ public static TimeSpan FromMilliseconds(double value)
+ {
return Interval(value, 1);
}
- public static TimeSpan FromMinutes(double value) {
+ public static TimeSpan FromMinutes(double value)
+ {
return Interval(value, MillisPerMinute);
}
- public TimeSpan Negate() {
- if (Ticks==TimeSpan.MinValue.Ticks)
- throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
+ public TimeSpan Negate()
+ {
+ if (Ticks == TimeSpan.MinValue.Ticks)
+ throw new OverflowException(SR.Overflow_NegateTwosCompNum);
Contract.EndContractBlock();
return new TimeSpan(-_ticks);
}
- public static TimeSpan FromSeconds(double value) {
+ public static TimeSpan FromSeconds(double value)
+ {
return Interval(value, MillisPerSecond);
}
- public TimeSpan Subtract(TimeSpan ts) {
+ public TimeSpan Subtract(TimeSpan ts)
+ {
long result = _ticks - ts._ticks;
// Overflow if signs of operands was different and result's
// sign was opposite from the first argument's sign.
// >> 63 gives the sign bit (either 64 1's or 64 0's).
if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63))
- throw new OverflowException(Environment.GetResourceString("Overflow_TimeSpanTooLong"));
+ throw new OverflowException(SR.Overflow_TimeSpanTooLong);
return new TimeSpan(result);
}
- public static TimeSpan FromTicks(long value) {
+ public TimeSpan Multiply(double factor) => this * factor;
+
+ public TimeSpan Divide(double divisor) => this / divisor;
+
+ public double Divide(TimeSpan ts) => this / ts;
+
+ public static TimeSpan FromTicks(long value)
+ {
return new TimeSpan(value);
}
- internal static long TimeToTicks(int hour, int minute, int second) {
+ internal static long TimeToTicks(int hour, int minute, int second)
+ {
// totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31,
// which is less than 2^44, meaning we won't overflow totalSeconds.
long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second;
if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds)
- throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("Overflow_TimeSpanTooLong"));
+ throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong);
return totalSeconds * TicksPerSecond;
}
// See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat
#region ParseAndFormat
- public static TimeSpan Parse(String s) {
+ public static TimeSpan Parse(String s)
+ {
/* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */
return TimeSpanParse.Parse(s, null);
}
- public static TimeSpan Parse(String input, IFormatProvider formatProvider) {
+ public static TimeSpan Parse(String input, IFormatProvider formatProvider)
+ {
return TimeSpanParse.Parse(input, formatProvider);
}
- public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) {
+ public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider)
+ {
return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None);
}
- public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) {
+ public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider)
+ {
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None);
}
- public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) {
+ public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
+ {
TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExact(input, format, formatProvider, styles);
}
- public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) {
+ public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
+ {
TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles);
}
- public static Boolean TryParse(String s, out TimeSpan result) {
+ public static Boolean TryParse(String s, out TimeSpan result)
+ {
return TimeSpanParse.TryParse(s, null, out result);
}
- public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) {
+ public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result)
+ {
return TimeSpanParse.TryParse(input, formatProvider, out result);
}
- public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) {
+ public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result)
+ {
return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result);
}
- public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) {
+ public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result)
+ {
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result);
}
- public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) {
+ public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
+ {
TimeSpanParse.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) {
+ public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
+ {
TimeSpanParse.ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result);
}
- public override String ToString() {
+ public override String ToString()
+ {
return TimeSpanFormat.Format(this, null, null);
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
return TimeSpanFormat.Format(this, format, null);
}
- public String ToString(String format, IFormatProvider formatProvider) {
- if (LegacyMode) {
+ public String ToString(String format, IFormatProvider formatProvider)
+ {
+ if (LegacyMode)
+ {
return TimeSpanFormat.Format(this, null, null);
}
- else {
+ else
+ {
return TimeSpanFormat.Format(this, format, formatProvider);
}
}
#endregion
-
- public static TimeSpan operator -(TimeSpan t) {
- if (t._ticks==TimeSpan.MinValue._ticks)
- throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum"));
+
+ public static TimeSpan operator -(TimeSpan t)
+ {
+ if (t._ticks == TimeSpan.MinValue._ticks)
+ throw new OverflowException(SR.Overflow_NegateTwosCompNum);
return new TimeSpan(-t._ticks);
}
- public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) {
+ public static TimeSpan operator -(TimeSpan t1, TimeSpan t2)
+ {
return t1.Subtract(t2);
}
- public static TimeSpan operator +(TimeSpan t) {
+ public static TimeSpan operator +(TimeSpan t)
+ {
return t;
}
- public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) {
+ public static TimeSpan operator +(TimeSpan t1, TimeSpan t2)
+ {
return t1.Add(t2);
}
- public static bool operator ==(TimeSpan t1, TimeSpan t2) {
+ public static TimeSpan operator *(TimeSpan timeSpan, double factor)
+ {
+ if (double.IsNaN(factor))
+ {
+ throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(factor));
+ }
+
+ // Rounding to the nearest tick is as close to the result we would have with unlimited
+ // precision as possible, and so likely to have the least potential to surprise.
+ double ticks = Math.Round(timeSpan.Ticks * factor);
+ if (ticks > long.MaxValue | ticks < long.MinValue)
+ {
+ throw new OverflowException(SR.Overflow_TimeSpanTooLong);
+ }
+
+ return FromTicks((long)ticks);
+ }
+
+ public static TimeSpan operator *(double factor, TimeSpan timeSpan) => timeSpan * factor;
+
+ public static TimeSpan operator /(TimeSpan timeSpan, double divisor)
+ {
+ if (double.IsNaN(divisor))
+ {
+ throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(divisor));
+ }
+
+ double ticks = Math.Round(timeSpan.Ticks / divisor);
+ if (ticks > long.MaxValue | ticks < long.MinValue || double.IsNaN(ticks))
+ {
+ throw new OverflowException(SR.Overflow_TimeSpanTooLong);
+ }
+
+ return FromTicks((long)ticks);
+ }
+
+ // Using floating-point arithmetic directly means that infinities can be returned, which is reasonable
+ // if we consider TimeSpan.FromHours(1) / TimeSpan.Zero asks how many zero-second intervals there are in
+ // an hour for which ∞ is the mathematic correct answer. Having TimeSpan.Zero / TimeSpan.Zero return NaN
+ // is perhaps less useful, but no less useful than an exception.
+ public static double operator /(TimeSpan t1, TimeSpan t2) => t1.Ticks / (double)t2.Ticks;
+
+ public static bool operator ==(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks == t2._ticks;
}
- public static bool operator !=(TimeSpan t1, TimeSpan t2) {
+ public static bool operator !=(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks != t2._ticks;
}
- public static bool operator <(TimeSpan t1, TimeSpan t2) {
+ public static bool operator <(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks < t2._ticks;
}
- public static bool operator <=(TimeSpan t1, TimeSpan t2) {
+ public static bool operator <=(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks <= t2._ticks;
}
- public static bool operator >(TimeSpan t1, TimeSpan t2) {
+ public static bool operator >(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks > t2._ticks;
}
- public static bool operator >=(TimeSpan t1, TimeSpan t2) {
+ public static bool operator >=(TimeSpan t1, TimeSpan t2)
+ {
return t1._ticks >= t2._ticks;
}
@@ -405,16 +515,20 @@ namespace System {
// [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework]
// "TimeSpan_LegacyFormatMode"=dword:00000001
//
- private static bool GetLegacyFormatMode() {
+ private static bool GetLegacyFormatMode()
+ {
return false;
}
private static volatile bool _legacyConfigChecked;
private static volatile bool _legacyMode;
- private static bool LegacyMode {
- get {
- if (!_legacyConfigChecked) {
+ private static bool LegacyMode
+ {
+ get
+ {
+ if (!_legacyConfigChecked)
+ {
// no need to lock - idempotent
_legacyMode = GetLegacyFormatMode();
_legacyConfigChecked = true;
diff --git a/src/mscorlib/src/System/TimeZone.cs b/src/mscorlib/src/System/TimeZone.cs
deleted file mode 100644
index 8ede49293e..0000000000
--- a/src/mscorlib/src/System/TimeZone.cs
+++ /dev/null
@@ -1,246 +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.
-
-/*============================================================
-**
-** Class: TimeZone
-**
-**
-** Purpose:
-** This class is used to represent a TimeZone. It
-** has methods for converting a DateTime to UTC from local time
-** and to local time from UTC and methods for getting the
-** standard name and daylight name of the time zone.
-**
-** The only TimeZone that we support in version 1 is the
-** CurrentTimeZone as determined by the system timezone.
-**
-**
-============================================================*/
-namespace System {
- using System;
- using System.Text;
- using System.Threading;
- using System.Collections;
- using System.Globalization;
-
- [Serializable]
- [Obsolete("System.TimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo instead.")]
- public abstract class TimeZone {
- private static volatile TimeZone currentTimeZone = null;
-
- // 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;
- }
- }
-
-
- protected TimeZone() {
- }
-
- public static TimeZone CurrentTimeZone {
- get {
- //Grabbing the cached value is required at the top of this function so that
- //we don't incur a race condition with the ResetTimeZone method below.
- TimeZone tz = currentTimeZone;
- if (tz == null) {
- lock(InternalSyncObject) {
- if (currentTimeZone == null) {
- currentTimeZone = new CurrentSystemTimeZone();
- }
- tz = currentTimeZone;
- }
- }
- return (tz);
- }
- }
-
- //This method is called by CultureInfo.ClearCachedData in response to control panel
- //change events. It must be synchronized because otherwise there is a race condition
- //with the CurrentTimeZone property above.
- internal static void ResetTimeZone() {
- if (currentTimeZone!=null) {
- lock(InternalSyncObject) {
- currentTimeZone = null;
- }
- }
- }
-
- public abstract String StandardName {
- get;
- }
-
- public abstract String DaylightName {
- get;
- }
-
- public abstract TimeSpan GetUtcOffset(DateTime time);
-
- //
- // Converts the specified datatime to the Universal time base on the current timezone
- //
- public virtual DateTime ToUniversalTime(DateTime time) {
- if (time.Kind == DateTimeKind.Utc) {
- return time;
- }
- long tickCount = time.Ticks - GetUtcOffset(time).Ticks;
- if (tickCount>DateTime.MaxTicks) {
- return new DateTime(DateTime.MaxTicks, DateTimeKind.Utc);
- }
- if (tickCount<DateTime.MinTicks) {
- return new DateTime(DateTime.MinTicks, DateTimeKind.Utc);
- }
- return new DateTime(tickCount, DateTimeKind.Utc);
- }
-
- //
- // Convert the specified datetime value from UTC to the local time based on the time zone.
- //
- public virtual DateTime ToLocalTime(DateTime time) {
- if (time.Kind == DateTimeKind.Local) {
- return time;
- }
- Boolean isAmbiguousLocalDst = false;
- Int64 offset = ((CurrentSystemTimeZone)(TimeZone.CurrentTimeZone)).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst);
- return new DateTime(time.Ticks + offset, DateTimeKind.Local, isAmbiguousLocalDst);
- }
-
- // Return an array of DaylightTime which reflects the daylight saving periods in a particular year.
- // We currently only support having one DaylightSavingTime per year.
- // If daylight saving time is not used in this timezone, null will be returned.
- public abstract DaylightTime GetDaylightChanges(int year);
-
- public virtual bool IsDaylightSavingTime(DateTime time) {
- return (IsDaylightSavingTime(time, GetDaylightChanges(time.Year)));
- }
-
- // Check if the specified time is in a daylight saving time. Allows the user to
- // specify the array of Daylight Saving Times.
- public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) {
- return CalculateUtcOffset(time, daylightTimes)!=TimeSpan.Zero;
- }
-
- //
- // NOTENOTE: Implementation detail
- // In the transition from standard time to daylight saving time,
- // if we convert local time to Universal time, we can have the
- // following (take PST as an example):
- // Local Universal UTC Offset
- // ----- --------- ----------
- // 01:00AM 09:00 -8:00
- // 02:00 (=> 03:00) 10:00 -8:00 [This time doesn't actually exist, but it can be created from DateTime]
- // 03:00 10:00 -7:00
- // 04:00 11:00 -7:00
- // 05:00 12:00 -7:00
- //
- // So from 02:00 - 02:59:59, we should return the standard offset, instead of the daylight saving offset.
- //
- // In the transition from daylight saving time to standard time,
- // if we convert local time to Universal time, we can have the
- // following (take PST as an example):
- // Local Universal UTC Offset
- // ----- --------- ----------
- // 01:00AM 08:00 -7:00
- // 02:00 (=> 01:00) 09:00 -8:00
- // 02:00 10:00 -8:00
- // 03:00 11:00 -8:00
- // 04:00 12:00 -8:00
- //
- // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this.
- // But note that there are two 01:00 in the local time.
-
- //
- // And imagine if the daylight saving offset is negative (although this does not exist in real life)
- // In the transition from standard time to daylight saving time,
- // if we convert local time to Universal time, we can have the
- // following (take PST as an example, but the daylight saving offset is -01:00):
- // Local Universal UTC Offset
- // ----- --------- ----------
- // 01:00AM 09:00 -8:00
- // 02:00 (=> 01:00) 10:00 -9:00
- // 02:00 11:00 -9:00
- // 03:00 12:00 -9:00
- // 04:00 13:00 -9:00
- // 05:00 14:00 -9:00
- //
- // So in this case, the 02:00 does exist after the first 2:00 rolls back to 01:00. We don't need to special case this.
- //
- // In the transition from daylight saving time to standard time,
- // if we convert local time to Universal time, we can have the
- // following (take PST as an example, daylight saving offset is -01:00):
- //
- // Local Universal UTC Offset
- // ----- --------- ----------
- // 01:00AM 10:00 -9:00
- // 02:00 (=> 03:00) 11:00 -9:00
- // 03:00 11:00 -8:00
- // 04:00 12:00 -8:00
- // 05:00 13:00 -8:00
- // 06:00 14:00 -8:00
- //
- // So from 02:00 - 02:59:59, we should return the daylight saving offset, instead of the standard offset.
- //
- internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) {
- if (daylightTimes==null) {
- return TimeSpan.Zero;
- }
- DateTimeKind kind = time.Kind;
- if (kind == DateTimeKind.Utc) {
- return TimeSpan.Zero;
- }
-
- DateTime startTime;
- DateTime endTime;
-
- // startTime and endTime represent the period from either the start of DST to the end and includes the
- // potentially overlapped times
- startTime = daylightTimes.Start + daylightTimes.Delta;
- endTime = daylightTimes.End;
-
- // For normal time zones, the ambiguous hour is the last hour of daylight saving when you wind the
- // clock back. It is theoretically possible to have a positive delta, (which would really be daylight
- // reduction time), where you would have to wind the clock back in the begnning.
- DateTime ambiguousStart;
- DateTime ambiguousEnd;
- if (daylightTimes.Delta.Ticks > 0) {
- ambiguousStart = endTime - daylightTimes.Delta;
- ambiguousEnd = endTime;
- } else {
- ambiguousStart = startTime;
- ambiguousEnd = startTime - daylightTimes.Delta;
- }
-
- Boolean isDst = false;
- if (startTime > endTime) {
- // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
- // Note, the summer in the southern hemisphere begins late in the year.
- if (time >= startTime || time < endTime) {
- isDst = true;
- }
- }
- else if (time>=startTime && time < endTime) {
- // In northern hemisphere, the daylight saving time starts in the middle of the year.
- isDst = true;
- }
-
- // If this date was previously converted from a UTC date and we were able to detect that the local
- // DateTime would be ambiguous, this data is stored in the DateTime to resolve this ambiguity.
- if (isDst && time >= ambiguousStart && time < ambiguousEnd) {
- isDst = time.IsAmbiguousDaylightSavingTime();
- }
-
- if (isDst) {
- return daylightTimes.Delta;
- }
- return TimeSpan.Zero;
- }
- }
-}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
index d27d2386e2..c0c27eeab7 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
@@ -144,22 +144,22 @@ namespace System
{
if (dateStart.Kind != DateTimeKind.Unspecified && dateStart.Kind != DateTimeKind.Utc)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"), nameof(dateStart));
+ throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, nameof(dateStart));
}
if (dateEnd.Kind != DateTimeKind.Unspecified && dateEnd.Kind != DateTimeKind.Utc)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"), nameof(dateEnd));
+ throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, nameof(dateEnd));
}
if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_TransitionTimesAreIdentical"), nameof(daylightTransitionEnd));
+ throw new ArgumentException(SR.Argument_TransitionTimesAreIdentical, nameof(daylightTransitionEnd));
}
if (dateStart > dateEnd)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_OutOfOrderDateTimes"), nameof(dateStart));
+ throw new ArgumentException(SR.Argument_OutOfOrderDateTimes, nameof(dateStart));
}
// This cannot use UtcOffsetOutOfRange to account for the scenario where Samoa moved across the International Date Line,
@@ -168,22 +168,22 @@ namespace System
// to be -23 (what it takes to go from UTC+13 to UTC-10)
if (daylightDelta.TotalHours < -23.0 || daylightDelta.TotalHours > 14.0)
{
- throw new ArgumentOutOfRangeException(nameof(daylightDelta), daylightDelta, Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
+ throw new ArgumentOutOfRangeException(nameof(daylightDelta), daylightDelta, SR.ArgumentOutOfRange_UtcOffset);
}
if (daylightDelta.Ticks % TimeSpan.TicksPerMinute != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"), nameof(daylightDelta));
+ throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(daylightDelta));
}
if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"), nameof(dateStart));
+ throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateStart));
}
if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTimeOfDay"), nameof(dateEnd));
+ throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, nameof(dateEnd));
}
Contract.EndContractBlock();
}
@@ -200,7 +200,7 @@ namespace System
}
catch (ArgumentException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
@@ -221,7 +221,7 @@ namespace System
info.AddValue("NoDaylightTransitions", _noDaylightTransitions);
}
- AdjustmentRule(SerializationInfo info, StreamingContext context)
+ private AdjustmentRule(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
diff --git a/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs b/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
index 9c1d5c3502..c52f7307d8 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
@@ -112,11 +112,11 @@ namespace System
}
catch (ArgumentException ex)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
+ throw new SerializationException(SR.Serialization_InvalidData, ex);
}
catch (InvalidTimeZoneException ex)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), ex);
+ throw new SerializationException(SR.Serialization_InvalidData, ex);
}
}
@@ -181,7 +181,7 @@ namespace System
{
if (c != Esc && c != Sep && c != Lhs && c != Rhs)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidEscapeSequence", c));
+ throw new SerializationException(SR.Format(SR.Serialization_InvalidEscapeSequence, c));
}
}
@@ -194,7 +194,7 @@ namespace System
{
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
State tokenState = State.NotEscaped;
@@ -236,7 +236,7 @@ namespace System
case '\0':
// invalid character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
default:
break;
@@ -244,7 +244,7 @@ namespace System
}
}
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
/// <summary>
@@ -258,11 +258,11 @@ namespace System
// first verify the internal state of the object
if (_state == State.EndOfLine)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
State tokenState = State.NotEscaped;
StringBuilder token = StringBuilderCache.Acquire(InitialCapacityForString);
@@ -286,11 +286,11 @@ namespace System
case Lhs:
// '[' is an unexpected character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
case Rhs:
// ']' is an unexpected character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
case Sep:
_currentTokenStartIndex = i + 1;
@@ -306,7 +306,7 @@ namespace System
case '\0':
// invalid character
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
default:
token.Append(_serializedText[i]);
@@ -320,10 +320,10 @@ namespace System
if (tokenState == State.Escaped)
{
// we are at the end of the serialized text but we are in an escaped state
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidEscapeSequence", string.Empty));
+ throw new SerializationException(SR.Format(SR.Serialization_InvalidEscapeSequence, string.Empty));
}
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
/// <summary>
@@ -335,7 +335,7 @@ namespace System
DateTime time;
if (!DateTime.TryParseExact(token, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out time))
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
return time;
}
@@ -352,7 +352,7 @@ namespace System
}
catch (ArgumentOutOfRangeException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
@@ -365,7 +365,7 @@ namespace System
int value;
if (!int.TryParse(token, NumberStyles.AllowLeadingSign /* "[sign]digits" */, CultureInfo.InvariantCulture, out value))
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
return value;
}
@@ -391,11 +391,11 @@ namespace System
// the AdjustmentRule array must end with a separator
if (_state == State.EndOfLine)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
return count != 0 ? rules.ToArray() : null;
@@ -414,7 +414,7 @@ namespace System
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
// check to see if the very first token we see is the separator
@@ -426,7 +426,7 @@ namespace System
// verify the current token is a left-hand-side marker ("[")
if (_serializedText[_currentTokenStartIndex] != Lhs)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
_currentTokenStartIndex++;
@@ -442,7 +442,7 @@ namespace System
if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
// Check if we have baseUtcOffsetDelta in the serialized string and then deserialize it
@@ -460,7 +460,7 @@ namespace System
if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
if (_serializedText[_currentTokenStartIndex] != Rhs)
@@ -486,7 +486,7 @@ namespace System
}
catch (ArgumentException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
// finally set the state to either EndOfLine or StartOfToken for the next caller
@@ -514,19 +514,19 @@ namespace System
//
// we are at the end of the line or we are starting at a "]" character
//
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
// verify the current token is a left-hand-side marker ("[")
if (_serializedText[_currentTokenStartIndex] != Lhs)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
_currentTokenStartIndex++;
@@ -534,7 +534,7 @@ namespace System
if (isFixedDate != 0 && isFixedDate != 1)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
TransitionTime transition;
@@ -554,7 +554,7 @@ namespace System
}
catch (ArgumentException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
else
@@ -568,7 +568,7 @@ namespace System
}
catch (ArgumentException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
@@ -576,7 +576,7 @@ namespace System
if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
if (_serializedText[_currentTokenStartIndex] != Rhs)
@@ -606,7 +606,7 @@ namespace System
if (!sepFound)
{
// we MUST end on a separator
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"));
+ throw new SerializationException(SR.Serialization_InvalidData);
}
// finally set the state to either EndOfLine or StartOfToken for the next caller
diff --git a/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
index dedcb880a4..1e1d9d328b 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.TransitionTime.cs
@@ -75,37 +75,37 @@ namespace System
{
if (timeOfDay.Kind != DateTimeKind.Unspecified)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeKindMustBeUnspecified"), nameof(timeOfDay));
+ throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecified, nameof(timeOfDay));
}
// Month range 1-12
if (month < 1 || month > 12)
{
- throw new ArgumentOutOfRangeException(nameof(month), Environment.GetResourceString("ArgumentOutOfRange_MonthParam"));
+ throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_MonthParam);
}
// Day range 1-31
if (day < 1 || day > 31)
{
- throw new ArgumentOutOfRangeException(nameof(day), Environment.GetResourceString("ArgumentOutOfRange_DayParam"));
+ throw new ArgumentOutOfRangeException(nameof(day), SR.ArgumentOutOfRange_DayParam);
}
// Week range 1-5
if (week < 1 || week > 5)
{
- throw new ArgumentOutOfRangeException(nameof(week), Environment.GetResourceString("ArgumentOutOfRange_Week"));
+ throw new ArgumentOutOfRangeException(nameof(week), SR.ArgumentOutOfRange_Week);
}
// DayOfWeek range 0-6
if ((int)dayOfWeek < 0 || (int)dayOfWeek > 6)
{
- throw new ArgumentOutOfRangeException(nameof(dayOfWeek), Environment.GetResourceString("ArgumentOutOfRange_DayOfWeek"));
+ throw new ArgumentOutOfRangeException(nameof(dayOfWeek), SR.ArgumentOutOfRange_DayOfWeek);
}
Contract.EndContractBlock();
if (timeOfDay.Year != 1 || timeOfDay.Month != 1 || timeOfDay.Day != 1 || (timeOfDay.Ticks % TimeSpan.TicksPerMillisecond != 0))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeHasTicks"), nameof(timeOfDay));
+ throw new ArgumentException(SR.Argument_DateTimeHasTicks, nameof(timeOfDay));
}
}
@@ -120,7 +120,7 @@ namespace System
}
catch (ArgumentException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
@@ -140,7 +140,7 @@ namespace System
info.AddValue("IsFixedDateRule", _isFixedDateRule);
}
- TransitionTime(SerializationInfo info, StreamingContext context)
+ private TransitionTime(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
diff --git a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
index b94c8b71c1..02baadcfe5 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
@@ -97,6 +97,12 @@ namespace System
private void GetDisplayName(Interop.GlobalizationInterop.TimeZoneDisplayNameType nameType, ref string displayName)
{
+ if (GlobalizationMode.Invariant)
+ {
+ displayName = _standardDisplayName;
+ return;
+ }
+
string timeZoneDisplayName;
bool result = Interop.CallStringMethod(
(locale, id, type, stringBuilder) => Interop.GlobalizationInterop.GetTimeZoneDisplayName(
@@ -128,8 +134,8 @@ namespace System
return Array.Empty<AdjustmentRule>();
}
- // The rules we use in Unix cares mostly about the start and end dates but doesn’t fill the transition start and end info.
- // as the rules now is public, we should fill it properly so the caller doesn’t have to know how we use it internally
+ // The rules we use in Unix care mostly about the start and end dates but don't fill the transition start and end info.
+ // as the rules now is public, we should fill it properly so the caller doesn't have to know how we use it internally
// and can use it as it is used in Windows
AdjustmentRule[] rules = new AdjustmentRule[_adjustmentRules.Length];
@@ -138,10 +144,14 @@ namespace System
{
var rule = _adjustmentRules[i];
var start = rule.DateStart.Kind == DateTimeKind.Utc ?
- new DateTime(TimeZoneInfo.ConvertTime(rule.DateStart, this).Ticks, DateTimeKind.Unspecified) :
+ // At the daylight start we didn't start the daylight saving yet then we convert to Local time
+ // by adding the _baseUtcOffset to the UTC time
+ new DateTime(rule.DateStart.Ticks + _baseUtcOffset.Ticks, DateTimeKind.Unspecified) :
rule.DateStart;
var end = rule.DateEnd.Kind == DateTimeKind.Utc ?
- new DateTime(TimeZoneInfo.ConvertTime(rule.DateEnd, this).Ticks - 1, DateTimeKind.Unspecified) :
+ // At the daylight saving end, the UTC time is mapped to local time which is already shifted by the daylight delta
+ // we calculate the local time by adding _baseUtcOffset + DaylightDelta to the UTC time
+ new DateTime(rule.DateEnd.Ticks + _baseUtcOffset.Ticks + rule.DaylightDelta.Ticks, DateTimeKind.Unspecified) :
rule.DateEnd;
var startTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, start.Hour, start.Minute, start.Second), start.Month, start.Day);
@@ -209,7 +219,7 @@ namespace System
}
catch (IOException ex)
{
- e = new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidFileData", id, timeZoneFilePath), ex);
+ e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath), ex);
return TimeZoneInfoResult.InvalidTimeZoneException;
}
@@ -217,7 +227,7 @@ namespace System
if (value == null)
{
- e = new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidFileData", id, timeZoneFilePath));
+ e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath));
return TimeZoneInfoResult.InvalidTimeZoneException;
}
@@ -561,7 +571,7 @@ namespace System
}
else if (id.Length == 0 || id.Contains("\0"))
{
- throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id));
+ throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo value;
@@ -588,11 +598,11 @@ namespace System
}
else if (result == TimeZoneInfoResult.SecurityException)
{
- throw new SecurityException(Environment.GetResourceString("Security_CannotReadFileData", id), e);
+ throw new SecurityException(SR.Format(SR.Security_CannotReadFileData, id), e);
}
else
{
- throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id), e);
+ throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
@@ -916,14 +926,14 @@ namespace System
return transitionTypes[0];
}
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_NoTTInfoStructures"));
+ throw new InvalidTimeZoneException(SR.InvalidTimeZone_NoTTInfoStructures);
}
/// <summary>
/// Creates an AdjustmentRule given the POSIX TZ environment variable string.
/// </summary>
/// <remarks>
- /// See http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html for the format and semantics of this POSX string.
+ /// See http://man7.org/linux/man-pages/man3/tzset.3.html for the format and semantics of this POSX string.
/// </remarks>
private static AdjustmentRule TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset)
{
@@ -1050,7 +1060,7 @@ namespace System
DayOfWeek day;
if (!TZif_ParseMDateRule(date, out month, out week, out day))
{
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_UnparseablePosixMDateString", date));
+ throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_UnparseablePosixMDateString, date));
}
DateTime timeOfDay;
@@ -1093,7 +1103,7 @@ namespace System
// One of them *could* be supported if we relaxed the TransitionTime validation rules, and allowed
// "IsFixedDateRule = true, Month = 0, Day = n" to mean the nth day of the year, picking one of the rules above
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_JulianDayNotSupported"));
+ throw new InvalidTimeZoneException(SR.InvalidTimeZone_JulianDayNotSupported);
}
}
@@ -1185,8 +1195,32 @@ namespace System
return !string.IsNullOrEmpty(standardName) && !string.IsNullOrEmpty(standardOffset);
}
- private static string TZif_ParsePosixName(string posixFormat, ref int index) =>
- TZif_ParsePosixString(posixFormat, ref index, c => char.IsDigit(c) || c == '+' || c == '-' || c == ',');
+ private static string TZif_ParsePosixName(string posixFormat, ref int index)
+ {
+ bool isBracketEnclosed = index < posixFormat.Length && posixFormat[index] == '<';
+ if (isBracketEnclosed)
+ {
+ // move past the opening bracket
+ index++;
+
+ string result = TZif_ParsePosixString(posixFormat, ref index, c => c == '>');
+
+ // move past the closing bracket
+ if (index < posixFormat.Length && posixFormat[index] == '>')
+ {
+ index++;
+ }
+
+ return result;
+ }
+ else
+ {
+ return TZif_ParsePosixString(
+ posixFormat,
+ ref index,
+ c => char.IsDigit(c) || c == '+' || c == '-' || c == ',');
+ }
+ }
private static string TZif_ParsePosixOffset(string posixFormat, ref int index) =>
TZif_ParsePosixString(posixFormat, ref index, c => !char.IsDigit(c) && c != '+' && c != '-' && c != ':');
@@ -1391,7 +1425,7 @@ namespace System
{
if (data == null || data.Length < index + Length)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoInvalidTZif"), nameof(data));
+ throw new ArgumentException(SR.Argument_TimeZoneInfoInvalidTZif, nameof(data));
}
Contract.EndContractBlock();
UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00));
@@ -1427,7 +1461,7 @@ namespace System
if (Magic != 0x545A6966)
{
// 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif"
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeZoneInfoBadTZif"), nameof(data));
+ throw new ArgumentException(SR.Argument_TimeZoneInfoBadTZif, nameof(data));
}
byte version = data[index + 04];
diff --git a/src/mscorlib/src/System/TimeZoneInfo.Win32.cs b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
index 79ee535505..b6585bd0a0 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Security;
@@ -348,7 +349,7 @@ namespace System
}
else if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains("\0"))
{
- throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id));
+ throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id));
}
TimeZoneInfo value;
@@ -369,15 +370,15 @@ namespace System
}
else if (result == TimeZoneInfoResult.InvalidTimeZoneException)
{
- throw new InvalidTimeZoneException(Environment.GetResourceString("InvalidTimeZone_InvalidRegistryData", id), e);
+ throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e);
}
else if (result == TimeZoneInfoResult.SecurityException)
{
- throw new SecurityException(Environment.GetResourceString("Security_CannotReadRegistryData", id), e);
+ throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e);
}
else
{
- throw new TimeZoneNotFoundException(Environment.GetResourceString("TimeZoneNotFound_MissingData", id), e);
+ throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e);
}
}
@@ -575,8 +576,8 @@ namespace System
// read LastEntry {(yearN, 1, 1) - MaxValue }
// read the FirstEntry and LastEntry key values (ex: "1980", "2038")
- int first = (int)dynamicKey.GetValue(FirstEntryValue, -1, RegistryValueOptions.None);
- int last = (int)dynamicKey.GetValue(LastEntryValue, -1, RegistryValueOptions.None);
+ int first = (int)dynamicKey.GetValue(FirstEntryValue, -1);
+ int last = (int)dynamicKey.GetValue(LastEntryValue, -1);
if (first == -1 || last == -1 || first > last)
{
@@ -586,7 +587,7 @@ namespace System
// read the first year entry
Win32Native.RegistryTimeZoneInformation dtzi;
- byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
+ byte[] regValue = dynamicKey.GetValue(first.ToString(CultureInfo.InvariantCulture)) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
@@ -619,7 +620,7 @@ namespace System
// read the middle year entries
for (int i = first + 1; i < last; i++)
{
- regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
+ regValue = dynamicKey.GetValue(i.ToString(CultureInfo.InvariantCulture)) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
rules = null;
@@ -639,7 +640,7 @@ namespace System
}
// read the last year entry
- regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture), null, RegistryValueOptions.None) as byte[];
+ regValue = dynamicKey.GetValue(last.ToString(CultureInfo.InvariantCulture)) as byte[];
dtzi = new Win32Native.RegistryTimeZoneInformation(regValue);
if (regValue == null || regValue.Length != RegByteLength)
{
@@ -718,7 +719,7 @@ namespace System
}
Win32Native.RegistryTimeZoneInformation registryTimeZoneInfo;
- byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
+ byte[] regValue = key.GetValue(TimeZoneInfoValue) as byte[];
if (regValue == null || regValue.Length != RegByteLength) return false;
registryTimeZoneInfo = new Win32Native.RegistryTimeZoneInformation(regValue);
@@ -755,7 +756,7 @@ namespace System
//
if (result)
{
- string registryStandardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
+ string registryStandardName = key.GetValue(StandardValue, string.Empty) as string;
result = string.Equals(registryStandardName, timeZone.StandardName, StringComparison.Ordinal);
}
return result;
@@ -883,9 +884,9 @@ namespace System
daylightName = string.Empty;
// read the MUI_ registry keys
- string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty, RegistryValueOptions.None) as string;
- string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty, RegistryValueOptions.None) as string;
- string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty, RegistryValueOptions.None) as string;
+ string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string;
+ string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string;
+ string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string;
// try to load the strings from the native resource DLL(s)
if (!string.IsNullOrEmpty(displayNameMuiResource))
@@ -906,15 +907,15 @@ namespace System
// fallback to using the standard registry keys
if (string.IsNullOrEmpty(displayName))
{
- displayName = key.GetValue(DisplayValue, string.Empty, RegistryValueOptions.None) as string;
+ displayName = key.GetValue(DisplayValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(standardName))
{
- standardName = key.GetValue(StandardValue, string.Empty, RegistryValueOptions.None) as string;
+ standardName = key.GetValue(StandardValue, string.Empty) as string;
}
if (string.IsNullOrEmpty(daylightName))
{
- daylightName = key.GetValue(DaylightValue, string.Empty, RegistryValueOptions.None) as string;
+ daylightName = key.GetValue(DaylightValue, string.Empty) as string;
}
return true;
@@ -963,7 +964,7 @@ namespace System
}
Win32Native.RegistryTimeZoneInformation defaultTimeZoneInformation;
- byte[] regValue = key.GetValue(TimeZoneInfoValue, null, RegistryValueOptions.None) as byte[];
+ byte[] regValue = key.GetValue(TimeZoneInfoValue) as byte[];
if (regValue == null || regValue.Length != RegByteLength)
{
// the registry value could not be cast to a byte array
@@ -1016,7 +1017,6 @@ namespace System
e = ex;
return TimeZoneInfoResult.InvalidTimeZoneException;
}
-
}
}
}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.cs b/src/mscorlib/src/System/TimeZoneInfo.cs
index fc5625be2e..29ea33a8ad 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.cs
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
+using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Serialization;
@@ -164,7 +165,7 @@ namespace System
{
if (!SupportsDaylightSavingTime)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), nameof(dateTimeOffset));
+ throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
}
Contract.EndContractBlock();
@@ -180,7 +181,7 @@ namespace System
if (!isAmbiguous)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"), nameof(dateTimeOffset));
+ throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, nameof(dateTimeOffset));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
@@ -210,7 +211,7 @@ namespace System
{
if (!SupportsDaylightSavingTime)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), nameof(dateTime));
+ throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
}
Contract.EndContractBlock();
@@ -240,7 +241,7 @@ namespace System
if (!isAmbiguous)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsNotAmbiguous"), nameof(dateTime));
+ throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, nameof(dateTime));
}
// the passed in dateTime is ambiguous in this TimeZoneInfo instance
@@ -513,7 +514,6 @@ namespace System
if ((dateTime.Kind == DateTimeKind.Unspecified) ||
(dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local))
{
-
// only check Unspecified and (Local when this TimeZoneInfo instance is Local)
AdjustmentRule rule = GetAdjustmentRuleForTime(dateTime);
@@ -650,7 +650,7 @@ namespace System
DateTimeKind sourceKind = cachedData.GetCorrespondingKind(sourceTimeZone);
if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && (dateTime.Kind != DateTimeKind.Unspecified) && (dateTime.Kind != sourceKind))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_ConvertMismatch"), nameof(sourceTimeZone));
+ throw new ArgumentException(SR.Argument_ConvertMismatch, nameof(sourceTimeZone));
}
//
@@ -676,7 +676,7 @@ namespace System
// period that supports DST
if (((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0) && GetIsInvalidTime(dateTime, sourceRule, sourceDaylightTime))
{
- throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeIsInvalid"), nameof(dateTime));
+ throw new ArgumentException(SR.Argument_DateTimeIsInvalid, nameof(dateTime));
}
sourceIsDaylightSavings = GetIsDaylightSavings(dateTime, sourceRule, sourceDaylightTime, flags);
@@ -768,7 +768,7 @@ namespace System
}
if (source.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSerializedString", source), nameof(source));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), nameof(source));
}
Contract.EndContractBlock();
@@ -868,7 +868,6 @@ namespace System
return false;
}
}
-
}
return sameRules;
}
@@ -915,7 +914,6 @@ namespace System
AdjustmentRule[] adjustmentRules,
bool disableDaylightSavingTime)
{
-
bool adjustmentRulesSupportDst;
ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out adjustmentRulesSupportDst);
@@ -1004,16 +1002,16 @@ namespace System
if (adjustmentRulesSupportDst != _supportsDaylightSavingTime)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_CorruptField", "SupportsDaylightSavingTime"));
+ throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime"));
}
}
catch (ArgumentException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
catch (InvalidTimeZoneException e)
{
- throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
+ throw new SerializationException(SR.Serialization_InvalidData, e);
}
}
@@ -1034,7 +1032,7 @@ namespace System
info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime);
}
- TimeZoneInfo(SerializationInfo info, StreamingContext context)
+ private TimeZoneInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
@@ -1065,14 +1063,29 @@ namespace System
(dateTime + BaseUtcOffset).Date :
dateTime.Date;
- for (int i = 0; i < _adjustmentRules.Length; i++)
+ int low = 0;
+ int high = _adjustmentRules.Length - 1;
+
+ while (low <= high)
{
- AdjustmentRule rule = _adjustmentRules[i];
- AdjustmentRule previousRule = i > 0 ? _adjustmentRules[i - 1] : rule;
- if (IsAdjustmentRuleValid(rule, previousRule, dateTime, date, dateTimeisUtc))
+ int median = low + ((high - low) >> 1);
+
+ AdjustmentRule rule = _adjustmentRules[median];
+ AdjustmentRule previousRule = median > 0 ? _adjustmentRules[median - 1] : rule;
+
+ int compareResult = CompareAdjustmentRuleToDateTime(rule, previousRule, dateTime, date, dateTimeisUtc);
+ if (compareResult == 0)
{
return rule;
}
+ else if (compareResult < 0)
+ {
+ low = median + 1;
+ }
+ else
+ {
+ high = median - 1;
+ }
}
return null;
@@ -1081,7 +1094,12 @@ namespace System
/// <summary>
/// Determines if 'rule' is the correct AdjustmentRule for the given dateTime.
/// </summary>
- private bool IsAdjustmentRuleValid(AdjustmentRule rule, AdjustmentRule previousRule,
+ /// <returns>
+ /// A value less than zero if rule is for times before dateTime.
+ /// Zero if rule is correct for dateTime.
+ /// A value greater than zero if rule is for times after dateTime.
+ /// </returns>
+ private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule,
DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc)
{
bool isAfterStart;
@@ -1103,7 +1121,7 @@ namespace System
if (!isAfterStart)
{
- return false;
+ return 1;
}
bool isBeforeEnd;
@@ -1121,7 +1139,7 @@ namespace System
isBeforeEnd = dateOnly <= rule.DateEnd;
}
- return isBeforeEnd;
+ return isBeforeEnd ? 0 : -1;
}
/// <summary>
@@ -1430,7 +1448,6 @@ namespace System
}
catch (ArgumentOutOfRangeException) { }
}
-
}
}
@@ -1884,18 +1901,17 @@ namespace System
if (id.Length == 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidId", id), nameof(id));
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), nameof(id));
}
if (UtcOffsetOutOfRange(baseUtcOffset))
{
-
- throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), Environment.GetResourceString("ArgumentOutOfRange_UtcOffset"));
+ throw new ArgumentOutOfRangeException(nameof(baseUtcOffset), SR.ArgumentOutOfRange_UtcOffset);
}
if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
{
- throw new ArgumentException(Environment.GetResourceString("Argument_TimeSpanHasSeconds"), nameof(baseUtcOffset));
+ throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, nameof(baseUtcOffset));
}
Contract.EndContractBlock();
@@ -1919,7 +1935,7 @@ namespace System
if (current == null)
{
- throw new InvalidTimeZoneException(Environment.GetResourceString("Argument_AdjustmentRulesNoNulls"));
+ throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls);
}
// FUTURE: check to see if this rule supports Daylight Saving Time
@@ -1928,13 +1944,13 @@ namespace System
if (UtcOffsetOutOfRange(baseUtcOffset + current.DaylightDelta))
{
- throw new InvalidTimeZoneException(Environment.GetResourceString("ArgumentOutOfRange_UtcOffsetAndDaylightDelta"));
+ throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta);
}
if (prev != null && current.DateStart <= prev.DateEnd)
{
// verify the rules are in chronological order and the DateStart/DateEnd do not overlap
- throw new InvalidTimeZoneException(Environment.GetResourceString("Argument_AdjustmentRulesOutOfOrder"));
+ throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder);
}
}
}
diff --git a/src/mscorlib/src/System/TimeZoneNotFoundException.cs b/src/mscorlib/src/System/TimeZoneNotFoundException.cs
deleted file mode 100644
index ee21c2524f..0000000000
--- a/src/mscorlib/src/System/TimeZoneNotFoundException.cs
+++ /dev/null
@@ -1,28 +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.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class TimeZoneNotFoundException : Exception
- {
- public TimeZoneNotFoundException()
- {
- }
-
- public TimeZoneNotFoundException(String message)
- : base(message)
- {
- }
-
- public TimeZoneNotFoundException(String message, Exception innerException)
- : base(message, innerException)
- {
- }
-
- protected TimeZoneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/TimeoutException.cs b/src/mscorlib/src/System/TimeoutException.cs
deleted file mode 100644
index 32775a1c56..0000000000
--- a/src/mscorlib/src/System/TimeoutException.cs
+++ /dev/null
@@ -1,41 +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 class for Timeout
-**
-**
-=============================================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public class TimeoutException : SystemException
- {
- public TimeoutException()
- : base(SR.Arg_TimeoutException)
- {
- HResult = __HResults.COR_E_TIMEOUT;
- }
-
- public TimeoutException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_TIMEOUT;
- }
-
- public TimeoutException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_TIMEOUT;
- }
-
- protected TimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/Tuple.cs b/src/mscorlib/src/System/Tuple.cs
index bb0dbcad6f..a118df02bd 100644
--- a/src/mscorlib/src/System/Tuple.cs
+++ b/src/mscorlib/src/System/Tuple.cs
@@ -1,6 +1,7 @@
// 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.Collections;
@@ -15,7 +16,6 @@ using System.Runtime.CompilerServices;
namespace System
{
-
/// <summary>
/// Helper so we can call some tuple methods recursively without knowing the underlying types.
/// </summary>
@@ -107,7 +107,6 @@ namespace System
[Serializable]
public class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
public T1 Item1 { get { return m_Item1; } }
@@ -149,7 +148,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
return comparer.Compare(m_Item1, objTuple.m_Item1);
@@ -207,7 +206,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
@@ -252,7 +250,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
@@ -322,7 +320,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
@@ -370,7 +367,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
@@ -448,7 +445,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
@@ -499,7 +495,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
@@ -585,7 +581,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
@@ -639,7 +634,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
@@ -733,7 +728,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
@@ -790,7 +784,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
@@ -892,7 +886,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
@@ -952,7 +945,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
@@ -1062,7 +1055,6 @@ namespace System
[Serializable]
public class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple
{
-
private readonly T1 m_Item1;
private readonly T2 m_Item2;
private readonly T3 m_Item3;
@@ -1085,7 +1077,7 @@ namespace System
{
if (!(rest is ITupleInternal))
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleLastArgumentNotATuple"));
+ throw new ArgumentException(SR.ArgumentException_TupleLastArgumentNotATuple);
}
m_Item1 = item1;
@@ -1130,7 +1122,7 @@ namespace System
if (objTuple == null)
{
- throw new ArgumentException(Environment.GetResourceString("ArgumentException_TupleIncorrectType", this.GetType().ToString()), "other");
+ throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, this.GetType().ToString()), "other");
}
int c = 0;
diff --git a/src/mscorlib/src/System/TupleExtensions.cs b/src/mscorlib/src/System/TupleExtensions.cs
deleted file mode 100644
index b63cb41213..0000000000
--- a/src/mscorlib/src/System/TupleExtensions.cs
+++ /dev/null
@@ -1,930 +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.ComponentModel;
-using System.Runtime.CompilerServices;
-
-namespace System
-{
- /// <summary>
- /// Provides extension methods for <see cref="Tuple"/> instances to interop with C# tuples features (deconstruction syntax, converting from and to <see cref="ValueTuple"/>).
- /// </summary>
- public static class TupleExtensions
- {
- #region Deconstruct
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 1 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1>(
- this Tuple<T1> value,
- out T1 item1)
- {
- item1 = value.Item1;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 2 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2>(
- this Tuple<T1, T2> value,
- out T1 item1, out T2 item2)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 3 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3>(
- this Tuple<T1, T2, T3> value,
- out T1 item1, out T2 item2, out T3 item3)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 4 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4>(
- this Tuple<T1, T2, T3, T4> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 5 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5>(
- this Tuple<T1, T2, T3, T4, T5> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 6 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6>(
- this Tuple<T1, T2, T3, T4, T5, T6> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 7 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 8 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 9 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 10 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 11 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 12 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 13 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 14 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 15 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 16 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- item16 = value.Rest.Rest.Item2;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 17 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- item16 = value.Rest.Rest.Item2;
- item17 = value.Rest.Rest.Item3;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 18 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- item16 = value.Rest.Rest.Item2;
- item17 = value.Rest.Rest.Item3;
- item18 = value.Rest.Rest.Item4;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 19 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- item16 = value.Rest.Rest.Item2;
- item17 = value.Rest.Rest.Item3;
- item18 = value.Rest.Rest.Item4;
- item19 = value.Rest.Rest.Item5;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 20 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- item16 = value.Rest.Rest.Item2;
- item17 = value.Rest.Rest.Item3;
- item18 = value.Rest.Rest.Item4;
- item19 = value.Rest.Rest.Item5;
- item20 = value.Rest.Rest.Item6;
- }
-
- /// <summary>
- /// Deconstruct a properly nested <see cref="Tuple"/> with 21 elements.
- /// </summary>
- [EditorBrowsable(EditorBrowsableState.Never)]
- public static void Deconstruct<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>> value,
- out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20, out T21 item21)
- {
- item1 = value.Item1;
- item2 = value.Item2;
- item3 = value.Item3;
- item4 = value.Item4;
- item5 = value.Item5;
- item6 = value.Item6;
- item7 = value.Item7;
- item8 = value.Rest.Item1;
- item9 = value.Rest.Item2;
- item10 = value.Rest.Item3;
- item11 = value.Rest.Item4;
- item12 = value.Rest.Item5;
- item13 = value.Rest.Item6;
- item14 = value.Rest.Item7;
- item15 = value.Rest.Rest.Item1;
- item16 = value.Rest.Rest.Item2;
- item17 = value.Rest.Rest.Item3;
- item18 = value.Rest.Rest.Item4;
- item19 = value.Rest.Rest.Item5;
- item20 = value.Rest.Rest.Item6;
- item21 = value.Rest.Rest.Item7;
- }
- #endregion
-
- #region ToValueTuple
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 1 element.
- /// </summary>
- public static ValueTuple<T1>
- ToValueTuple<T1>(
- this Tuple<T1> value)
- {
- return ValueTuple.Create(value.Item1);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 2 elements.
- /// </summary>
- public static ValueTuple<T1, T2>
- ToValueTuple<T1, T2>(
- this Tuple<T1, T2> value)
- {
- return ValueTuple.Create(value.Item1, value.Item2);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 3 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3>
- ToValueTuple<T1, T2, T3>(
- this Tuple<T1, T2, T3> value)
- {
- return ValueTuple.Create(value.Item1, value.Item2, value.Item3);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 4 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4>
- ToValueTuple<T1, T2, T3, T4>(
- this Tuple<T1, T2, T3, T4> value)
- {
- return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 5 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5>
- ToValueTuple<T1, T2, T3, T4, T5>(
- this Tuple<T1, T2, T3, T4, T5> value)
- {
- return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 6 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6>
- ToValueTuple<T1, T2, T3, T4, T5, T6>(
- this Tuple<T1, T2, T3, T4, T5, T6> value)
- {
- return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 7 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7> value)
- {
- return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 8 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 9 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1, value.Rest.Item2));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 10 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 11 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 12 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 13 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 14 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 15 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 16 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 17 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 18 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 19 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 20 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="ValueTuple"/> from a properly nested <see cref="Tuple"/> with 21 elements.
- /// </summary>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20, T21>>>
- ToValueTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
- this Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>> value)
- {
- return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6, value.Rest.Rest.Item7)));
- }
- #endregion
-
- #region ToTuple
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 1 element.
- /// </summary>
- public static Tuple<T1>
- ToTuple<T1>(
- this ValueTuple<T1> value)
- {
- return Tuple.Create(value.Item1);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 2 elements.
- /// </summary>
- public static Tuple<T1, T2>
- ToTuple<T1, T2>(
- this ValueTuple<T1, T2> value)
- {
- return Tuple.Create(value.Item1, value.Item2);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 3 elements.
- /// </summary>
- public static Tuple<T1, T2, T3>
- ToTuple<T1, T2, T3>(
- this ValueTuple<T1, T2, T3> value)
- {
- return Tuple.Create(value.Item1, value.Item2, value.Item3);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 4 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4>
- ToTuple<T1, T2, T3, T4>(
- this ValueTuple<T1, T2, T3, T4> value)
- {
- return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 5 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5>
- ToTuple<T1, T2, T3, T4, T5>(
- this ValueTuple<T1, T2, T3, T4, T5> value)
- {
- return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 6 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6>
- ToTuple<T1, T2, T3, T4, T5, T6>(
- this ValueTuple<T1, T2, T3, T4, T5, T6> value)
- {
- return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 7 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7>
- ToTuple<T1, T2, T3, T4, T5, T6, T7>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7> value)
- {
- return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7);
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 8 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 9 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1, value.Rest.Item2));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 10 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 11 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 12 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 13 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 14 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 15 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 16 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 17 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 18 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 19 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 20 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6)));
- }
-
- /// <summary>
- /// Make a properly nested <see cref="Tuple"/> from a properly nested <see cref="ValueTuple"/> with 21 elements.
- /// </summary>
- public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8, T9, T10, T11, T12, T13, T14, Tuple<T15, T16, T17, T18, T19, T20, T21>>>
- ToTuple<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21>(
- this ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8, T9, T10, T11, T12, T13, T14, ValueTuple<T15, T16, T17, T18, T19, T20, T21>>> value)
- {
- return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7,
- CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7,
- Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6, value.Rest.Rest.Item7)));
- }
- #endregion
-
- private static ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLong<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : struct, ITuple =>
- new ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
-
- private static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : ITuple =>
- new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
- }
-} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Type.CoreCLR.cs b/src/mscorlib/src/System/Type.CoreCLR.cs
new file mode 100644
index 0000000000..9c443b472a
--- /dev/null
+++ b/src/mscorlib/src/System/Type.CoreCLR.cs
@@ -0,0 +1,206 @@
+// 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.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+using StackCrawlMark = System.Threading.StackCrawlMark;
+
+namespace System
+{
+ public abstract partial class Type : MemberInfo, IReflect
+ {
+ public bool IsInterface
+ {
+ get
+ {
+ RuntimeType rt = this as RuntimeType;
+ if (rt != null)
+ return RuntimeTypeHandle.IsInterface(rt);
+ return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface);
+ }
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Type GetType(String typeName, bool throwOnError, bool ignoreCase)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeType.GetType(typeName, throwOnError, ignoreCase, false, ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Type GetType(String typeName, bool throwOnError)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeType.GetType(typeName, throwOnError, false, false, ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Type GetType(String typeName)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return RuntimeType.GetType(typeName, false, false, false, ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Type GetType(
+ string typeName,
+ Func<AssemblyName, Assembly> assemblyResolver,
+ Func<Assembly, string, bool, Type> typeResolver)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, false, false, ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Type GetType(
+ string typeName,
+ Func<AssemblyName, Assembly> assemblyResolver,
+ Func<Assembly, string, bool, Type> typeResolver,
+ bool throwOnError)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError, false, ref stackMark);
+ }
+
+ [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
+ public static Type GetType(
+ string typeName,
+ Func<AssemblyName, Assembly> assemblyResolver,
+ Func<Assembly, string, bool, Type> typeResolver,
+ bool throwOnError,
+ bool ignoreCase)
+ {
+ StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
+ return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // This will return a class based upon the progID. This is provided for
+ // COM classic support. Program ID's are not used in COM+ because they
+ // have been superceded by namespace. (This routine is called this instead
+ // of getClass() because of the name conflict with the first method above.)
+ //
+ // param progID: the progID of the class to retrieve
+ // returns: the class object associated to the progID
+ ////
+ public static Type GetTypeFromProgID(String progID, String server, bool throwOnError)
+ {
+ return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////
+ // This will return a class based upon the CLSID. This is provided for
+ // COM classic support.
+ //
+ // param CLSID: the CLSID of the class to retrieve
+ // returns: the class object associated to the CLSID
+ ////
+ public static Type GetTypeFromCLSID(Guid clsid, String server, bool throwOnError)
+ {
+ return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
+ }
+
+ internal virtual RuntimeTypeHandle GetTypeHandleInternal()
+ {
+ return TypeHandle;
+ }
+
+ // Given a class handle, this will return the class for that handle.
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle);
+
+ [Pure]
+ [MethodImpl(MethodImplOptions.InternalCall)]
+ public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle);
+
+
+
+
+#if FEATURE_COMINTEROP
+ internal bool IsWindowsRuntimeObject
+ {
+ [Pure]
+ get { return IsWindowsRuntimeObjectImpl(); }
+ }
+
+ internal bool IsExportedToWindowsRuntime
+ {
+ [Pure]
+ get { return IsExportedToWindowsRuntimeImpl(); }
+ }
+
+
+ // Protected routine to determine if this class represents a Windows Runtime object
+ virtual internal bool IsWindowsRuntimeObjectImpl()
+ {
+ throw new NotImplementedException();
+ }
+
+ // Determines if this type is exported to WinRT (i.e. is an activatable class in a managed .winmd)
+ virtual internal bool IsExportedToWindowsRuntimeImpl()
+ {
+ throw new NotImplementedException();
+ }
+#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()
+ {
+ return FormatTypeName(false);
+ }
+
+ internal virtual string FormatTypeName(bool serialization)
+ {
+ throw new NotImplementedException();
+ }
+
+ [Pure]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern bool operator ==(Type left, Type right);
+
+ [Pure]
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public static extern bool operator !=(Type left, Type right);
+
+ // Exists to faciliate code sharing between CoreCLR and CoreRT.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal bool IsRuntimeImplemented() => this is RuntimeType;
+ }
+}
diff --git a/src/mscorlib/src/System/Type.cs b/src/mscorlib/src/System/Type.cs
deleted file mode 100644
index 3647451445..0000000000
--- a/src/mscorlib/src/System/Type.cs
+++ /dev/null
@@ -1,1764 +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.
-
-//
-//
-//
-// Implements System.Type
-//
-// ======================================================================================
-
-namespace System
-{
- using System;
- using System.Reflection;
- using System.Threading;
- using System.Runtime;
- using System.Runtime.Remoting;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Security;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
- using CultureInfo = System.Globalization.CultureInfo;
- using StackCrawlMark = System.Threading.StackCrawlMark;
- using DebuggerStepThroughAttribute = System.Diagnostics.DebuggerStepThroughAttribute;
-
- [Serializable]
- public abstract class Type : MemberInfo, IReflect
- {
- //
- // System.Type is appdomain agile type. Appdomain agile types cannot have precise static constructors. Make
- // sure to never introduce one here!
- //
- public static readonly MemberFilter FilterAttribute = new MemberFilter(__Filters.Instance.FilterAttribute);
- public static readonly MemberFilter FilterName = new MemberFilter(__Filters.Instance.FilterName);
- public static readonly MemberFilter FilterNameIgnoreCase = new MemberFilter(__Filters.Instance.FilterIgnoreCase);
-
- public static readonly Object Missing = System.Reflection.Missing.Value;
-
- public static readonly char Delimiter = '.';
-
- // EmptyTypes is used to indicate that we are looking for someting without any parameters.
- public readonly static Type[] EmptyTypes = EmptyArray<Type>.Value;
-
- // The Default binder. We create a single one and expose that.
- private static Binder defaultBinder;
-
-
- protected Type() {}
-
-
- // MemberInfo Methods....
- // The Member type Field.
- public override MemberTypes MemberType {
- get {return System.Reflection.MemberTypes.TypeInfo;}
- }
-
- // Return the class that declared this type.
- public override Type DeclaringType {
- get {return null;}
- }
-
- public virtual MethodBase DeclaringMethod { get { return null; } }
-
- // Return the class that was used to obtain this type.
- public override Type ReflectedType
- {
- get {return null;}
- }
-
- ////////////////////////////////////////////////////////////////////////////////
- // This is a static method that returns a Class based upon the name of the class
- // (this name needs to be fully qualified with the package name and is
- // case-sensitive by default).
- ////
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type GetType(String typeName, bool throwOnError, bool ignoreCase) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeType.GetType(typeName, throwOnError, ignoreCase, false, ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type GetType(String typeName, bool throwOnError) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeType.GetType(typeName, throwOnError, false, false, ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type GetType(String typeName) {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return RuntimeType.GetType(typeName, false, false, false, ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type GetType(
- string typeName,
- Func<AssemblyName, Assembly> assemblyResolver,
- Func<Assembly, string, bool, Type> typeResolver)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, false, false, ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type GetType(
- string typeName,
- Func<AssemblyName, Assembly> assemblyResolver,
- Func<Assembly, string, bool, Type> typeResolver,
- bool throwOnError)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError, false, ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type GetType(
- string typeName,
- Func<AssemblyName, Assembly> assemblyResolver,
- Func<Assembly, string, bool, Type> typeResolver,
- bool throwOnError,
- bool ignoreCase)
- {
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark);
- }
-
- [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable
- public static Type ReflectionOnlyGetType(String typeName, bool throwIfNotFound, bool ignoreCase)
- {
- if (typeName == null)
- throw new ArgumentNullException(nameof(typeName));
- if (typeName.Length == 0 && throwIfNotFound)
- throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr"));
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_ReflectionOnlyGetType"));
- }
-
- public virtual Type MakePointerType() { throw new NotSupportedException(); }
- public virtual StructLayoutAttribute StructLayoutAttribute { get { throw new NotSupportedException(); } }
- public virtual Type MakeByRefType() { throw new NotSupportedException(); }
- public virtual Type MakeArrayType() { throw new NotSupportedException(); }
- public virtual Type MakeArrayType(int rank) { throw new NotSupportedException(); }
-
- ////////////////////////////////////////////////////////////////////////////////
- // This will return a class based upon the progID. This is provided for
- // COM classic support. Program ID's are not used in COM+ because they
- // have been superceded by namespace. (This routine is called this instead
- // of getClass() because of the name conflict with the first method above.)
- //
- // param progID: the progID of the class to retrieve
- // returns: the class object associated to the progID
- ////
- public static Type GetTypeFromProgID(String progID)
- {
- return RuntimeType.GetTypeFromProgIDImpl(progID, null, false);
- }
-
- ////////////////////////////////////////////////////////////////////////////////
- // This will return a class based upon the progID. This is provided for
- // COM classic support. Program ID's are not used in COM+ because they
- // have been superceded by namespace. (This routine is called this instead
- // of getClass() because of the name conflict with the first method above.)
- //
- // param progID: the progID of the class to retrieve
- // returns: the class object associated to the progID
- ////
- public static Type GetTypeFromProgID(String progID, bool throwOnError)
- {
- return RuntimeType.GetTypeFromProgIDImpl(progID, null, throwOnError);
- }
-
- public static Type GetTypeFromProgID(String progID, String server)
- {
- return RuntimeType.GetTypeFromProgIDImpl(progID, server, false);
- }
-
- public static Type GetTypeFromProgID(String progID, String server, bool throwOnError)
- {
- return RuntimeType.GetTypeFromProgIDImpl(progID, server, throwOnError);
- }
-
- ////////////////////////////////////////////////////////////////////////////////
- // This will return a class based upon the CLSID. This is provided for
- // COM classic support.
- //
- // param CLSID: the CLSID of the class to retrieve
- // returns: the class object associated to the CLSID
- ////
- public static Type GetTypeFromCLSID(Guid clsid)
- {
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, false);
- }
-
- public static Type GetTypeFromCLSID(Guid clsid, bool throwOnError)
- {
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, null, throwOnError);
- }
-
- public static Type GetTypeFromCLSID(Guid clsid, String server)
- {
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, false);
- }
-
- public static Type GetTypeFromCLSID(Guid clsid, String server, bool throwOnError)
- {
- return RuntimeType.GetTypeFromCLSIDImpl(clsid, server, throwOnError);
- }
-
- // GetTypeCode
- // This method will return a TypeCode for the passed
- // type.
- public static TypeCode GetTypeCode(Type type)
- {
- if (type == null)
- return TypeCode.Empty;
- return type.GetTypeCodeImpl();
- }
-
- protected virtual TypeCode GetTypeCodeImpl()
- {
- // System.RuntimeType overrides GetTypeCodeInternal
- // so we can assume that this is not a runtime type
-
- // this is true for EnumBuilder but not the other System.Type subclasses in BCL
- if (this != UnderlyingSystemType && UnderlyingSystemType != null)
- return Type.GetTypeCode(UnderlyingSystemType);
-
- return TypeCode.Object;
- }
-
- // Property representing the GUID associated with a class.
- public abstract Guid GUID {
- get;
- }
-
- // Return the Default binder used by the system.
- static public Binder DefaultBinder {
- get {
- // Allocate the default binder if it hasn't been allocated yet.
- if (defaultBinder == null)
- CreateBinder();
- return defaultBinder;
- }
- }
-
- static private void CreateBinder()
- {
- if (defaultBinder == null)
- {
- DefaultBinder binder = new DefaultBinder();
- Interlocked.CompareExchange<Binder>(ref defaultBinder, binder, null);
- }
- }
-
- // Description of the Binding Process.
- // We must invoke a method that is accessable 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
- // 2. The type of each argument can be converted by the binder to the
- // type of the type of the parameter.
- //
- // The binder will find all of the matching methods. These method are found based
- // upon the type of binding requested (MethodInvoke, Get/Set Properties). The set
- // 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
- // at that point. The search may be control which set of methods are searched based
- // upon the accessibility attribute associated with the method.
- //
- // The BindToMethod method is responsible for selecting the method to be invoked.
- // For the default binder, the most specific method will be selected.
- //
- // This will invoke a specific member...
-
- abstract public Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target,
- Object[] args, ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters);
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args, CultureInfo culture)
- {
- return InvokeMember(name,invokeAttr,binder,target,args,null,culture,null);
- }
-
- [DebuggerStepThroughAttribute]
- [Diagnostics.DebuggerHidden]
- public Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder, Object target, Object[] args)
- {
- return InvokeMember(name,invokeAttr,binder,target,args,null,null,null);
- }
-
-
- // Module Property associated with a class.
- public new abstract Module Module { get; }
-
- // Assembly Property associated with a class.
- public abstract Assembly Assembly {
- [Pure]
- get;
- }
-
- // Assembly Property associated with a class.
- // A class handle is a unique integer value associated with
- // each class. The handle is unique during the process life time.
- public virtual RuntimeTypeHandle TypeHandle
- {
- [Pure]
- get
- {
- throw new NotSupportedException();
- }
- }
-
- internal virtual RuntimeTypeHandle GetTypeHandleInternal() {
- return TypeHandle;
- }
-
- public static RuntimeTypeHandle GetTypeHandle(Object o)
- {
- if (o == null)
- throw new ArgumentNullException(null, Environment.GetResourceString("Arg_InvalidHandle"));
- return new RuntimeTypeHandle((RuntimeType)o.GetType());
- }
-
- // Given a class handle, this will return the class for that handle.
- [MethodImpl(MethodImplOptions.InternalCall)]
- internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle);
-
- [Pure]
- [MethodImpl(MethodImplOptions.InternalCall)]
- public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle);
-
-
- // Return the fully qualified name. The name does contain the namespace.
- public abstract String FullName {
- [Pure]
- get;
- }
-
- // Return the name space of the class.
- public abstract String Namespace {
- [Pure]
- get;
- }
-
-
- public abstract String AssemblyQualifiedName {
- [Pure]
- get;
- }
-
-
- [Pure]
- public virtual int GetArrayRank() {
- Contract.Ensures(Contract.Result<int>() >= 0);
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
- }
-
- // Returns the base class for a class. If this is an interface or has
- // no base class null is returned. Object is the only Type that does not
- // have a base class.
- public abstract Type BaseType {
- [Pure]
- get;
- }
-
-
- // GetConstructor
- // This method will search for the specified constructor. For constructors,
- // unlike everything else, the default is to not look for static methods. The
- // reason is that we don't typically expose the class initializer.
- public ConstructorInfo GetConstructor(BindingFlags bindingAttr,
- Binder binder,
- CallingConventions callConvention,
- Type[] types,
- ParameterModifier[] modifiers)
- {
- // Must provide some types (Type[0] for nothing)
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- for (int i=0;i<types.Length;i++)
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
- }
-
- public ConstructorInfo GetConstructor(BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
- {
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- for (int i=0;i<types.Length;i++)
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- return GetConstructorImpl(bindingAttr, binder, CallingConventions.Any, types, modifiers);
- }
-
- public ConstructorInfo GetConstructor(Type[] types)
- {
- // The arguments are checked in the called version of GetConstructor.
- return GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, types, null);
- }
-
- abstract protected ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,
- Binder binder,
- CallingConventions callConvention,
- Type[] types,
- ParameterModifier[] modifiers);
-
- // GetConstructors()
- // This routine will return an array of all constructors supported by the class.
- // Unlike everything else, the default is to not look for static methods. The
- // reason is that we don't typically expose the class initializer.
- public ConstructorInfo[] GetConstructors() {
- return GetConstructors(BindingFlags.Public | BindingFlags.Instance);
- }
-
- abstract public ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
-
- public ConstructorInfo TypeInitializer {
- get {
- return GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic,
- null,
- CallingConventions.Any,
- Type.EmptyTypes,
- null);
- }
- }
-
-
- // Return a method based upon the passed criteria. The name of the method
- // must be provided, and exception is thrown if it is not. The bindingAttr
- // parameter indicates if non-public methods should be searched. The types
- // array indicates the types of the parameters being looked for.
- public MethodInfo GetMethod(String name,
- BindingFlags bindingAttr,
- Binder binder,
- CallingConventions callConvention,
- Type[] types,
- ParameterModifier[] modifiers)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- for (int i = 0; i < types.Length; i++)
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
- }
-
- public MethodInfo GetMethod(String name,
- BindingFlags bindingAttr,
- Binder binder,
- Type[] types,
- ParameterModifier[] modifiers)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- for (int i = 0; i < types.Length; i++)
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- return GetMethodImpl(name, bindingAttr, binder, CallingConventions.Any, types, modifiers);
- }
-
- public MethodInfo GetMethod(String name, Type[] types, ParameterModifier[] modifiers)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- for (int i=0;i<types.Length;i++)
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- return GetMethodImpl(name, Type.DefaultLookup, null, CallingConventions.Any, types, modifiers);
- }
-
- public MethodInfo GetMethod(String name,Type[] types)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- for (int i=0;i<types.Length;i++)
- if (types[i] == null)
- throw new ArgumentNullException(nameof(types));
- return GetMethodImpl(name, Type.DefaultLookup, null, CallingConventions.Any, types, null);
- }
-
- public MethodInfo GetMethod(String name, BindingFlags bindingAttr)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
- return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null);
- }
-
- public MethodInfo GetMethod(String name)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
- return GetMethodImpl(name, Type.DefaultLookup, null, CallingConventions.Any, null, null);
- }
-
- abstract protected MethodInfo GetMethodImpl(String name,
- BindingFlags bindingAttr,
- Binder binder,
- CallingConventions callConvention,
- Type[] types,
- ParameterModifier[] modifiers);
-
-
- // GetMethods
- // This routine will return all the methods implemented by the class
- public MethodInfo[] GetMethods() {
- return GetMethods(Type.DefaultLookup);
- }
-
- abstract public MethodInfo[] GetMethods(BindingFlags bindingAttr);
-
- // GetField
- // Get Field will return a specific field based upon name
- abstract public FieldInfo GetField(String name, BindingFlags bindingAttr);
-
-
- public FieldInfo GetField(String name) {
- return GetField(name, Type.DefaultLookup);
- }
-
-
- // GetFields
- // Get fields will return a full array of fields implemented by a class
- public FieldInfo[] GetFields() {
- return GetFields(Type.DefaultLookup);
- }
- abstract public FieldInfo[] GetFields(BindingFlags bindingAttr);
-
- // GetInterface
- // This method will return an interface (as a class) based upon
- // the passed in name.
- public Type GetInterface(String name) {
- return GetInterface(name,false);
- }
- abstract public Type GetInterface(String name, bool ignoreCase);
-
-
- // GetInterfaces
- // This method will return all of the interfaces implemented by a class
- abstract public Type[] GetInterfaces();
-
- // FindInterfaces
- // This method will filter the interfaces supported the class
- public virtual Type[] FindInterfaces(TypeFilter filter,Object filterCriteria)
- {
- if (filter == null)
- throw new ArgumentNullException(nameof(filter));
- Contract.EndContractBlock();
- Type[] c = GetInterfaces();
- int cnt = 0;
- for (int i = 0;i<c.Length;i++) {
- if (!filter(c[i],filterCriteria))
- c[i] = null;
- else
- cnt++;
- }
- if (cnt == c.Length)
- return c;
-
- Type[] ret = new Type[cnt];
- cnt=0;
- for (int i=0;i<c.Length;i++) {
- if (c[i] != null)
- ret[cnt++] = c[i];
- }
- return ret;
- }
-
- // GetEvent
- // This method will return a event by name if it is found.
- // null is returned if the event is not found
-
-
- public EventInfo GetEvent(String name) {
- return GetEvent(name,Type.DefaultLookup);
- }
- abstract public EventInfo GetEvent(String name,BindingFlags bindingAttr);
-
- // GetEvents
- // This method will return an array of EventInfo. If there are not Events
- // an empty array will be returned.
- virtual public EventInfo[] GetEvents() {
- return GetEvents(Type.DefaultLookup);
- }
- abstract public EventInfo[] GetEvents(BindingFlags bindingAttr);
-
-
- // Return a property based upon the passed criteria. The nameof the
- // parameter must be provided.
- public PropertyInfo GetProperty(String name,BindingFlags bindingAttr,Binder binder,
- Type returnType, Type[] types, ParameterModifier[] modifiers)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,bindingAttr,binder,returnType,types,modifiers);
- }
-
- public PropertyInfo GetProperty(String name, Type returnType, Type[] types,ParameterModifier[] modifiers)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,modifiers);
- }
-
- public PropertyInfo GetProperty(String name, BindingFlags bindingAttr)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,bindingAttr,null,null,null,null);
- }
-
- public PropertyInfo GetProperty(String name, Type returnType, Type[] types)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,types,null);
- }
-
- public PropertyInfo GetProperty(String name, Type[] types)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (types == null)
- throw new ArgumentNullException(nameof(types));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,null,types,null);
- }
-
- public PropertyInfo GetProperty(String name, Type returnType)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- if (returnType == null)
- throw new ArgumentNullException(nameof(returnType));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,returnType,null,null);
- }
-
- public PropertyInfo GetProperty(String name)
- {
- if (name == null)
- throw new ArgumentNullException(nameof(name));
- Contract.EndContractBlock();
- return GetPropertyImpl(name,Type.DefaultLookup,null,null,null,null);
- }
-
- protected abstract PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr,Binder binder,
- Type returnType, Type[] types, ParameterModifier[] modifiers);
-
-
- // GetProperties
- // This method will return an array of all of the properties defined
- // for a Type.
- abstract public PropertyInfo[] GetProperties(BindingFlags bindingAttr);
- public PropertyInfo[] GetProperties()
- {
- return GetProperties(Type.DefaultLookup);
- }
-
- // GetNestedTypes()
- // This set of method will return any nested types that are found inside
- // of the type.
- public Type[] GetNestedTypes()
- {
- return GetNestedTypes(Type.DefaultLookup);
- }
-
- abstract public Type[] GetNestedTypes(BindingFlags bindingAttr);
-
- public Type GetNestedType(String name)
- {
- return GetNestedType(name,Type.DefaultLookup);
- }
-
- abstract public Type GetNestedType(String name, BindingFlags bindingAttr);
-
- // GetMember
- // This method will return all of the members which match the specified string
- // passed into the method
- public MemberInfo[] GetMember(String name) {
- return GetMember(name,Type.DefaultLookup);
- }
-
- virtual public MemberInfo[] GetMember(String name, BindingFlags bindingAttr)
- {
- return GetMember(name,MemberTypes.All,bindingAttr);
- }
-
- virtual public MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
- }
-
-
- // GetMembers
- // This will return a Member array of all of the members of a class
- public MemberInfo[] GetMembers() {
- return GetMembers(Type.DefaultLookup);
- }
- abstract public MemberInfo[] GetMembers(BindingFlags bindingAttr);
-
- // GetDefaultMembers
- // This will return a MemberInfo that has been marked with the
- // DefaultMemberAttribute
- public virtual MemberInfo[] GetDefaultMembers()
- {
- throw new NotImplementedException();
- }
-
- // FindMembers
- // This will return a filtered version of the member information
- public virtual MemberInfo[] FindMembers(MemberTypes memberType,BindingFlags bindingAttr,MemberFilter filter,Object filterCriteria)
- {
- // Define the work arrays
- MethodInfo[] m = null;
- ConstructorInfo[] c = null;
- FieldInfo[] f = null;
- PropertyInfo[] p = null;
- EventInfo[] e = null;
- Type[] t = null;
-
- int i = 0;
- int cnt = 0; // Total Matchs
-
- // Check the methods
- if ((memberType & System.Reflection.MemberTypes.Method) != 0) {
- m = GetMethods(bindingAttr);
- if (filter != null) {
- for (i=0;i<m.Length;i++)
- if (!filter(m[i],filterCriteria))
- m[i] = null;
- else
- cnt++;
- } else {
- cnt+=m.Length;
- }
- }
-
- // Check the constructors
- if ((memberType & System.Reflection.MemberTypes.Constructor) != 0) {
- c = GetConstructors(bindingAttr);
- if (filter != null) {
- for (i=0;i<c.Length;i++)
- if (!filter(c[i],filterCriteria))
- c[i] = null;
- else
- cnt++;
- } else {
- cnt+=c.Length;
- }
- }
-
- // Check the fields
- if ((memberType & System.Reflection.MemberTypes.Field) != 0) {
- f = GetFields(bindingAttr);
- if (filter != null) {
- for (i=0;i<f.Length;i++)
- if (!filter(f[i],filterCriteria))
- f[i] = null;
- else
- cnt++;
- } else {
- cnt+=f.Length;
- }
- }
-
- // Check the Properties
- if ((memberType & System.Reflection.MemberTypes.Property) != 0) {
- p = GetProperties(bindingAttr);
- if (filter != null) {
- for (i=0;i<p.Length;i++)
- if (!filter(p[i],filterCriteria))
- p[i] = null;
- else
- cnt++;
- } else {
- cnt+=p.Length;
- }
- }
-
- // Check the Events
- if ((memberType & System.Reflection.MemberTypes.Event) != 0) {
- e = GetEvents(bindingAttr);
- if (filter != null) {
- for (i=0;i<e.Length;i++)
- if (!filter(e[i],filterCriteria))
- e[i] = null;
- else
- cnt++;
- } else {
- cnt+=e.Length;
- }
- }
-
- // Check the Types
- if ((memberType & System.Reflection.MemberTypes.NestedType) != 0) {
- t = GetNestedTypes(bindingAttr);
- if (filter != null) {
- for (i=0;i<t.Length;i++)
- if (!filter(t[i],filterCriteria))
- t[i] = null;
- else
- cnt++;
- } else {
- cnt+=t.Length;
- }
- }
-
- // Allocate the Member Info
- MemberInfo[] ret = new MemberInfo[cnt];
-
- // Copy the Methods
- cnt = 0;
- if (m != null) {
- for (i=0;i<m.Length;i++)
- if (m[i] != null)
- ret[cnt++] = m[i];
- }
-
- // Copy the Constructors
- if (c != null) {
- for (i=0;i<c.Length;i++)
- if (c[i] != null)
- ret[cnt++] = c[i];
- }
-
- // Copy the Fields
- if (f != null) {
- for (i=0;i<f.Length;i++)
- if (f[i] != null)
- ret[cnt++] = f[i];
- }
-
- // Copy the Properties
- if (p != null) {
- for (i=0;i<p.Length;i++)
- if (p[i] != null)
- ret[cnt++] = p[i];
- }
-
- // Copy the Events
- if (e != null) {
- for (i=0;i<e.Length;i++)
- if (e[i] != null)
- ret[cnt++] = e[i];
- }
-
- // Copy the Types
- if (t != null) {
- for (i=0;i<t.Length;i++)
- if (t[i] != null)
- ret[cnt++] = t[i];
- }
-
- return ret;
- }
-
- ////////////////////////////////////////////////////////////////////////////////
- //
- // Attributes
- //
- // The attributes are all treated as read-only properties on a class. Most of
- // these boolean properties have flag values defined in this class and act like
- // a bit mask of attributes. There are also a set of boolean properties that
- // relate to the classes relationship to other classes and to the state of the
- // class inside the runtime.
- //
- ////////////////////////////////////////////////////////////////////////////////
-
- public bool IsNested
- {
- [Pure]
- get
- {
- return DeclaringType != null;
- }
- }
-
- // The attribute property on the Type.
- public TypeAttributes Attributes {
- [Pure]
- get {return GetAttributeFlagsImpl();}
- }
-
- public virtual GenericParameterAttributes GenericParameterAttributes
- {
- get { throw new NotSupportedException(); }
- }
-
- public bool IsVisible
- {
- [Pure]
- get
- {
- RuntimeType rt = this as RuntimeType;
- if (rt != null)
- return RuntimeTypeHandle.IsVisible(rt);
-
- if (IsGenericParameter)
- return true;
-
- if (HasElementType)
- return GetElementType().IsVisible;
-
- Type type = this;
- while (type.IsNested)
- {
- if (!type.IsNestedPublic)
- return false;
-
- // this should be null for non-nested types.
- type = type.DeclaringType;
- }
-
- // Now "type" should be a top level type
- if (!type.IsPublic)
- return false;
-
- if (IsGenericType && !IsGenericTypeDefinition)
- {
- foreach (Type t in GetGenericArguments())
- {
- if (!t.IsVisible)
- return false;
- }
- }
-
- return true;
- }
- }
-
- public bool IsNotPublic
- {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic);}
- }
-
- public bool IsPublic {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public);}
- }
-
- public bool IsNestedPublic {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic);}
- }
-
- public bool IsNestedPrivate {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate);}
- }
- public bool IsNestedFamily {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily);}
- }
- public bool IsNestedAssembly {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly);}
- }
- public bool IsNestedFamANDAssem {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem);}
- }
- public bool IsNestedFamORAssem{
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem);}
- }
-
- public bool IsAutoLayout {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout);}
- }
- public bool IsLayoutSequential {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout);}
- }
- public bool IsExplicitLayout {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout);}
- }
-
- public bool IsClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsValueType);}
- }
-
- public bool IsInterface {
- [Pure]
- get
- {
- RuntimeType rt = this as RuntimeType;
- if (rt != null)
- return RuntimeTypeHandle.IsInterface(rt);
-
- return ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Interface);
- }
- }
-
- public bool IsValueType {
- [Pure]
- get {return IsValueTypeImpl();}
- }
-
- public bool IsAbstract {
- [Pure]
- get { return ((GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0); }
- }
-
- public bool IsSealed {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0);}
- }
-
- public virtual bool IsEnum {
- [Pure]
- get
- {
- // This will return false for a non-runtime Type object unless it overrides IsSubclassOf.
- return IsSubclassOf(RuntimeType.EnumType);
- }
- }
-
- public bool IsSpecialName {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0);}
- }
-
- public bool IsImport {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.Import) != 0);}
- }
-
- public virtual bool IsSerializable
- {
- [Pure]
- get
- {
- if ((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0)
- return true;
-
- RuntimeType rt = this.UnderlyingSystemType as RuntimeType;
-
- if (rt != null)
- return rt.IsSpecialSerializableType();
-
- return false;
- }
- }
-
- public bool IsAnsiClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass);}
- }
-
- public bool IsUnicodeClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass);}
- }
-
- public bool IsAutoClass {
- [Pure]
- get {return ((GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass);}
- }
-
- // These are not backed up by attributes. Instead they are implemented
- // based internally.
- public bool IsArray {
- [Pure]
- get {return IsArrayImpl();}
- }
-
- internal virtual bool IsSzArray {
- [Pure]
- get {return false;}
- }
-
- public virtual bool IsGenericType {
- [Pure]
- get { return false; }
- }
-
- public virtual bool IsGenericTypeDefinition {
- [Pure]
- get { return false; }
- }
-
- public virtual bool IsConstructedGenericType
- {
- [Pure]
- get { throw new NotImplementedException(); }
- }
-
- public virtual bool IsGenericParameter
- {
- [Pure]
- get { return false; }
- }
-
- public virtual int GenericParameterPosition {
- [Pure]
- get {throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter")); }
- }
-
- public virtual bool ContainsGenericParameters
- {
- [Pure]
- get
- {
- if (HasElementType)
- return GetRootElementType().ContainsGenericParameters;
-
- if (IsGenericParameter)
- return true;
-
- if (!IsGenericType)
- return false;
-
- Type[] genericArguments = GetGenericArguments();
- for (int i = 0; i < genericArguments.Length; i++)
- {
- if (genericArguments[i].ContainsGenericParameters)
- return true;
- }
-
- return false;
- }
- }
-
- [Pure]
- public virtual Type[] GetGenericParameterConstraints()
- {
- if (!IsGenericParameter)
- throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericParameter"));
- Contract.EndContractBlock();
-
- throw new InvalidOperationException();
- }
-
- public bool IsByRef {
- [Pure]
- get {return IsByRefImpl();}
- }
- public bool IsPointer {
- [Pure]
- get {return IsPointerImpl();}
- }
- public bool IsPrimitive {
- [Pure]
- get {return IsPrimitiveImpl();}
- }
- public bool IsCOMObject {
- [Pure]
- get {return IsCOMObjectImpl();}
- }
-
-#if FEATURE_COMINTEROP
- internal bool IsWindowsRuntimeObject {
- [Pure]
- get { return IsWindowsRuntimeObjectImpl(); }
- }
-
- internal bool IsExportedToWindowsRuntime {
- [Pure]
- get { return IsExportedToWindowsRuntimeImpl(); }
- }
-#endif // FEATURE_COMINTEROP
-
- public bool HasElementType {
- [Pure]
- get {return HasElementTypeImpl();}
- }
-
- public bool IsContextful {
- [Pure]
- get {return IsContextfulImpl();}
- }
-
- public bool IsMarshalByRef {
- [Pure]
- get {return IsMarshalByRefImpl();}
- }
-
- // Protected routine to determine if this class represents a value class
- // The default implementation of IsValueTypeImpl never returns true for non-runtime types.
- protected virtual bool IsValueTypeImpl()
- {
- // Note that typeof(Enum) and typeof(ValueType) are not themselves value types.
- // But there is no point excluding them here because customer derived System.Type
- // (non-runtime type) objects can never be equal to a runtime type, which typeof(XXX) is.
- // Ideally we should throw a NotImplementedException here or just return false because
- // customer implementations of IsSubclassOf should never return true between a non-runtime
- // type and a runtime type. There is no benefits in making that breaking change though.
-
- return IsSubclassOf(RuntimeType.ValueType);
- }
-
- // Protected routine to get the attributes.
- abstract protected TypeAttributes GetAttributeFlagsImpl();
-
- // Protected routine to determine if this class represents an Array
- abstract protected bool IsArrayImpl();
-
- // Protected routine to determine if this class is a ByRef
- abstract protected bool IsByRefImpl();
-
- // Protected routine to determine if this class is a Pointer
- abstract protected bool IsPointerImpl();
-
- // Protected routine to determine if this class represents a primitive type
- abstract protected bool IsPrimitiveImpl();
-
- // Protected routine to determine if this class represents a COM object
- abstract protected bool IsCOMObjectImpl();
-
-#if FEATURE_COMINTEROP
- // Protected routine to determine if this class represents a Windows Runtime object
- virtual internal bool IsWindowsRuntimeObjectImpl() {
- throw new NotImplementedException();
- }
-
- // Determines if this type is exported to WinRT (i.e. is an activatable class in a managed .winmd)
- virtual internal bool IsExportedToWindowsRuntimeImpl() {
- throw new NotImplementedException();
- }
-#endif // FEATURE_COMINTEROP
-
- public virtual Type MakeGenericType(params Type[] typeArguments) {
- Contract.Ensures(Contract.Result<Type>() != null);
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
- }
-
-
- // Protected routine to determine if this class is contextful
- protected virtual bool IsContextfulImpl()
- {
- return false;
- }
-
- // Protected routine to determine if this class is marshaled by ref
- protected virtual bool IsMarshalByRefImpl()
- {
- return false;
- }
-
- [Pure]
- abstract public Type GetElementType();
-
- [Pure]
- public virtual Type[] GetGenericArguments()
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
- }
-
- public virtual Type[] GenericTypeArguments{
- get{
- if(IsGenericType && !IsGenericTypeDefinition){
- return GetGenericArguments();
- }
- else{
- return Type.EmptyTypes;
- }
-
- }
- }
-
- [Pure]
- public virtual Type GetGenericTypeDefinition()
- {
- Contract.Ensures(Contract.Result<Type>() != null);
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
- }
-
- [Pure]
- abstract protected bool HasElementTypeImpl();
-
- internal Type GetRootElementType()
- {
- Type rootElementType = this;
-
- while (rootElementType.HasElementType)
- rootElementType = rootElementType.GetElementType();
-
- return rootElementType;
- }
-
-#region Enum methods
-
- // Default implementations of GetEnumNames, GetEnumValues, and GetEnumUnderlyingType
- // Subclass of types can override these methods.
-
- public virtual string[] GetEnumNames()
- {
- if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
- Contract.Ensures(Contract.Result<String[]>() != null);
-
- string[] names;
- Array values;
- GetEnumData(out names, out values);
- return names;
- }
-
- // We don't support GetEnumValues in the default implementation because we cannot create an array of
- // a non-runtime type. If there is strong need we can consider returning an object or int64 array.
- public virtual Array GetEnumValues()
- {
- if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
- Contract.Ensures(Contract.Result<Array>() != null);
-
- throw new NotImplementedException();
- }
-
- // Returns the enum values as an object array.
- private Array GetEnumRawConstantValues()
- {
- string[] names;
- Array values;
- GetEnumData(out names, out values);
- return values;
- }
-
- // This will return enumValues and enumNames sorted by the values.
- private void GetEnumData(out string[] enumNames, out Array enumValues)
- {
- Contract.Ensures(Contract.ValueAtReturn<String[]>(out enumNames) != null);
- Contract.Ensures(Contract.ValueAtReturn<Array>(out enumValues) != null);
-
- FieldInfo[] flds = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
-
- object[] values = new object[flds.Length];
- string[] names = new string[flds.Length];
-
- for (int i = 0; i < flds.Length; i++)
- {
- names[i] = flds[i].Name;
- values[i] = flds[i].GetRawConstantValue();
- }
-
- // Insertion Sort these values in ascending order.
- // We use this O(n^2) algorithm, but it turns out that most of the time the elements are already in sorted order and
- // the common case performance will be faster than quick sorting this.
- IComparer comparer = Comparer.Default;
- for (int i = 1; i < values.Length; i++)
- {
- int j = i;
- string tempStr = names[i];
- object val = values[i];
- bool exchanged = false;
-
- // Since the elements are sorted we only need to do one comparision, we keep the check for j inside the loop.
- while (comparer.Compare(values[j - 1], val) > 0)
- {
- names[j] = names[j - 1];
- values[j] = values[j - 1];
- j--;
- exchanged = true;
- if (j == 0)
- break;
- }
-
- if (exchanged)
- {
- names[j] = tempStr;
- values[j] = val;
- }
- }
-
- enumNames = names;
- enumValues = values;
- }
-
- public virtual Type GetEnumUnderlyingType()
- {
- if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
- Contract.Ensures(Contract.Result<Type>() != null);
-
- FieldInfo[] fields = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
- if (fields == null || fields.Length != 1)
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnum"), "enumType");
-
- return fields[0].FieldType;
- }
-
- public virtual bool IsEnumDefined(object value)
- {
- if (value == null)
- throw new ArgumentNullException(nameof(value));
-
- if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
- Contract.EndContractBlock();
-
- // Check if both of them are of the same type
- Type valueType = value.GetType();
-
- // If the value is an Enum then we need to extract the underlying value from it
- if (valueType.IsEnum)
- {
- if (!valueType.IsEquivalentTo(this))
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumAndObjectMustBeSameType", valueType.ToString(), this.ToString()));
-
- valueType = valueType.GetEnumUnderlyingType();
- }
-
- // If a string is passed in
- if (valueType == typeof(string))
- {
- string[] names = GetEnumNames();
- if (Array.IndexOf(names, value) >= 0)
- return true;
- else
- return false;
- }
-
- // If an enum or integer value is passed in
- if (Type.IsIntegerType(valueType))
- {
- Type underlyingType = GetEnumUnderlyingType();
- // We cannot compare the types directly because valueType is always a runtime type but underlyingType might not be.
- if (underlyingType.GetTypeCodeImpl() != valueType.GetTypeCodeImpl())
- throw new ArgumentException(Environment.GetResourceString("Arg_EnumUnderlyingTypeAndObjectMustBeSameType", valueType.ToString(), underlyingType.ToString()));
-
- Array values = GetEnumRawConstantValues();
- return (BinarySearch(values, value) >= 0);
- }
- else
- {
- throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_UnknownEnumType"));
- }
- }
-
- public virtual string GetEnumName(object value)
- {
- if (value == null)
- throw new ArgumentNullException(nameof(value));
-
- if (!IsEnum)
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnum"), "enumType");
- Contract.EndContractBlock();
-
- Type valueType = value.GetType();
-
- if (!(valueType.IsEnum || Type.IsIntegerType(valueType)))
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"), nameof(value));
-
- Array values = GetEnumRawConstantValues();
- int index = BinarySearch(values, value);
-
- if (index >= 0)
- {
- string[] names = GetEnumNames();
- return names[index];
- }
-
- return null;
- }
-
- // Convert everything to ulong then perform a binary search.
- private static int BinarySearch(Array array, object value)
- {
- ulong[] ulArray = new ulong[array.Length];
- for (int i = 0; i < array.Length; ++i)
- ulArray[i] = Enum.ToUInt64(array.GetValue(i));
-
- ulong ulValue = Enum.ToUInt64(value);
-
- return Array.BinarySearch(ulArray, ulValue);
- }
-
- internal static bool IsIntegerType(Type t)
- {
- return (t == typeof(int) ||
- t == typeof(short) ||
- t == typeof(ushort) ||
- t == typeof(byte) ||
- t == typeof(sbyte) ||
- t == typeof(uint) ||
- t == typeof(long) ||
- t == typeof(ulong) ||
- t == typeof(char) ||
- t == typeof(bool));
- }
-#endregion
-
- public virtual bool IsSecurityCritical { [Pure] get { throw new NotImplementedException(); } }
-
- public virtual bool IsSecuritySafeCritical { [Pure] get { throw new NotImplementedException(); } }
-
- public virtual bool IsSecurityTransparent { [Pure] get { throw new NotImplementedException(); } }
-
- 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;
- }
- }
-
- // The behavior of UnderlyingSystemType varies from type to type.
- // For IReflect objects: Return the underlying Type that represents the IReflect Object.
- // For expando object: this is the (Object) IReflectInstance.GetType(). For Type object it is this.
- // It could also return the baked type or the underlying enum type in RefEmit. See the comment in
- // code:TypeBuilder.SetConstantValue.
- public abstract Type UnderlyingSystemType {
- get;
- }
-
- // Returns true of this class is a true subclass of c. Everything
- // else returns false. If this class and c are the same class false is
- // returned.
- //
- [Pure]
- public virtual bool IsSubclassOf(Type c)
- {
- Type p = this;
- if (p == c)
- return false;
- while (p != null) {
- if (p == c)
- return true;
- p = p.BaseType;
- }
- return false;
- }
-
- // Returns true if the object passed is assignable to an instance of this class.
- // Everything else returns false.
- //
- [Pure]
- public virtual bool IsInstanceOfType(Object o)
- {
- if (o == null)
- return false;
-
- // No need for transparent proxy casting check here
- // because it never returns true for a non-rutnime type.
-
- return IsAssignableFrom(o.GetType());
- }
-
- // Returns true if an instance of Type c may be assigned
- // to an instance of this class. Return false otherwise.
- //
- [Pure]
- public virtual bool IsAssignableFrom(Type c)
- {
- if (c == null)
- return false;
-
- if (this == c)
- return true;
-
- // For backward-compatibility, we need to special case for the types
- // whose UnderlyingSystemType are RuntimeType objects.
- RuntimeType toType = this.UnderlyingSystemType as RuntimeType;
- if (toType != null)
- return toType.IsAssignableFrom(c);
-
- // If c is a subclass of this class, then c can be cast to this type.
- if (c.IsSubclassOf(this))
- return true;
-
- if (this.IsInterface)
- {
- return c.ImplementInterface(this);
- }
- else if (IsGenericParameter)
- {
- Type[] constraints = GetGenericParameterConstraints();
- for (int i = 0; i < constraints.Length; i++)
- if (!constraints[i].IsAssignableFrom(c))
- return false;
-
- return true;
- }
-
- return false;
- }
-
- // Base implementation that does only ==.
- [Pure]
- public virtual bool IsEquivalentTo(Type other)
- {
- return (this == other);
- }
-
- internal bool ImplementInterface(Type ifaceType)
- {
- Contract.Requires(ifaceType != null);
- Contract.Requires(ifaceType.IsInterface, "ifaceType must be an interface type");
-
- Type t = this;
- while (t != null)
- {
- Type[] interfaces = t.GetInterfaces();
- if (interfaces != null)
- {
- for (int i = 0; i < interfaces.Length; i++)
- {
- // Interfaces don't derive from other interfaces, they implement them.
- // So instead of IsSubclassOf, we should use ImplementInterface instead.
- if (interfaces[i] == ifaceType ||
- (interfaces[i] != null && interfaces[i].ImplementInterface(ifaceType)))
- return true;
- }
- }
-
- t = t.BaseType;
- }
-
- return false;
- }
-
- // This is only ever called on RuntimeType objects.
- internal string FormatTypeName()
- {
- return FormatTypeName(false);
- }
-
- internal virtual string FormatTypeName(bool serialization)
- {
- throw new NotImplementedException();
- }
-
- // ToString
- // Print the String Representation of the Type
- public override String ToString()
- {
- // Why do we add the "Type: " prefix? RuntimeType.ToString() doesn't include it.
- return "Type: " + Name;
- }
-
- // This method will return an array of classes based upon the array of
- // types.
- public static Type[] GetTypeArray(Object[] args) {
- if (args == null)
- throw new ArgumentNullException(nameof(args));
- Contract.EndContractBlock();
- Type[] cls = new Type[args.Length];
- for (int i = 0;i < cls.Length;i++)
- {
- if (args[i] == null)
- throw new ArgumentNullException();
- cls[i] = args[i].GetType();
- }
- return cls;
- }
-
- [Pure]
- public override bool Equals(Object o)
- {
- if (o == null)
- return false;
-
- return Equals(o as Type);
- }
-
- [Pure]
- public virtual bool Equals(Type o)
- {
- if ((object)o == null)
- return false;
-
- return (Object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType));
- }
-
- [Pure]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern bool operator ==(Type left, Type right);
-
- [Pure]
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- public static extern bool operator !=(Type left, Type right);
-
- public override int GetHashCode()
- {
- Type SystemType = UnderlyingSystemType;
- if (!Object.ReferenceEquals(SystemType, this))
- return SystemType.GetHashCode();
- return base.GetHashCode();
- }
-
-
- // GetInterfaceMap
- // This method will return an interface mapping for the interface
- // requested. It will throw an argument exception if the Type doesn't
- // implemenet the interface.
- public virtual InterfaceMapping GetInterfaceMap(Type interfaceType)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride"));
- }
-
- // this method is required so Object.GetType is not made virtual by the compiler
- public new Type GetType()
- {
- return base.GetType();
- }
-
- // private convenience data
- private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
- internal const BindingFlags DeclaredOnlyLookup = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;
-}
-}
diff --git a/src/mscorlib/src/System/TypeAccessException.cs b/src/mscorlib/src/System/TypeAccessException.cs
deleted file mode 100644
index 32afbdfeb8..0000000000
--- a/src/mscorlib/src/System/TypeAccessException.cs
+++ /dev/null
@@ -1,34 +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.Runtime.Serialization;
-
-namespace System
-{
- // TypeAccessException derives from TypeLoadException rather than MemberAccessException because in
- // pre-v4 releases of the runtime TypeLoadException was used in lieu of a TypeAccessException.
- [Serializable]
- public class TypeAccessException : TypeLoadException
- {
- public TypeAccessException()
- : base(SR.Arg_TypeAccessException)
- {
- HResult = __HResults.COR_E_TYPEACCESS;
- }
-
- public TypeAccessException(string message)
- : base(message)
- {
- HResult = __HResults.COR_E_TYPEACCESS;
- }
-
- public TypeAccessException(string message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_TYPEACCESS;
- }
-
- protected TypeAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/TypeCode.cs b/src/mscorlib/src/System/TypeCode.cs
deleted file mode 100644
index 293eb1f1aa..0000000000
--- a/src/mscorlib/src/System/TypeCode.cs
+++ /dev/null
@@ -1,48 +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.
-
-// The TypeCode enum represents the type code of an object. To obtain the
-// TypeCode for a given object, use the Value.GetTypeCode() method. The
-// TypeCode.Empty value represents a null object reference. The TypeCode.Object
-// value represents an object that doesn't implement the IConvertible interface. The
-// TypeCode.DBNull value represents the database null, which is distinct and
-// different from a null reference. The other type codes represent values that
-// use the given simple type encoding.
-//
-// Note that when an object has a given TypeCode, there is no guarantee that
-// the object is an instance of the corresponding System.XXX value class. For
-// example, an object with the type code TypeCode.Int32 might actually be an
-// instance of a nullable 32-bit integer type (with a value that isn't the
-// database null).
-//
-// There are no type codes for "Missing", "Error", "IDispatch", and "IUnknown".
-// These types of values are instead represented as classes. When the type code
-// of an object is TypeCode.Object, a further instance-of check can be used to
-// determine if the object is one of these values.
-
-namespace System
-{
- [Serializable]
- public enum TypeCode
- {
- Empty = 0, // Null reference
- Object = 1, // Instance that isn't a value
- DBNull = 2, // Database null value
- Boolean = 3, // Boolean
- Char = 4, // Unicode character
- SByte = 5, // Signed 8-bit integer
- Byte = 6, // Unsigned 8-bit integer
- Int16 = 7, // Signed 16-bit integer
- UInt16 = 8, // Unsigned 16-bit integer
- Int32 = 9, // Signed 32-bit integer
- UInt32 = 10, // Unsigned 32-bit integer
- Int64 = 11, // Signed 64-bit integer
- UInt64 = 12, // Unsigned 64-bit integer
- Single = 13, // IEEE 32-bit float
- Double = 14, // IEEE 64-bit double
- Decimal = 15, // Decimal
- DateTime = 16, // DateTime
- String = 18, // Unicode character string
- }
-}
diff --git a/src/mscorlib/src/System/TypeInitializationException.cs b/src/mscorlib/src/System/TypeInitializationException.cs
deleted file mode 100644
index 9191028346..0000000000
--- a/src/mscorlib/src/System/TypeInitializationException.cs
+++ /dev/null
@@ -1,79 +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 to wrap exceptions thrown by
-** a type's class initializer (.cctor). This is sufficiently
-** distinct from a TypeLoadException, which means we couldn't
-** find the type.
-**
-**
-=============================================================================*/
-
-using System.Globalization;
-using System.Runtime.Serialization;
-
-namespace System
-{
- [Serializable]
- public sealed class TypeInitializationException : SystemException
- {
- private String _typeName;
-
- // This exception is not creatable without specifying the
- // inner exception.
- private TypeInitializationException()
- : base(SR.TypeInitialization_Default)
- {
- HResult = __HResults.COR_E_TYPEINITIALIZATION;
- }
-
-
- public TypeInitializationException(String fullTypeName, Exception innerException)
- : this(fullTypeName, SR.Format(SR.TypeInitialization_Type, fullTypeName), innerException)
- {
- }
-
- // This is called from within the runtime. I believe this is necessary
- // for Interop only, though it's not particularly useful.
- internal TypeInitializationException(String message) : base(message)
- {
- HResult = __HResults.COR_E_TYPEINITIALIZATION;
- }
-
- internal TypeInitializationException(String fullTypeName, String message, Exception innerException)
- : base(message, innerException)
- {
- _typeName = fullTypeName;
- HResult = __HResults.COR_E_TYPEINITIALIZATION;
- }
-
- internal TypeInitializationException(SerializationInfo info, StreamingContext context)
- : base(info, context)
- {
- _typeName = info.GetString("TypeName");
- }
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
- info.AddValue("TypeName", TypeName, typeof(String));
- }
-
- public String TypeName
- {
- get
- {
- if (_typeName == null)
- {
- return String.Empty;
- }
- return _typeName;
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs
index 7bc3a1bcce..85e1da5920 100644
--- a/src/mscorlib/src/System/TypeLoadException.cs
+++ b/src/mscorlib/src/System/TypeLoadException.cs
@@ -10,56 +10,63 @@
**
**
=============================================================================*/
-namespace System {
-
- using System;
- using System.Globalization;
- using System.Runtime.Remoting;
- using System.Runtime.Serialization;
- using System.Runtime.InteropServices;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Security;
- using System.Diagnostics.Contracts;
- [Serializable]
- public class TypeLoadException : SystemException, ISerializable {
+using System;
+using System.Globalization;
+using System.Runtime.Remoting;
+using System.Runtime.Serialization;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Security;
+using System.Diagnostics.Contracts;
- public TypeLoadException()
- : base(Environment.GetResourceString("Arg_TypeLoadException")) {
- SetErrorCode(__HResults.COR_E_TYPELOAD);
+namespace System
+{
+ [Serializable]
+ public class TypeLoadException : SystemException, ISerializable
+ {
+ public TypeLoadException()
+ : base(SR.Arg_TypeLoadException)
+ {
+ HResult = __HResults.COR_E_TYPELOAD;
}
-
- public TypeLoadException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_TYPELOAD);
+
+ public TypeLoadException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_TYPELOAD;
}
-
- public TypeLoadException(String message, Exception inner)
- : base(message, inner) {
- SetErrorCode(__HResults.COR_E_TYPELOAD);
+
+ public TypeLoadException(String message, Exception inner)
+ : base(message, inner)
+ {
+ HResult = __HResults.COR_E_TYPELOAD;
}
-
+
public override String Message
{
- get {
+ get
+ {
SetMessageField();
return _message;
}
}
-
+
private void SetMessageField()
{
- if (_message == null) {
+ if (_message == null)
+ {
if ((ClassName == null) &&
(ResourceId == 0))
- _message = Environment.GetResourceString("Arg_TypeLoadException");
+ _message = SR.Arg_TypeLoadException;
- else {
+ else
+ {
if (AssemblyName == null)
- AssemblyName = Environment.GetResourceString("IO_UnknownFileName");
+ AssemblyName = SR.IO_UnknownFileName;
if (ClassName == null)
- ClassName = Environment.GetResourceString("IO_UnknownFileName");
+ ClassName = SR.IO_UnknownFileName;
String format = null;
GetTypeLoadExceptionMessage(ResourceId, JitHelpers.GetStringHandleOnStack(ref format));
@@ -70,50 +77,53 @@ namespace System {
public String TypeName
{
- get {
+ get
+ {
if (ClassName == null)
return String.Empty;
return ClassName;
}
}
-
+
// This is called from inside the EE.
private TypeLoadException(String className,
String assemblyName,
String messageArg,
- int resourceId)
+ int resourceId)
: base(null)
{
- SetErrorCode(__HResults.COR_E_TYPELOAD);
- ClassName = className;
+ HResult = __HResults.COR_E_TYPELOAD;
+ ClassName = className;
AssemblyName = assemblyName;
MessageArg = messageArg;
ResourceId = resourceId;
// Set the _message field eagerly; debuggers look at this field to
// display error info. They don't call the Message property.
- SetMessageField();
+ SetMessageField();
}
- protected TypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context) {
+ protected TypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
- ClassName = info.GetString("TypeLoadClassName");
+ ClassName = info.GetString("TypeLoadClassName");
AssemblyName = info.GetString("TypeLoadAssemblyName");
MessageArg = info.GetString("TypeLoadMessageArg");
ResourceId = info.GetInt32("TypeLoadResourceID");
}
-
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetTypeLoadExceptionMessage(int resourceId, StringHandleOnStack retString);
-
+
//We can rely on the serialization mechanism on Exception to handle most of our needs, but
//we need to add a few fields of our own.
- public override void GetObjectData(SerializationInfo info, StreamingContext context) {
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
@@ -124,13 +134,13 @@ namespace System {
info.AddValue("TypeLoadMessageArg", MessageArg, typeof(String));
info.AddValue("TypeLoadResourceID", ResourceId);
}
-
+
// If ClassName != null, GetMessage will construct on the fly using it
// and ResourceId (mscorrc.dll). This allows customization of the
// class name format depending on the language environment.
- private String ClassName;
- private String AssemblyName;
- private String MessageArg;
- internal int ResourceId;
+ private String ClassName;
+ private String AssemblyName;
+ private String MessageArg;
+ internal int ResourceId;
}
}
diff --git a/src/mscorlib/src/System/TypeNameParser.cs b/src/mscorlib/src/System/TypeNameParser.cs
index 844578210f..f9d608968f 100644
--- a/src/mscorlib/src/System/TypeNameParser.cs
+++ b/src/mscorlib/src/System/TypeNameParser.cs
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
+
using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -73,7 +74,7 @@ namespace System
if (typeName == null)
throw new ArgumentNullException(nameof(typeName));
if (typeName.Length > 0 && typeName[0] == '\0')
- throw new ArgumentException(Environment.GetResourceString("Format_StringZeroLength"));
+ throw new ArgumentException(SR.Format_StringZeroLength);
Contract.EndContractBlock();
Type ret = null;
@@ -96,7 +97,7 @@ namespace System
#region Private Data Members
private SafeTypeNameParserHandle m_NativeParser;
- private static readonly char[] SPECIAL_CHARS = {',', '[', ']', '&', '*', '+', '\\'}; /* see typeparse.h */
+ private static readonly char[] SPECIAL_CHARS = { ',', '[', ']', '&', '*', '+', '\\' }; /* see typeparse.h */
#endregion
#region Constructor and Disposer
@@ -142,7 +143,7 @@ namespace System
{
// This can only happen if the type name is an empty string or if the first char is '\0'
if (throwOnError)
- throw new TypeLoadException(Environment.GetResourceString("Arg_TypeLoadNullStr"));
+ throw new TypeLoadException(SR.Arg_TypeLoadNullStr);
return null;
}
@@ -207,7 +208,7 @@ namespace System
// Other exceptions like BadImangeFormatException should still fly.
try
{
- assembly = RuntimeAssembly.InternalLoad(asmName, null, ref stackMark, false /*forIntrospection*/);
+ assembly = RuntimeAssembly.InternalLoad(asmName, null, ref stackMark, false /*forIntrospection*/);
}
catch (FileNotFoundException)
{
@@ -220,7 +221,7 @@ namespace System
assembly = assemblyResolver(new AssemblyName(asmName));
if (assembly == null && throwOnError)
{
- throw new FileNotFoundException(Environment.GetResourceString("FileNotFound_ResolveAssembly", asmName));
+ throw new FileNotFoundException(SR.Format(SR.FileNotFound_ResolveAssembly, asmName));
}
}
@@ -244,8 +245,8 @@ namespace System
if (type == null && throwOnError)
{
string errorString = assembly == null ?
- Environment.GetResourceString("TypeLoad_ResolveType", OuterMostTypeName) :
- Environment.GetResourceString("TypeLoad_ResolveTypeFromAssembly", OuterMostTypeName, assembly.FullName);
+ SR.Format(SR.TypeLoad_ResolveType, OuterMostTypeName):
+ SR.Format(SR.TypeLoad_ResolveTypeFromAssembly, OuterMostTypeName, assembly.FullName);
throw new TypeLoadException(errorString);
}
@@ -276,7 +277,7 @@ namespace System
if (type == null)
{
if (throwOnError)
- throw new TypeLoadException(Environment.GetResourceString("TypeLoad_ResolveNestedType", names[i], names[i-1]));
+ throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveNestedType, names[i], names[i - 1]));
else
break;
}
@@ -339,7 +340,7 @@ namespace System
{
string assemblyName = null;
_GetAssemblyName(m_NativeParser, JitHelpers.GetStringHandleOnStack(ref assemblyName));
-
+
return assemblyName;
}
#endregion
diff --git a/src/mscorlib/src/System/TypeUnloadedException.cs b/src/mscorlib/src/System/TypeUnloadedException.cs
deleted file mode 100644
index f05d673a74..0000000000
--- a/src/mscorlib/src/System/TypeUnloadedException.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: Exception class for attempt to access an unloaded class
-**
-**
-=============================================================================*/
-
-namespace System {
-
- using System.Runtime.Serialization;
-
- [Serializable]
- public class TypeUnloadedException : SystemException {
- public TypeUnloadedException()
- : base(Environment.GetResourceString("Arg_TypeUnloadedException")) {
- SetErrorCode(__HResults.COR_E_TYPEUNLOADED);
- }
-
- public TypeUnloadedException(String message)
- : base(message) {
- SetErrorCode(__HResults.COR_E_TYPEUNLOADED);
- }
-
- public TypeUnloadedException(String message, Exception innerException)
- : base(message, innerException) {
- SetErrorCode(__HResults.COR_E_TYPEUNLOADED);
- }
-
- //
- // This constructor is required for serialization;
- //
- protected TypeUnloadedException(SerializationInfo info, StreamingContext context) : base (info, context) {
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/TypedReference.cs b/src/mscorlib/src/System/TypedReference.cs
index 5e8f3c4c04..ca65082158 100644
--- a/src/mscorlib/src/System/TypedReference.cs
+++ b/src/mscorlib/src/System/TypedReference.cs
@@ -2,10 +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.
-namespace System {
-
+namespace System
+{
// TypedReference is basically only ever seen on the call stack, and in param arrays.
// These are blob that must be dealt with by the compiler.
+
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
@@ -14,7 +15,7 @@ namespace System {
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
- [CLSCompliant(false)]
+ [CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable] // This only applies to field layout
public struct TypedReference
{
@@ -22,14 +23,15 @@ namespace System {
private IntPtr Type;
[CLSCompliant(false)]
- public static TypedReference MakeTypedReference(Object target, FieldInfo[] flds) {
+ public static TypedReference MakeTypedReference(Object target, FieldInfo[] flds)
+ {
if (target == null)
throw new ArgumentNullException(nameof(target));
if (flds == null)
throw new ArgumentNullException(nameof(flds));
Contract.EndContractBlock();
if (flds.Length == 0)
- throw new ArgumentException(Environment.GetResourceString("Arg_ArrayZeroError"));
+ throw new ArgumentException(SR.Arg_ArrayZeroError);
IntPtr[] fields = new IntPtr[flds.Length];
// For proper handling of Nullable<T> don't change GetType() to something like 'IsAssignableFrom'
@@ -39,29 +41,29 @@ namespace System {
{
RuntimeFieldInfo field = flds[i] as RuntimeFieldInfo;
if (field == null)
- throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeFieldInfo"));
+ throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo);
if (field.IsInitOnly || field.IsStatic)
- throw new ArgumentException(Environment.GetResourceString("Argument_TypedReferenceInvalidField"));
-
+ throw new ArgumentException(SR.Argument_TypedReferenceInvalidField);
+
if (targetType != field.GetDeclaringTypeInternal() && !targetType.IsSubclassOf(field.GetDeclaringTypeInternal()))
- throw new MissingMemberException(Environment.GetResourceString("MissingMemberTypeRef"));
+ throw new MissingMemberException(SR.MissingMemberTypeRef);
RuntimeType fieldType = (RuntimeType)field.FieldType;
if (fieldType.IsPrimitive)
- throw new ArgumentException(Environment.GetResourceString("Arg_TypeRefPrimitve"));
-
+ throw new ArgumentException(SR.Arg_TypeRefPrimitve);
+
if (i < (flds.Length - 1) && !fieldType.IsValueType)
- throw new MissingMemberException(Environment.GetResourceString("MissingMemberNestErr"));
-
+ throw new MissingMemberException(SR.MissingMemberNestErr);
+
fields[i] = field.FieldHandle.Value;
targetType = fieldType;
}
- TypedReference result = new TypedReference ();
+ TypedReference result = new TypedReference();
// reference to TypedReference is banned, so have to pass result as pointer
- unsafe
+ unsafe
{
InternalMakeTypedReference(&result, target, fields, targetType);
}
@@ -82,7 +84,7 @@ namespace System {
public override bool Equals(Object o)
{
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_NYI"));
+ throw new NotSupportedException(SR.NotSupported_NYI);
}
public unsafe static Object ToObject(TypedReference value)
@@ -91,22 +93,22 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal unsafe extern static Object InternalToObject(void * value);
+ internal unsafe extern static Object InternalToObject(void* value);
- internal bool IsNull
- {
+ internal bool IsNull
+ {
get
{
- return Value.IsNull() && Type.IsNull();
+ return Value.IsNull() && Type.IsNull();
}
}
- public static Type GetTargetType (TypedReference value)
+ public static Type GetTargetType(TypedReference value)
{
return __reftype(value);
}
- public static RuntimeTypeHandle TargetTypeToken (TypedReference value)
+ public static RuntimeTypeHandle TargetTypeToken(TypedReference value)
{
return __reftype(value).TypeHandle;
}
@@ -119,7 +121,6 @@ namespace System {
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal unsafe extern static void InternalSetTypedReference(void * target, Object value);
+ internal unsafe extern static void InternalSetTypedReference(void* target, Object value);
}
-
}
diff --git a/src/mscorlib/src/System/UInt16.cs b/src/mscorlib/src/System/UInt16.cs
index 5cd1a65b70..e4a6837ae2 100644
--- a/src/mscorlib/src/System/UInt16.cs
+++ b/src/mscorlib/src/System/UInt16.cs
@@ -10,46 +10,54 @@
**
**
===========================================================*/
-namespace System {
- using System.Globalization;
- using System;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
+using System.Globalization;
+using System;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// Wrapper for unsigned 16 bit integers.
-[Serializable]
-[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+ [Serializable]
+ [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct UInt16 : IComparable, IFormattable, IConvertible
- , IComparable<UInt16>, IEquatable<UInt16>
+ , IComparable<UInt16>, IEquatable<UInt16>
{
private ushort m_value;
-
+
public const ushort MaxValue = (ushort)0xFFFF;
public const ushort MinValue = 0;
-
-
+
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt16, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is UInt16) {
+ if (value is UInt16)
+ {
return ((int)m_value - (int)(((UInt16)value).m_value));
}
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeUInt16"));
+ throw new ArgumentException(SR.Arg_MustBeUInt16);
}
- public int CompareTo(UInt16 value) {
+ public int CompareTo(UInt16 value)
+ {
return ((int)m_value - (int)value);
}
-
- public override bool Equals(Object obj) {
- if (!(obj is UInt16)) {
+
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is UInt16))
+ {
return false;
}
return m_value == ((UInt16)obj).m_value;
@@ -62,174 +70,190 @@ namespace System {
}
// Returns a HashCode for the UInt16
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return (int)m_value;
}
// Converts the current value to a String in base-10 with no extra padding.
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
-
- public String ToString(String format, IFormatProvider provider) {
+
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static ushort Parse(String s) {
+ public static ushort Parse(String s)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
+
[CLSCompliant(false)]
- public static ushort Parse(String s, NumberStyles style) {
+ public static ushort Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
- public static ushort Parse(String s, IFormatProvider provider) {
+ public static ushort Parse(String s, IFormatProvider provider)
+ {
return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
-
+
[CLSCompliant(false)]
- public static ushort Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static ushort Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
-
- private static ushort Parse(String s, NumberStyles style, NumberFormatInfo info) {
-
+
+ private static ushort Parse(String s, NumberStyles style, NumberFormatInfo info)
+ {
uint i = 0;
- try {
+ try
+ {
i = Number.ParseUInt32(s, style, info);
}
- catch(OverflowException e) {
- throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"), e);
+ catch (OverflowException e)
+ {
+ throw new OverflowException(SR.Overflow_UInt16, e);
}
- if (i > MaxValue) throw new OverflowException(Environment.GetResourceString("Overflow_UInt16"));
+ if (i > MaxValue) throw new OverflowException(SR.Overflow_UInt16);
return (ushort)i;
}
[CLSCompliant(false)]
- public static bool TryParse(String s, out UInt16 result) {
+ public static bool TryParse(String s, out UInt16 result)
+ {
return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result) {
+ public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result)
+ {
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(String s, NumberStyles style, NumberFormatInfo info, out UInt16 result)
+ {
result = 0;
UInt32 i;
- if (!Number.TryParseUInt32(s, style, info, out i)) {
+ if (!Number.TryParseUInt32(s, style, info, out i))
+ {
return false;
}
- if (i > MaxValue) {
+ if (i > MaxValue)
+ {
return false;
}
- result = (UInt16) i;
+ result = (UInt16)i;
return true;
}
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.UInt16;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "UInt16", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/UInt32.cs b/src/mscorlib/src/System/UInt32.cs
index fc3f10f96f..7c27efef39 100644
--- a/src/mscorlib/src/System/UInt32.cs
+++ b/src/mscorlib/src/System/UInt32.cs
@@ -11,16 +11,18 @@
**
**
===========================================================*/
-namespace System {
- using System.Globalization;
- using System;
- using System.Runtime;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
+using System.Globalization;
+using System;
+using System.Runtime;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// * Wrapper for unsigned 32 bit integers.
[Serializable]
- [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+ [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct UInt32 : IComparable, IFormattable, IConvertible
, IComparable<UInt32>, IEquatable<UInt32>
{
@@ -28,19 +30,22 @@ namespace System {
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
-
-
+
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is UInt32) {
+ if (value is UInt32)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
@@ -48,19 +53,22 @@ namespace System {
if (m_value > i) return 1;
return 0;
}
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeUInt32"));
+ throw new ArgumentException(SR.Arg_MustBeUInt32);
}
- public int CompareTo(UInt32 value) {
+ public int CompareTo(UInt32 value)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
-
- public override bool Equals(Object obj) {
- if (!(obj is UInt32)) {
+
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is UInt32))
+ {
return false;
}
return m_value == ((UInt32)obj).m_value;
@@ -73,61 +81,72 @@ namespace System {
}
// The absolute value of the int contained.
- public override int GetHashCode() {
- return ((int) m_value);
+ public override int GetHashCode()
+ {
+ return ((int)m_value);
}
-
+
// The base 10 representation of the number with no extra padding.
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.CurrentInfo);
}
- public String ToString(IFormatProvider provider) {
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, null, NumberFormatInfo.GetInstance(provider));
}
- public String ToString(String format) {
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt32(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static uint Parse(String s) {
+ public static uint Parse(String s)
+ {
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
+
[CLSCompliant(false)]
- public static uint Parse(String s, NumberStyles style) {
+ public static uint Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
- public static uint Parse(String s, IFormatProvider provider) {
+ public static uint Parse(String s, IFormatProvider provider)
+ {
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static uint Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static uint Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static bool TryParse(String s, out UInt32 result) {
+ public static bool TryParse(String s, out UInt32 result)
+ {
return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
- public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) {
+ public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
@@ -135,83 +154,84 @@ namespace System {
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.UInt32;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return Convert.ToUInt64(m_value);
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "UInt32", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
diff --git a/src/mscorlib/src/System/UInt64.cs b/src/mscorlib/src/System/UInt64.cs
index 3b64f056e9..0b79b6a7d8 100644
--- a/src/mscorlib/src/System/UInt64.cs
+++ b/src/mscorlib/src/System/UInt64.cs
@@ -10,34 +10,39 @@
**
**
===========================================================*/
-namespace System {
- using System.Globalization;
- using System;
- using System.Runtime.InteropServices;
- using System.Diagnostics.Contracts;
+using System.Globalization;
+using System;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
// Wrapper for unsigned 64 bit integers.
-[Serializable]
-[CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
+ [Serializable]
+ [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
public struct UInt64 : IComparable, IFormattable, IConvertible
- , IComparable<UInt64>, IEquatable<UInt64>
+ , IComparable<UInt64>, IEquatable<UInt64>
{
private ulong m_value;
-
- public const ulong MaxValue = (ulong) 0xffffffffffffffffL;
+
+ public const ulong MaxValue = (ulong)0xffffffffffffffffL;
public const ulong MinValue = 0x0;
-
+
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt64, this method throws an ArgumentException.
//
- public int CompareTo(Object value) {
- if (value == null) {
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
return 1;
}
- if (value is UInt64) {
+ if (value is UInt64)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
ulong i = (ulong)value;
@@ -45,19 +50,22 @@ namespace System {
if (m_value > i) return 1;
return 0;
}
- throw new ArgumentException (Environment.GetResourceString("Arg_MustBeUInt64"));
+ throw new ArgumentException(SR.Arg_MustBeUInt64);
}
- public int CompareTo(UInt64 value) {
+ public int CompareTo(UInt64 value)
+ {
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
-
- public override bool Equals(Object obj) {
- if (!(obj is UInt64)) {
+
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is UInt64))
+ {
return false;
}
return m_value == ((UInt64)obj).m_value;
@@ -70,59 +78,70 @@ namespace System {
}
// The value of the lower 32 bits XORed with the uppper 32 bits.
- public override int GetHashCode() {
+ public override int GetHashCode()
+ {
return ((int)m_value) ^ (int)(m_value >> 32);
}
- public override String ToString() {
+ public override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, null, NumberFormatInfo.CurrentInfo);
}
-
- public String ToString(IFormatProvider provider) {
+
+ public String ToString(IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, null, NumberFormatInfo.GetInstance(provider));
- }
-
- public String ToString(String format) {
+ }
+
+ public String ToString(String format)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, format, NumberFormatInfo.CurrentInfo);
}
- public String ToString(String format, IFormatProvider provider) {
+ public String ToString(String format, IFormatProvider provider)
+ {
Contract.Ensures(Contract.Result<String>() != null);
return Number.FormatUInt64(m_value, format, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static ulong Parse(String s) {
+ public static ulong Parse(String s)
+ {
return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
-
+
[CLSCompliant(false)]
- public static ulong Parse(String s, NumberStyles style) {
+ public static ulong Parse(String s, NumberStyles style)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt64(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
- public static ulong Parse(string s, IFormatProvider provider) {
+ public static ulong Parse(string s, IFormatProvider provider)
+ {
return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static ulong Parse(String s, NumberStyles style, IFormatProvider provider) {
+ public static ulong Parse(String s, NumberStyles style, IFormatProvider provider)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
- public static Boolean TryParse(String s, out UInt64 result) {
+ public static Boolean TryParse(String s, out UInt64 result)
+ {
return Number.TryParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
- public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) {
+ public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result)
+ {
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
@@ -130,84 +149,85 @@ namespace System {
//
// IConvertible implementation
//
-
- public TypeCode GetTypeCode() {
+
+ public TypeCode GetTypeCode()
+ {
return TypeCode.UInt64;
}
- /// <internalonly/>
- bool IConvertible.ToBoolean(IFormatProvider provider) {
+ bool IConvertible.ToBoolean(IFormatProvider provider)
+ {
return Convert.ToBoolean(m_value);
}
- /// <internalonly/>
- char IConvertible.ToChar(IFormatProvider provider) {
+ char IConvertible.ToChar(IFormatProvider provider)
+ {
return Convert.ToChar(m_value);
}
- /// <internalonly/>
- sbyte IConvertible.ToSByte(IFormatProvider provider) {
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
return Convert.ToSByte(m_value);
}
- /// <internalonly/>
- byte IConvertible.ToByte(IFormatProvider provider) {
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
return Convert.ToByte(m_value);
}
- /// <internalonly/>
- short IConvertible.ToInt16(IFormatProvider provider) {
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
return Convert.ToInt16(m_value);
}
- /// <internalonly/>
- ushort IConvertible.ToUInt16(IFormatProvider provider) {
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
return Convert.ToUInt16(m_value);
}
- /// <internalonly/>
- int IConvertible.ToInt32(IFormatProvider provider) {
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
return Convert.ToInt32(m_value);
}
- /// <internalonly/>
- uint IConvertible.ToUInt32(IFormatProvider provider) {
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
return Convert.ToUInt32(m_value);
}
- /// <internalonly/>
- long IConvertible.ToInt64(IFormatProvider provider) {
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
return Convert.ToInt64(m_value);
}
- /// <internalonly/>
- ulong IConvertible.ToUInt64(IFormatProvider provider) {
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
return m_value;
}
- /// <internalonly/>
- float IConvertible.ToSingle(IFormatProvider provider) {
+ float IConvertible.ToSingle(IFormatProvider provider)
+ {
return Convert.ToSingle(m_value);
}
- /// <internalonly/>
- double IConvertible.ToDouble(IFormatProvider provider) {
+ double IConvertible.ToDouble(IFormatProvider provider)
+ {
return Convert.ToDouble(m_value);
}
- /// <internalonly/>
- Decimal IConvertible.ToDecimal(IFormatProvider provider) {
+ Decimal IConvertible.ToDecimal(IFormatProvider provider)
+ {
return Convert.ToDecimal(m_value);
}
- /// <internalonly/>
- DateTime IConvertible.ToDateTime(IFormatProvider provider) {
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "UInt64", "DateTime"));
+ DateTime IConvertible.ToDateTime(IFormatProvider provider)
+ {
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime"));
}
- /// <internalonly/>
- Object IConvertible.ToType(Type type, IFormatProvider provider) {
- return Convert.DefaultToType((IConvertible)this, type, provider);
+ Object IConvertible.ToType(Type type, IFormatProvider provider)
+ {
+ return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
diff --git a/src/mscorlib/src/System/UIntPtr.cs b/src/mscorlib/src/System/UIntPtr.cs
index d0f988dbb8..09b7e51e89 100644
--- a/src/mscorlib/src/System/UIntPtr.cs
+++ b/src/mscorlib/src/System/UIntPtr.cs
@@ -11,8 +11,8 @@
**
===========================================================*/
-namespace System {
-
+namespace System
+{
using System;
using System.Globalization;
using System.Runtime.Serialization;
@@ -20,25 +20,25 @@ namespace System {
using System.Diagnostics.Contracts;
[Serializable]
- [CLSCompliant(false)]
+ [CLSCompliant(false)]
public struct UIntPtr : IEquatable<UIntPtr>, ISerializable
{
unsafe private void* m_value;
public static readonly UIntPtr Zero;
-
+
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(uint value)
{
- m_value = (void *)value;
+ m_value = (void*)value;
}
[System.Runtime.Versioning.NonVersionable]
public unsafe UIntPtr(ulong value)
{
#if BIT64
- m_value = (void *)value;
+ m_value = (void*)value;
#else // 32
m_value = (void*)checked((uint)value);
#endif
@@ -51,27 +51,32 @@ namespace System {
m_value = value;
}
- private unsafe UIntPtr(SerializationInfo info, StreamingContext context) {
+ private unsafe UIntPtr(SerializationInfo info, StreamingContext context)
+ {
ulong l = info.GetUInt64("value");
- if (Size==4 && l>UInt32.MaxValue) {
- throw new ArgumentException(Environment.GetResourceString("Serialization_InvalidPtrValue"));
+ if (Size == 4 && l > UInt32.MaxValue)
+ {
+ throw new ArgumentException(SR.Serialization_InvalidPtrValue);
}
- m_value = (void *)l;
+ m_value = (void*)l;
}
unsafe void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info==null) {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
info.AddValue("value", (ulong)m_value);
}
- public unsafe override bool Equals(Object obj) {
- if (obj is UIntPtr) {
+ public unsafe override bool Equals(Object obj)
+ {
+ if (obj is UIntPtr)
+ {
return (m_value == ((UIntPtr)obj).m_value);
}
return false;
@@ -81,8 +86,9 @@ namespace System {
{
return m_value == other.m_value;
}
-
- public unsafe override int GetHashCode() {
+
+ public unsafe override int GetHashCode()
+ {
#if BIT64
ulong l = (ulong)m_value;
return (unchecked((int)l) ^ (int)(l >> 32));
@@ -92,7 +98,8 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe uint ToUInt32() {
+ public unsafe uint ToUInt32()
+ {
#if BIT64
return checked((uint)m_value);
#else // 32
@@ -101,11 +108,13 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe ulong ToUInt64() {
+ public unsafe ulong ToUInt64()
+ {
return (ulong)m_value;
}
- public unsafe override String ToString() {
+ public unsafe override String ToString()
+ {
Contract.Ensures(Contract.Result<String>() != null);
#if BIT64
@@ -116,13 +125,13 @@ namespace System {
}
[System.Runtime.Versioning.NonVersionable]
- public static explicit operator UIntPtr (uint value)
+ public static explicit operator UIntPtr(uint value)
{
return new UIntPtr(value);
}
[System.Runtime.Versioning.NonVersionable]
- public static explicit operator UIntPtr (ulong value)
+ public static explicit operator UIntPtr(ulong value)
{
return new UIntPtr(value);
}
@@ -135,17 +144,17 @@ namespace System {
#else // 32
return (uint)value.m_value;
#endif
- }
+ }
[System.Runtime.Versioning.NonVersionable]
- public unsafe static explicit operator ulong (UIntPtr value)
+ public unsafe static explicit operator ulong(UIntPtr value)
{
return (ulong)value.m_value;
}
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
- public static unsafe explicit operator UIntPtr (void* value)
+ public static unsafe explicit operator UIntPtr(void* value)
{
return new UIntPtr(value);
}
@@ -159,41 +168,45 @@ namespace System {
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool operator == (UIntPtr value1, UIntPtr value2)
+ public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2)
{
return value1.m_value == value2.m_value;
}
[System.Runtime.Versioning.NonVersionable]
- public unsafe static bool operator != (UIntPtr value1, UIntPtr value2)
+ public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2)
{
return value1.m_value != value2.m_value;
}
[System.Runtime.Versioning.NonVersionable]
- public static UIntPtr Add(UIntPtr pointer, int offset) {
+ public static UIntPtr Add(UIntPtr pointer, int offset)
+ {
return pointer + offset;
}
[System.Runtime.Versioning.NonVersionable]
- public static UIntPtr operator +(UIntPtr pointer, int offset) {
+ public static UIntPtr operator +(UIntPtr pointer, int offset)
+ {
#if BIT64
- return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
+ return new UIntPtr(pointer.ToUInt64() + (ulong)offset);
#else // 32
return new UIntPtr(pointer.ToUInt32() + (uint)offset);
#endif
}
[System.Runtime.Versioning.NonVersionable]
- public static UIntPtr Subtract(UIntPtr pointer, int offset) {
+ public static UIntPtr Subtract(UIntPtr pointer, int offset)
+ {
return pointer - offset;
}
[System.Runtime.Versioning.NonVersionable]
- public static UIntPtr operator -(UIntPtr pointer, int offset) {
+ public static UIntPtr operator -(UIntPtr pointer, int offset)
+ {
#if BIT64
- return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
+ return new UIntPtr(pointer.ToUInt64() - (ulong)offset);
#else // 32
return new UIntPtr(pointer.ToUInt32() - (uint)offset);
#endif
@@ -211,15 +224,14 @@ namespace System {
#endif
}
}
-
+
[CLSCompliant(false)]
[System.Runtime.Versioning.NonVersionable]
public unsafe void* ToPointer()
{
return m_value;
}
-
- }
+ }
}
diff --git a/src/mscorlib/src/System/UnauthorizedAccessException.cs b/src/mscorlib/src/System/UnauthorizedAccessException.cs
deleted file mode 100644
index 997358826f..0000000000
--- a/src/mscorlib/src/System/UnauthorizedAccessException.cs
+++ /dev/null
@@ -1,45 +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: An exception for OS 'access denied' types of
-** errors, including IO and limited security types
-** of errors.
-**
-**
-===========================================================*/
-
-using System.Runtime.Serialization;
-
-namespace System
-{
- // The UnauthorizedAccessException is thrown when access errors
- // occur from IO or other OS methods.
- [Serializable]
- public class UnauthorizedAccessException : SystemException
- {
- public UnauthorizedAccessException()
- : base(SR.Arg_UnauthorizedAccessException)
- {
- HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
- }
-
- public UnauthorizedAccessException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
- }
-
- public UnauthorizedAccessException(String message, Exception inner)
- : base(message, inner)
- {
- HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
- }
-
- protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { }
- }
-}
diff --git a/src/mscorlib/src/System/UnhandledExceptionEventArgs.cs b/src/mscorlib/src/System/UnhandledExceptionEventArgs.cs
deleted file mode 100644
index d33830181c..0000000000
--- a/src/mscorlib/src/System/UnhandledExceptionEventArgs.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.
-
-namespace System
-{
- [Serializable]
- public class UnhandledExceptionEventArgs : EventArgs
- {
- private Object _exception;
- private bool _isTerminating;
-
- public UnhandledExceptionEventArgs(Object exception, bool isTerminating)
- {
- _exception = exception;
- _isTerminating = isTerminating;
- }
-
- public Object ExceptionObject
- {
- get { return _exception; }
- }
-
- public bool IsTerminating
- {
- get { return _isTerminating; }
- }
- }
-}
diff --git a/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs b/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
deleted file mode 100644
index b99414c189..0000000000
--- a/src/mscorlib/src/System/UnhandledExceptionEventHandler.cs
+++ /dev/null
@@ -1,9 +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.
-
-namespace System
-{
- [Serializable]
- public delegate void UnhandledExceptionEventHandler(Object sender, UnhandledExceptionEventArgs e);
-}
diff --git a/src/mscorlib/src/System/UnitySerializationHolder.cs b/src/mscorlib/src/System/UnitySerializationHolder.cs
deleted file mode 100644
index 712391a915..0000000000
--- a/src/mscorlib/src/System/UnitySerializationHolder.cs
+++ /dev/null
@@ -1,357 +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.Runtime.Remoting;
-using System.Runtime.Serialization;
-using System.Reflection;
-using System.Globalization;
-using System.Runtime.Versioning;
-using System.Collections.Generic;
-using System.Diagnostics.Contracts;
-
-namespace System {
-
- [Serializable]
- // Holds classes (Empty, Null, Missing) for which we guarantee that there is only ever one instance of.
- internal class UnitySerializationHolder : ISerializable, IObjectReference
- {
- #region Internal Constants
- internal const int EmptyUnity = 0x0001;
- internal const int NullUnity = 0x0002;
- internal const int MissingUnity = 0x0003;
- internal const int RuntimeTypeUnity = 0x0004;
- internal const int ModuleUnity = 0x0005;
- internal const int AssemblyUnity = 0x0006;
- internal const int GenericParameterTypeUnity = 0x0007;
- internal const int PartialInstantiationTypeUnity = 0x0008;
-
- internal const int Pointer = 0x0001;
- internal const int Array = 0x0002;
- internal const int SzArray = 0x0003;
- internal const int ByRef = 0x0004;
- #endregion
-
- #region Internal Static Members
- internal static void GetUnitySerializationInfo(SerializationInfo info, Missing missing)
- {
- info.SetType(typeof(UnitySerializationHolder));
- info.AddValue("UnityType", MissingUnity);
- }
-
- internal static RuntimeType AddElementTypes(SerializationInfo info, RuntimeType type)
- {
- List<int> elementTypes = new List<int>();
- while(type.HasElementType)
- {
- if (type.IsSzArray)
- {
- elementTypes.Add(SzArray);
- }
- else if (type.IsArray)
- {
- elementTypes.Add(type.GetArrayRank());
- elementTypes.Add(Array);
- }
- else if (type.IsPointer)
- {
- elementTypes.Add(Pointer);
- }
- else if (type.IsByRef)
- {
- elementTypes.Add(ByRef);
- }
-
- type = (RuntimeType)type.GetElementType();
- }
-
- info.AddValue("ElementTypes", elementTypes.ToArray(), typeof(int[]));
-
- return type;
- }
-
- internal Type MakeElementTypes(Type type)
- {
- for (int i = m_elementTypes.Length - 1; i >= 0; i --)
- {
- if (m_elementTypes[i] == SzArray)
- {
- type = type.MakeArrayType();
- }
- else if (m_elementTypes[i] == Array)
- {
- type = type.MakeArrayType(m_elementTypes[--i]);
- }
- else if ((m_elementTypes[i] == Pointer))
- {
- type = type.MakePointerType();
- }
- else if ((m_elementTypes[i] == ByRef))
- {
- type = type.MakeByRefType();
- }
- }
-
- return type;
- }
-
- internal static void GetUnitySerializationInfo(SerializationInfo info, RuntimeType type)
- {
- if (type.GetRootElementType().IsGenericParameter)
- {
- type = AddElementTypes(info, type);
- info.SetType(typeof(UnitySerializationHolder));
- info.AddValue("UnityType", GenericParameterTypeUnity);
- info.AddValue("GenericParameterPosition", type.GenericParameterPosition);
- info.AddValue("DeclaringMethod", type.DeclaringMethod, typeof(MethodBase));
- info.AddValue("DeclaringType", type.DeclaringType, typeof(Type));
-
- return;
- }
-
- int unityType = RuntimeTypeUnity;
-
- if (!type.IsGenericTypeDefinition && type.ContainsGenericParameters)
- {
- // Partial instantiation
- unityType = PartialInstantiationTypeUnity;
- type = AddElementTypes(info, type);
- info.AddValue("GenericArguments", type.GetGenericArguments(), typeof(Type[]));
- type = (RuntimeType)type.GetGenericTypeDefinition();
- }
-
- GetUnitySerializationInfo(info, unityType, type.FullName, type.GetRuntimeAssembly());
- }
-
- internal static void GetUnitySerializationInfo(
- SerializationInfo info, int unityType, String data, RuntimeAssembly assembly)
- {
- // 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.)
-
- info.SetType(typeof(UnitySerializationHolder));
- info.AddValue("Data", data, typeof(String));
- info.AddValue("UnityType", unityType);
-
- String assemName;
-
- if (assembly == null)
- {
- assemName = String.Empty;
- }
- else
- {
- assemName = assembly.FullName;
- }
-
- info.AddValue("AssemblyName", assemName);
- }
- #endregion
-
- #region Private Data Members
- private Type[] m_instantiation;
- private int[] m_elementTypes;
- private int m_genericParameterPosition;
- private Type m_declaringType;
- private MethodBase m_declaringMethod;
- private String m_data;
- private String m_assemblyName;
- private int m_unityType;
- #endregion
-
- #region Constructor
- internal UnitySerializationHolder(SerializationInfo info, StreamingContext context)
- {
- if (info == null)
- throw new ArgumentNullException(nameof(info));
- Contract.EndContractBlock();
-
- m_unityType = info.GetInt32("UnityType");
-
- if (m_unityType == MissingUnity)
- return;
-
- if (m_unityType == GenericParameterTypeUnity)
- {
- m_declaringMethod = info.GetValue("DeclaringMethod", typeof(MethodBase)) as MethodBase;
- m_declaringType = info.GetValue("DeclaringType", typeof(Type)) as Type;
- m_genericParameterPosition = info.GetInt32("GenericParameterPosition");
- m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
-
- return;
- }
-
- if (m_unityType == PartialInstantiationTypeUnity)
- {
- m_instantiation = info.GetValue("GenericArguments", typeof(Type[])) as Type[];
- m_elementTypes = info.GetValue("ElementTypes", typeof(int[])) as int[];
- }
-
- m_data = info.GetString("Data");
- m_assemblyName = info.GetString("AssemblyName");
- }
- #endregion
-
- #region Private Methods
- private void ThrowInsufficientInformation(string field)
- {
- throw new SerializationException(
- Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
- }
- #endregion
-
- #region ISerializable
- public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnitySerHolder"));
- }
- #endregion
-
- #region IObjectReference
- public virtual Object GetRealObject(StreamingContext context)
- {
- // GetRealObject uses the data we have in m_data and m_unityType to do a lookup on the correct
- // object to return. We have specific code here to handle the different types which we support.
- // The reflection types (Assembly, Module, and Type) have to be looked up through their static
- // accessors by name.
-
- Assembly assembly;
-
- switch (m_unityType)
- {
- case EmptyUnity:
- {
- return Empty.Value;
- }
-
- case NullUnity:
- {
- return DBNull.Value;
- }
-
- case MissingUnity:
- {
- return Missing.Value;
- }
-
- case PartialInstantiationTypeUnity:
- {
- m_unityType = RuntimeTypeUnity;
- Type definition = GetRealObject(context) as Type;
- m_unityType = PartialInstantiationTypeUnity;
-
- if (m_instantiation[0] == null)
- return null;
-
- return MakeElementTypes(definition.MakeGenericType(m_instantiation));
- }
-
- case GenericParameterTypeUnity:
- {
- if (m_declaringMethod == null && m_declaringType == null)
- ThrowInsufficientInformation("DeclaringMember");
-
- if (m_declaringMethod != null)
- return m_declaringMethod.GetGenericArguments()[m_genericParameterPosition];
-
- return MakeElementTypes(m_declaringType.GetGenericArguments()[m_genericParameterPosition]);
- }
-
- case RuntimeTypeUnity:
- {
- if (m_data == null || m_data.Length == 0)
- ThrowInsufficientInformation("Data");
-
- if (m_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
-
- if (m_assemblyName.Length == 0)
- return Type.GetType(m_data, true, false);
-
- assembly = Assembly.Load(m_assemblyName);
-
- Type t = assembly.GetType(m_data, true, false);
-
- return t;
- }
-
- case ModuleUnity:
- {
- if (m_data == null || m_data.Length == 0)
- ThrowInsufficientInformation("Data");
-
- if (m_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
-
- assembly = Assembly.Load(m_assemblyName);
-
- Module namedModule = assembly.GetModule(m_data);
-
- if (namedModule == null)
- throw new SerializationException(
- Environment.GetResourceString("Serialization_UnableToFindModule", m_data, m_assemblyName));
-
- return namedModule;
- }
-
- case AssemblyUnity:
- {
- if (m_data == null || m_data.Length == 0)
- ThrowInsufficientInformation("Data");
-
- if (m_assemblyName == null)
- ThrowInsufficientInformation("AssemblyName");
-
- assembly = Assembly.Load(m_assemblyName);
-
- return assembly;
- }
-
- default:
- throw new ArgumentException(Environment.GetResourceString("Argument_InvalidUnity"));
- }
- }
- #endregion
- }
-
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/mscorlib/src/System/ValueTuple.cs b/src/mscorlib/src/System/ValueTuple.cs
deleted file mode 100644
index 0f0863a2ed..0000000000
--- a/src/mscorlib/src/System/ValueTuple.cs
+++ /dev/null
@@ -1,2324 +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.Collections;
-using System.Collections.Generic;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-using System.Runtime.CompilerServices;
-using HashHelpers = System.Numerics.Hashing.HashHelpers;
-
-namespace System
-{
- /// <summary>
- /// Helper so we can call some tuple methods recursively without knowing the underlying types.
- /// </summary>
- internal interface IValueTupleInternal : ITuple
- {
- int GetHashCode(IEqualityComparer comparer);
- string ToStringEnd();
- }
-
- /// <summary>
- /// The ValueTuple types (from arity 0 to 8) comprise the runtime implementation that underlies tuples in C# and struct tuples in F#.
- /// Aside from created via language syntax, they are most easily created via the ValueTuple.Create factory methods.
- /// The System.ValueTuple types differ from the System.Tuple types in that:
- /// - they are structs rather than classes,
- /// - they are mutable rather than readonly, and
- /// - their members (such as Item1, Item2, etc) are fields rather than properties.
- /// </summary>
- [Serializable]
- public struct ValueTuple
- : IEquatable<ValueTuple>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="ValueTuple"/>.</returns>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple;
- }
-
- /// <summary>Returns a value indicating whether this instance is equal to a specified value.</summary>
- /// <param name="other">An instance to compare to this instance.</param>
- /// <returns>true if <paramref name="other"/> has the same value as this instance; otherwise, false.</returns>
- public bool Equals(ValueTuple other)
- {
- return true;
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- return other is ValueTuple;
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return 0;
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple other)
- {
- return 0;
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return 0;
- }
-
- /// <summary>Returns the hash code for this instance.</summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return 0;
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return 0;
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return 0;
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>()</c>.
- /// </remarks>
- public override string ToString()
- {
- return "()";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 0;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- throw new IndexOutOfRangeException();
- }
- }
-
- /// <summary>Creates a new struct 0-tuple.</summary>
- /// <returns>A 0-tuple.</returns>
- public static ValueTuple Create() =>
- new ValueTuple();
-
- /// <summary>Creates a new struct 1-tuple, or singleton.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <returns>A 1-tuple (singleton) whose value is (item1).</returns>
- public static ValueTuple<T1> Create<T1>(T1 item1) =>
- new ValueTuple<T1>(item1);
-
- /// <summary>Creates a new struct 2-tuple, or pair.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <returns>A 2-tuple (pair) whose value is (item1, item2).</returns>
- public static ValueTuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) =>
- new ValueTuple<T1, T2>(item1, item2);
-
- /// <summary>Creates a new struct 3-tuple, or triple.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <param name="item3">The value of the third component of the tuple.</param>
- /// <returns>A 3-tuple (triple) whose value is (item1, item2, item3).</returns>
- public static ValueTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3) =>
- new ValueTuple<T1, T2, T3>(item1, item2, item3);
-
- /// <summary>Creates a new struct 4-tuple, or quadruple.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
- /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <param name="item3">The value of the third component of the tuple.</param>
- /// <param name="item4">The value of the fourth component of the tuple.</param>
- /// <returns>A 4-tuple (quadruple) whose value is (item1, item2, item3, item4).</returns>
- public static ValueTuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4) =>
- new ValueTuple<T1, T2, T3, T4>(item1, item2, item3, item4);
-
- /// <summary>Creates a new struct 5-tuple, or quintuple.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
- /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
- /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <param name="item3">The value of the third component of the tuple.</param>
- /// <param name="item4">The value of the fourth component of the tuple.</param>
- /// <param name="item5">The value of the fifth component of the tuple.</param>
- /// <returns>A 5-tuple (quintuple) whose value is (item1, item2, item3, item4, item5).</returns>
- public static ValueTuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) =>
- new ValueTuple<T1, T2, T3, T4, T5>(item1, item2, item3, item4, item5);
-
- /// <summary>Creates a new struct 6-tuple, or sextuple.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
- /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
- /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
- /// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <param name="item3">The value of the third component of the tuple.</param>
- /// <param name="item4">The value of the fourth component of the tuple.</param>
- /// <param name="item5">The value of the fifth component of the tuple.</param>
- /// <param name="item6">The value of the sixth component of the tuple.</param>
- /// <returns>A 6-tuple (sextuple) whose value is (item1, item2, item3, item4, item5, item6).</returns>
- public static ValueTuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) =>
- new ValueTuple<T1, T2, T3, T4, T5, T6>(item1, item2, item3, item4, item5, item6);
-
- /// <summary>Creates a new struct 7-tuple, or septuple.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
- /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
- /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
- /// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
- /// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <param name="item3">The value of the third component of the tuple.</param>
- /// <param name="item4">The value of the fourth component of the tuple.</param>
- /// <param name="item5">The value of the fifth component of the tuple.</param>
- /// <param name="item6">The value of the sixth component of the tuple.</param>
- /// <param name="item7">The value of the seventh component of the tuple.</param>
- /// <returns>A 7-tuple (septuple) whose value is (item1, item2, item3, item4, item5, item6, item7).</returns>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) =>
- new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(item1, item2, item3, item4, item5, item6, item7);
-
- /// <summary>Creates a new struct 8-tuple, or octuple.</summary>
- /// <typeparam name="T1">The type of the first component of the tuple.</typeparam>
- /// <typeparam name="T2">The type of the second component of the tuple.</typeparam>
- /// <typeparam name="T3">The type of the third component of the tuple.</typeparam>
- /// <typeparam name="T4">The type of the fourth component of the tuple.</typeparam>
- /// <typeparam name="T5">The type of the fifth component of the tuple.</typeparam>
- /// <typeparam name="T6">The type of the sixth component of the tuple.</typeparam>
- /// <typeparam name="T7">The type of the seventh component of the tuple.</typeparam>
- /// <typeparam name="T8">The type of the eighth component of the tuple.</typeparam>
- /// <param name="item1">The value of the first component of the tuple.</param>
- /// <param name="item2">The value of the second component of the tuple.</param>
- /// <param name="item3">The value of the third component of the tuple.</param>
- /// <param name="item4">The value of the fourth component of the tuple.</param>
- /// <param name="item5">The value of the fifth component of the tuple.</param>
- /// <param name="item6">The value of the sixth component of the tuple.</param>
- /// <param name="item7">The value of the seventh component of the tuple.</param>
- /// <param name="item8">The value of the eighth component of the tuple.</param>
- /// <returns>An 8-tuple (octuple) whose value is (item1, item2, item3, item4, item5, item6, item7, item8).</returns>
- public static ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) =>
- new ValueTuple<T1, T2, T3, T4, T5, T6, T7, ValueTuple<T8>>(item1, item2, item3, item4, item5, item6, item7, ValueTuple.Create(item8));
-
- internal static int CombineHashCodes(int h1, int h2)
- {
- return HashHelpers.Combine(HashHelpers.Combine(HashHelpers.RandomSeed, h1), h2);
- }
-
- internal static int CombineHashCodes(int h1, int h2, int h3)
- {
- return HashHelpers.Combine(CombineHashCodes(h1, h2), h3);
- }
-
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4)
- {
- return HashHelpers.Combine(CombineHashCodes(h1, h2, h3), h4);
- }
-
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5)
- {
- return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4), h5);
- }
-
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6)
- {
- return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5), h6);
- }
-
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7)
- {
- return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6), h7);
- }
-
- internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8)
- {
- return HashHelpers.Combine(CombineHashCodes(h1, h2, h3, h4, h5, h6, h7), h8);
- }
- }
-
- /// <summary>Represents a 1-tuple, or singleton, as a value type.</summary>
- /// <typeparam name="T1">The type of the tuple's only component.</typeparam>
- [Serializable]
- public struct ValueTuple<T1>
- : IEquatable<ValueTuple<T1>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1}"/> instance's first component.
- /// </summary>
- public T1 Item1;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- public ValueTuple(T1 item1)
- {
- Item1 = item1;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1> && Equals((ValueTuple<T1>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its field
- /// is equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1>)) return false;
-
- var objTuple = (ValueTuple<T1>)other;
-
- return comparer.Equals(Item1, objTuple.Item1);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1>)other;
-
- return Comparer<T1>.Default.Compare(Item1, objTuple.Item1);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1> other)
- {
- return Comparer<T1>.Default.Compare(Item1, other.Item1);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1>)other;
-
- return comparer.Compare(Item1, objTuple.Item1);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return Item1?.GetHashCode() ?? 0;
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return comparer.GetHashCode(Item1);
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return comparer.GetHashCode(Item1);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1)</c>,
- /// where <c>Item1</c> represents the value of <see cref="Item1"/>. If the field is <see langword="null"/>,
- /// it is represented as <see cref="string.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 1;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- if (index != 0)
- {
- throw new IndexOutOfRangeException();
- }
- return Item1;
- }
- }
- }
-
- /// <summary>
- /// Represents a 2-tuple, or pair, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2>
- : IEquatable<ValueTuple<T1, T2>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
- /// </summary>
- public T1 Item1;
-
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2}"/> instance's first component.
- /// </summary>
- public T2 Item2;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- public ValueTuple(T1 item1, T2 item2)
- {
- Item1 = item1;
- Item2 = item2;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- ///
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2> && Equals((ValueTuple<T1, T2>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified <see cref="ValueTuple{T1, T2}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2}"/> instance is equal to a specified object based on a specified comparison method.
- /// </summary>
- /// <param name="other">The object to compare with this instance.</param>
- /// <param name="comparer">An object that defines the method to use to evaluate whether the two objects are equal.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- ///
- /// <remarks>
- /// This member is an explicit interface member implementation. It can be used only when the
- /// <see cref="ValueTuple{T1, T2}"/> instance is cast to an <see cref="IStructuralEquatable"/> interface.
- ///
- /// The <see cref="IEqualityComparer.Equals"/> implementation is called only if <c>other</c> is not <see langword="null"/>,
- /// and if it can be successfully cast (in C#) or converted (in Visual Basic) to a <see cref="ValueTuple{T1, T2}"/>
- /// whose components are of the same types as those of the current instance. The IStructuralEquatable.Equals(Object, IEqualityComparer) method
- /// first passes the <see cref="Item1"/> values of the <see cref="ValueTuple{T1, T2}"/> objects to be compared to the
- /// <see cref="IEqualityComparer.Equals"/> implementation. If this method call returns <see langword="true"/>, the method is
- /// called again and passed the <see cref="Item2"/> values of the two <see cref="ValueTuple{T1, T2}"/> instances.
- /// </remarks>
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2>)) return false;
-
- var objTuple = (ValueTuple<T1, T2>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- return Comparer<T2>.Default.Compare(Item2, other.Item2);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- return comparer.Compare(Item2, objTuple.Item2);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0);
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
- comparer.GetHashCode(Item2));
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2)</c>,
- /// where <c>Item1</c> and <c>Item2</c> represent the values of the <see cref="Item1"/>
- /// and <see cref="Item2"/> fields. If either field value is <see langword="null"/>,
- /// it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 2;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- default:
- throw new IndexOutOfRangeException();
- }
- }
- }
- }
-
- /// <summary>
- /// Represents a 3-tuple, or triple, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2, T3>
- : IEquatable<ValueTuple<T1, T2, T3>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's first component.
- /// </summary>
- public T1 Item1;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's second component.
- /// </summary>
- public T2 Item2;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3}"/> instance's third component.
- /// </summary>
- public T3 Item3;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- /// <param name="item3">The value of the tuple's third component.</param>
- public ValueTuple(T1 item1, T2 item2, T3 item3)
- {
- Item1 = item1;
- Item2 = item2;
- Item3 = item3;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2, T3> && Equals((ValueTuple<T1, T2, T3>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2, T3> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
- && EqualityComparer<T3>.Default.Equals(Item3, other.Item3);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2, T3>)) return false;
-
- var objTuple = (ValueTuple<T1, T2, T3>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2)
- && comparer.Equals(Item3, objTuple.Item3);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2, T3>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2, T3> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- c = Comparer<T2>.Default.Compare(Item2, other.Item2);
- if (c != 0) return c;
-
- return Comparer<T3>.Default.Compare(Item3, other.Item3);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2, T3>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- c = comparer.Compare(Item2, objTuple.Item2);
- if (c != 0) return c;
-
- return comparer.Compare(Item3, objTuple.Item3);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0);
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
- comparer.GetHashCode(Item2),
- comparer.GetHashCode(Item3));
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2, Item3)</c>.
- /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 3;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- case 2:
- return Item3;
- default:
- throw new IndexOutOfRangeException();
- }
- }
- }
- }
-
- /// <summary>
- /// Represents a 4-tuple, or quadruple, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
- /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2, T3, T4>
- : IEquatable<ValueTuple<T1, T2, T3, T4>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's first component.
- /// </summary>
- public T1 Item1;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's second component.
- /// </summary>
- public T2 Item2;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's third component.
- /// </summary>
- public T3 Item3;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance's fourth component.
- /// </summary>
- public T4 Item4;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- /// <param name="item3">The value of the tuple's third component.</param>
- /// <param name="item4">The value of the tuple's fourth component.</param>
- public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4)
- {
- Item1 = item1;
- Item2 = item2;
- Item3 = item3;
- Item4 = item4;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2, T3, T4> && Equals((ValueTuple<T1, T2, T3, T4>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2, T3, T4> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
- && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
- && EqualityComparer<T4>.Default.Equals(Item4, other.Item4);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2, T3, T4>)) return false;
-
- var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2)
- && comparer.Equals(Item3, objTuple.Item3)
- && comparer.Equals(Item4, objTuple.Item4);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2, T3, T4>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2, T3, T4> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- c = Comparer<T2>.Default.Compare(Item2, other.Item2);
- if (c != 0) return c;
-
- c = Comparer<T3>.Default.Compare(Item3, other.Item3);
- if (c != 0) return c;
-
- return Comparer<T4>.Default.Compare(Item4, other.Item4);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2, T3, T4>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- c = comparer.Compare(Item2, objTuple.Item2);
- if (c != 0) return c;
-
- c = comparer.Compare(Item3, objTuple.Item3);
- if (c != 0) return c;
-
- return comparer.Compare(Item4, objTuple.Item4);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0);
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
- comparer.GetHashCode(Item2),
- comparer.GetHashCode(Item3),
- comparer.GetHashCode(Item4));
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4)</c>.
- /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 4;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- case 2:
- return Item3;
- case 3:
- return Item4;
- default:
- throw new IndexOutOfRangeException();
- }
- }
- }
- }
-
- /// <summary>
- /// Represents a 5-tuple, or quintuple, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
- /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
- /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2, T3, T4, T5>
- : IEquatable<ValueTuple<T1, T2, T3, T4, T5>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's first component.
- /// </summary>
- public T1 Item1;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's second component.
- /// </summary>
- public T2 Item2;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's third component.
- /// </summary>
- public T3 Item3;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fourth component.
- /// </summary>
- public T4 Item4;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance's fifth component.
- /// </summary>
- public T5 Item5;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- /// <param name="item3">The value of the tuple's third component.</param>
- /// <param name="item4">The value of the tuple's fourth component.</param>
- /// <param name="item5">The value of the tuple's fifth component.</param>
- public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5)
- {
- Item1 = item1;
- Item2 = item2;
- Item3 = item3;
- Item4 = item4;
- Item5 = item5;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2, T3, T4, T5> && Equals((ValueTuple<T1, T2, T3, T4, T5>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2, T3, T4, T5> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
- && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
- && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
- && EqualityComparer<T5>.Default.Equals(Item5, other.Item5);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5>)) return false;
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2)
- && comparer.Equals(Item3, objTuple.Item3)
- && comparer.Equals(Item4, objTuple.Item4)
- && comparer.Equals(Item5, objTuple.Item5);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2, T3, T4, T5>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2, T3, T4, T5> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- c = Comparer<T2>.Default.Compare(Item2, other.Item2);
- if (c != 0) return c;
-
- c = Comparer<T3>.Default.Compare(Item3, other.Item3);
- if (c != 0) return c;
-
- c = Comparer<T4>.Default.Compare(Item4, other.Item4);
- if (c != 0) return c;
-
- return Comparer<T5>.Default.Compare(Item5, other.Item5);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- c = comparer.Compare(Item2, objTuple.Item2);
- if (c != 0) return c;
-
- c = comparer.Compare(Item3, objTuple.Item3);
- if (c != 0) return c;
-
- c = comparer.Compare(Item4, objTuple.Item4);
- if (c != 0) return c;
-
- return comparer.Compare(Item5, objTuple.Item5);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0);
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
- comparer.GetHashCode(Item2),
- comparer.GetHashCode(Item3),
- comparer.GetHashCode(Item4),
- comparer.GetHashCode(Item5));
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5)</c>.
- /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 5;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- case 2:
- return Item3;
- case 3:
- return Item4;
- case 4:
- return Item5;
- default:
- throw new IndexOutOfRangeException();
- }
- }
- }
- }
-
- /// <summary>
- /// Represents a 6-tuple, or sixtuple, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
- /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
- /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
- /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2, T3, T4, T5, T6>
- : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's first component.
- /// </summary>
- public T1 Item1;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's second component.
- /// </summary>
- public T2 Item2;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's third component.
- /// </summary>
- public T3 Item3;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fourth component.
- /// </summary>
- public T4 Item4;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's fifth component.
- /// </summary>
- public T5 Item5;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance's sixth component.
- /// </summary>
- public T6 Item6;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- /// <param name="item3">The value of the tuple's third component.</param>
- /// <param name="item4">The value of the tuple's fourth component.</param>
- /// <param name="item5">The value of the tuple's fifth component.</param>
- /// <param name="item6">The value of the tuple's sixth component.</param>
- public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6)
- {
- Item1 = item1;
- Item2 = item2;
- Item3 = item3;
- Item4 = item4;
- Item5 = item5;
- Item6 = item6;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2, T3, T4, T5, T6> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
- && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
- && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
- && EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
- && EqualityComparer<T6>.Default.Equals(Item6, other.Item6);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6>)) return false;
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2)
- && comparer.Equals(Item3, objTuple.Item3)
- && comparer.Equals(Item4, objTuple.Item4)
- && comparer.Equals(Item5, objTuple.Item5)
- && comparer.Equals(Item6, objTuple.Item6);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- c = Comparer<T2>.Default.Compare(Item2, other.Item2);
- if (c != 0) return c;
-
- c = Comparer<T3>.Default.Compare(Item3, other.Item3);
- if (c != 0) return c;
-
- c = Comparer<T4>.Default.Compare(Item4, other.Item4);
- if (c != 0) return c;
-
- c = Comparer<T5>.Default.Compare(Item5, other.Item5);
- if (c != 0) return c;
-
- return Comparer<T6>.Default.Compare(Item6, other.Item6);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- c = comparer.Compare(Item2, objTuple.Item2);
- if (c != 0) return c;
-
- c = comparer.Compare(Item3, objTuple.Item3);
- if (c != 0) return c;
-
- c = comparer.Compare(Item4, objTuple.Item4);
- if (c != 0) return c;
-
- c = comparer.Compare(Item5, objTuple.Item5);
- if (c != 0) return c;
-
- return comparer.Compare(Item6, objTuple.Item6);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0);
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
- comparer.GetHashCode(Item2),
- comparer.GetHashCode(Item3),
- comparer.GetHashCode(Item4),
- comparer.GetHashCode(Item5),
- comparer.GetHashCode(Item6));
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6)</c>.
- /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 6;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- case 2:
- return Item3;
- case 3:
- return Item4;
- case 4:
- return Item5;
- case 5:
- return Item6;
- default:
- throw new IndexOutOfRangeException();
- }
- }
- }
- }
-
- /// <summary>
- /// Represents a 7-tuple, or sentuple, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
- /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
- /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
- /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
- /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7>
- : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>, IValueTupleInternal, ITuple
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's first component.
- /// </summary>
- public T1 Item1;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's second component.
- /// </summary>
- public T2 Item2;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's third component.
- /// </summary>
- public T3 Item3;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fourth component.
- /// </summary>
- public T4 Item4;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's fifth component.
- /// </summary>
- public T5 Item5;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's sixth component.
- /// </summary>
- public T6 Item6;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance's seventh component.
- /// </summary>
- public T7 Item7;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- /// <param name="item3">The value of the tuple's third component.</param>
- /// <param name="item4">The value of the tuple's fourth component.</param>
- /// <param name="item5">The value of the tuple's fifth component.</param>
- /// <param name="item6">The value of the tuple's sixth component.</param>
- /// <param name="item7">The value of the tuple's seventh component.</param>
- public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7)
- {
- Item1 = item1;
- Item2 = item2;
- Item3 = item3;
- Item4 = item4;
- Item5 = item5;
- Item6 = item6;
- Item7 = item7;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
- && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
- && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
- && EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
- && EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
- && EqualityComparer<T7>.Default.Equals(Item7, other.Item7);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>)) return false;
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2)
- && comparer.Equals(Item3, objTuple.Item3)
- && comparer.Equals(Item4, objTuple.Item4)
- && comparer.Equals(Item5, objTuple.Item5)
- && comparer.Equals(Item6, objTuple.Item6)
- && comparer.Equals(Item7, objTuple.Item7);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- c = Comparer<T2>.Default.Compare(Item2, other.Item2);
- if (c != 0) return c;
-
- c = Comparer<T3>.Default.Compare(Item3, other.Item3);
- if (c != 0) return c;
-
- c = Comparer<T4>.Default.Compare(Item4, other.Item4);
- if (c != 0) return c;
-
- c = Comparer<T5>.Default.Compare(Item5, other.Item5);
- if (c != 0) return c;
-
- c = Comparer<T6>.Default.Compare(Item6, other.Item6);
- if (c != 0) return c;
-
- return Comparer<T7>.Default.Compare(Item7, other.Item7);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- c = comparer.Compare(Item2, objTuple.Item2);
- if (c != 0) return c;
-
- c = comparer.Compare(Item3, objTuple.Item3);
- if (c != 0) return c;
-
- c = comparer.Compare(Item4, objTuple.Item4);
- if (c != 0) return c;
-
- c = comparer.Compare(Item5, objTuple.Item5);
- if (c != 0) return c;
-
- c = comparer.Compare(Item6, objTuple.Item6);
- if (c != 0) return c;
-
- return comparer.Compare(Item7, objTuple.Item7);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0);
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1),
- comparer.GetHashCode(Item2),
- comparer.GetHashCode(Item3),
- comparer.GetHashCode(Item4),
- comparer.GetHashCode(Item5),
- comparer.GetHashCode(Item6),
- comparer.GetHashCode(Item7));
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7)</c>.
- /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")";
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length => 7;
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- case 2:
- return Item3;
- case 3:
- return Item4;
- case 4:
- return Item5;
- case 5:
- return Item6;
- case 6:
- return Item7;
- default:
- throw new IndexOutOfRangeException();
- }
- }
- }
- }
-
- /// <summary>
- /// Represents an 8-tuple, or octuple, as a value type.
- /// </summary>
- /// <typeparam name="T1">The type of the tuple's first component.</typeparam>
- /// <typeparam name="T2">The type of the tuple's second component.</typeparam>
- /// <typeparam name="T3">The type of the tuple's third component.</typeparam>
- /// <typeparam name="T4">The type of the tuple's fourth component.</typeparam>
- /// <typeparam name="T5">The type of the tuple's fifth component.</typeparam>
- /// <typeparam name="T6">The type of the tuple's sixth component.</typeparam>
- /// <typeparam name="T7">The type of the tuple's seventh component.</typeparam>
- /// <typeparam name="TRest">The type of the tuple's eighth component.</typeparam>
- [Serializable]
- [StructLayout(LayoutKind.Auto)]
- public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>
- : IEquatable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>, IValueTupleInternal, ITuple
- where TRest : struct
- {
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's first component.
- /// </summary>
- public T1 Item1;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's second component.
- /// </summary>
- public T2 Item2;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's third component.
- /// </summary>
- public T3 Item3;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fourth component.
- /// </summary>
- public T4 Item4;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's fifth component.
- /// </summary>
- public T5 Item5;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's sixth component.
- /// </summary>
- public T6 Item6;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's seventh component.
- /// </summary>
- public T7 Item7;
- /// <summary>
- /// The current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance's eighth component.
- /// </summary>
- public TRest Rest;
-
- /// <summary>
- /// Initializes a new instance of the <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.
- /// </summary>
- /// <param name="item1">The value of the tuple's first component.</param>
- /// <param name="item2">The value of the tuple's second component.</param>
- /// <param name="item3">The value of the tuple's third component.</param>
- /// <param name="item4">The value of the tuple's fourth component.</param>
- /// <param name="item5">The value of the tuple's fifth component.</param>
- /// <param name="item6">The value of the tuple's sixth component.</param>
- /// <param name="item7">The value of the tuple's seventh component.</param>
- /// <param name="rest">The value of the tuple's eight component.</param>
- public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest)
- {
- if (!(rest is IValueTupleInternal))
- {
- throw new ArgumentException(SR.ArgumentException_ValueTupleLastArgumentNotATuple);
- }
-
- Item1 = item1;
- Item2 = item2;
- Item3 = item3;
- Item4 = item4;
- Item5 = item5;
- Item6 = item6;
- Item7 = item7;
- Rest = rest;
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance is equal to a specified object.
- /// </summary>
- /// <param name="obj">The object to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified object; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="obj"/> parameter is considered to be equal to the current instance under the following conditions:
- /// <list type="bullet">
- /// <item><description>It is a <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> value type.</description></item>
- /// <item><description>Its components are of the same types as those of the current instance.</description></item>
- /// <item><description>Its components are equal to those of the current instance. Equality is determined by the default object equality comparer for each component.</description></item>
- /// </list>
- /// </remarks>
- public override bool Equals(object obj)
- {
- return obj is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> && Equals((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)obj);
- }
-
- /// <summary>
- /// Returns a value that indicates whether the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>
- /// instance is equal to a specified <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/>.
- /// </summary>
- /// <param name="other">The tuple to compare with this instance.</param>
- /// <returns><see langword="true"/> if the current instance is equal to the specified tuple; otherwise, <see langword="false"/>.</returns>
- /// <remarks>
- /// The <paramref name="other"/> parameter is considered to be equal to the current instance if each of its fields
- /// are equal to that of the current instance, using the default comparer for that field's type.
- /// </remarks>
- public bool Equals(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
- {
- return EqualityComparer<T1>.Default.Equals(Item1, other.Item1)
- && EqualityComparer<T2>.Default.Equals(Item2, other.Item2)
- && EqualityComparer<T3>.Default.Equals(Item3, other.Item3)
- && EqualityComparer<T4>.Default.Equals(Item4, other.Item4)
- && EqualityComparer<T5>.Default.Equals(Item5, other.Item5)
- && EqualityComparer<T6>.Default.Equals(Item6, other.Item6)
- && EqualityComparer<T7>.Default.Equals(Item7, other.Item7)
- && EqualityComparer<TRest>.Default.Equals(Rest, other.Rest);
- }
-
- bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer)
- {
- if (other == null || !(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)) return false;
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
-
- return comparer.Equals(Item1, objTuple.Item1)
- && comparer.Equals(Item2, objTuple.Item2)
- && comparer.Equals(Item3, objTuple.Item3)
- && comparer.Equals(Item4, objTuple.Item4)
- && comparer.Equals(Item5, objTuple.Item5)
- && comparer.Equals(Item6, objTuple.Item6)
- && comparer.Equals(Item7, objTuple.Item7)
- && comparer.Equals(Rest, objTuple.Rest);
- }
-
- int IComparable.CompareTo(object other)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- return CompareTo((ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other);
- }
-
- /// <summary>Compares this instance to a specified instance and returns an indication of their relative values.</summary>
- /// <param name="other">An instance to compare.</param>
- /// <returns>
- /// A signed number indicating the relative values of this instance and <paramref name="other"/>.
- /// Returns less than zero if this instance is less than <paramref name="other"/>, zero if this
- /// instance is equal to <paramref name="other"/>, and greater than zero if this instance is greater
- /// than <paramref name="other"/>.
- /// </returns>
- public int CompareTo(ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> other)
- {
- int c = Comparer<T1>.Default.Compare(Item1, other.Item1);
- if (c != 0) return c;
-
- c = Comparer<T2>.Default.Compare(Item2, other.Item2);
- if (c != 0) return c;
-
- c = Comparer<T3>.Default.Compare(Item3, other.Item3);
- if (c != 0) return c;
-
- c = Comparer<T4>.Default.Compare(Item4, other.Item4);
- if (c != 0) return c;
-
- c = Comparer<T5>.Default.Compare(Item5, other.Item5);
- if (c != 0) return c;
-
- c = Comparer<T6>.Default.Compare(Item6, other.Item6);
- if (c != 0) return c;
-
- c = Comparer<T7>.Default.Compare(Item7, other.Item7);
- if (c != 0) return c;
-
- return Comparer<TRest>.Default.Compare(Rest, other.Rest);
- }
-
- int IStructuralComparable.CompareTo(object other, IComparer comparer)
- {
- if (other == null) return 1;
-
- if (!(other is ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>))
- {
- throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, this.GetType().ToString()), nameof(other));
- }
-
- var objTuple = (ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>)other;
-
- int c = comparer.Compare(Item1, objTuple.Item1);
- if (c != 0) return c;
-
- c = comparer.Compare(Item2, objTuple.Item2);
- if (c != 0) return c;
-
- c = comparer.Compare(Item3, objTuple.Item3);
- if (c != 0) return c;
-
- c = comparer.Compare(Item4, objTuple.Item4);
- if (c != 0) return c;
-
- c = comparer.Compare(Item5, objTuple.Item5);
- if (c != 0) return c;
-
- c = comparer.Compare(Item6, objTuple.Item6);
- if (c != 0) return c;
-
- c = comparer.Compare(Item7, objTuple.Item7);
- if (c != 0) return c;
-
- return comparer.Compare(Rest, objTuple.Rest);
- }
-
- /// <summary>
- /// Returns the hash code for the current <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
- /// </summary>
- /// <returns>A 32-bit signed integer hash code.</returns>
- public override int GetHashCode()
- {
- // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
- IValueTupleInternal rest = Rest as IValueTupleInternal;
- if (rest == null)
- {
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0);
- }
-
- int size = rest.Length;
- if (size >= 8) { return rest.GetHashCode(); }
-
- // In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
- int k = 8 - size;
- switch (k)
- {
- case 1:
- return ValueTuple.CombineHashCodes(Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- case 2:
- return ValueTuple.CombineHashCodes(Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- case 3:
- return ValueTuple.CombineHashCodes(Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- case 4:
- return ValueTuple.CombineHashCodes(Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- case 5:
- return ValueTuple.CombineHashCodes(Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- case 6:
- return ValueTuple.CombineHashCodes(Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- case 7:
- case 8:
- return ValueTuple.CombineHashCodes(Item1?.GetHashCode() ?? 0,
- Item2?.GetHashCode() ?? 0,
- Item3?.GetHashCode() ?? 0,
- Item4?.GetHashCode() ?? 0,
- Item5?.GetHashCode() ?? 0,
- Item6?.GetHashCode() ?? 0,
- Item7?.GetHashCode() ?? 0,
- rest.GetHashCode());
- }
-
- Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
- return -1;
- }
-
- int IStructuralEquatable.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- private int GetHashCodeCore(IEqualityComparer comparer)
- {
- // We want to have a limited hash in this case. We'll use the last 8 elements of the tuple
- IValueTupleInternal rest = Rest as IValueTupleInternal;
- if (rest == null)
- {
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
- comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
- comparer.GetHashCode(Item7));
- }
-
- int size = rest.Length;
- if (size >= 8) { return rest.GetHashCode(comparer); }
-
- // In this case, the rest member has less than 8 elements so we need to combine some our elements with the elements in rest
- int k = 8 - size;
- switch (k)
- {
- case 1:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
- case 2:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
- case 3:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
- rest.GetHashCode(comparer));
- case 4:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
- comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
- case 5:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5),
- comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
- case 6:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4),
- comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7),
- rest.GetHashCode(comparer));
- case 7:
- case 8:
- return ValueTuple.CombineHashCodes(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3),
- comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6),
- comparer.GetHashCode(Item7), rest.GetHashCode(comparer));
- }
-
- Contract.Assert(false, "Missed all cases for computing ValueTuple hash code");
- return -1;
- }
-
- int IValueTupleInternal.GetHashCode(IEqualityComparer comparer)
- {
- return GetHashCodeCore(comparer);
- }
-
- /// <summary>
- /// Returns a string that represents the value of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.
- /// </summary>
- /// <returns>The string representation of this <see cref="ValueTuple{T1, T2, T3, T4, T5, T6, T7, TRest}"/> instance.</returns>
- /// <remarks>
- /// The string returned by this method takes the form <c>(Item1, Item2, Item3, Item4, Item5, Item6, Item7, Rest)</c>.
- /// If any field value is <see langword="null"/>, it is represented as <see cref="String.Empty"/>.
- /// </remarks>
- public override string ToString()
- {
- IValueTupleInternal rest = Rest as IValueTupleInternal;
- if (rest == null)
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
- }
- else
- {
- return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
- }
- }
-
- string IValueTupleInternal.ToStringEnd()
- {
- IValueTupleInternal rest = Rest as IValueTupleInternal;
- if (rest == null)
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + Rest.ToString() + ")";
- }
- else
- {
- return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ", " + rest.ToStringEnd();
- }
- }
-
- /// <summary>
- /// The number of positions in this data structure.
- /// </summary>
- int ITuple.Length
- {
- get
- {
- IValueTupleInternal rest = Rest as IValueTupleInternal;
- return rest == null ? 8 : 7 + rest.Length;
- }
- }
-
- /// <summary>
- /// Get the element at position <param name="index"/>.
- /// </summary>
- object ITuple.this[int index]
- {
- get
- {
- switch (index)
- {
- case 0:
- return Item1;
- case 1:
- return Item2;
- case 2:
- return Item3;
- case 3:
- return Item4;
- case 4:
- return Item5;
- case 5:
- return Item6;
- case 6:
- return Item7;
- }
-
- IValueTupleInternal rest = Rest as IValueTupleInternal;
- if (rest == null)
- {
- if (index == 7)
- {
- return Rest;
- }
- throw new IndexOutOfRangeException();
- }
- return rest[index - 7];
- }
- }
- }
-}
diff --git a/src/mscorlib/src/System/ValueType.cs b/src/mscorlib/src/System/ValueType.cs
index 06a64e397c..0cd08bd26f 100644
--- a/src/mscorlib/src/System/ValueType.cs
+++ b/src/mscorlib/src/System/ValueType.cs
@@ -10,24 +10,29 @@
**
**
===========================================================*/
-namespace System {
- using System;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- [Serializable]
- public abstract class ValueType {
+using System;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
- public override bool Equals (Object obj) {
- BCLDebug.Perf(false, "ValueType::Equals is not fast. "+this.GetType().FullName+" should override Equals(Object)");
- if (null==obj) {
+namespace System
+{
+ [Serializable]
+ public abstract class ValueType
+ {
+ public override bool Equals(Object obj)
+ {
+ BCLDebug.Perf(false, "ValueType::Equals is not fast. " + this.GetType().FullName + " should override Equals(Object)");
+ if (null == obj)
+ {
return false;
}
RuntimeType thisType = (RuntimeType)this.GetType();
RuntimeType thatType = (RuntimeType)obj.GetType();
- if (thatType!=thisType) {
+ if (thatType != thisType)
+ {
return false;
}
@@ -41,16 +46,19 @@ namespace System {
FieldInfo[] thisFields = thisType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
- for (int i=0; i<thisFields.Length; i++) {
+ for (int i = 0; i < thisFields.Length; i++)
+ {
thisResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(thisObj);
thatResult = ((RtFieldInfo)thisFields[i]).UnsafeGetValue(obj);
-
- if (thisResult == null) {
+
+ if (thisResult == null)
+ {
if (thatResult != null)
return false;
}
else
- if (!thisResult.Equals(thatResult)) {
+ if (!thisResult.Equals(thatResult))
+ {
return false;
}
}
diff --git a/src/mscorlib/src/System/Variant.cs b/src/mscorlib/src/System/Variant.cs
index 509650b8fc..cae5bdade4 100644
--- a/src/mscorlib/src/System/Variant.cs
+++ b/src/mscorlib/src/System/Variant.cs
@@ -10,22 +10,23 @@
**
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Reflection;
- using System.Threading;
- using System.Runtime.InteropServices;
- using System.Globalization;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Reflection;
+using System.Threading;
+using System.Runtime.InteropServices;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
- internal struct Variant {
-
+ internal struct Variant
+ {
//Do Not change the order of these fields.
//They are mapped to the native VariantData * data structure.
private Object m_objref;
@@ -45,48 +46,48 @@ namespace System {
// If you update this, update the corresponding stuff in OAVariantLib.cs,
// COMOAVariant.cpp (2 tables, forwards and reverse), and perhaps OleVariant.h
///////////////////////////////////////////////////////////////////////
- internal const int CV_EMPTY=0x0;
- internal const int CV_VOID=0x1;
- internal const int CV_BOOLEAN=0x2;
- internal const int CV_CHAR=0x3;
- internal const int CV_I1=0x4;
- internal const int CV_U1=0x5;
- internal const int CV_I2=0x6;
- internal const int CV_U2=0x7;
- internal const int CV_I4=0x8;
- internal const int CV_U4=0x9;
- internal const int CV_I8=0xa;
- internal const int CV_U8=0xb;
- internal const int CV_R4=0xc;
- internal const int CV_R8=0xd;
- internal const int CV_STRING=0xe;
- internal const int CV_PTR=0xf;
+ internal const int CV_EMPTY = 0x0;
+ internal const int CV_VOID = 0x1;
+ internal const int CV_BOOLEAN = 0x2;
+ internal const int CV_CHAR = 0x3;
+ internal const int CV_I1 = 0x4;
+ internal const int CV_U1 = 0x5;
+ internal const int CV_I2 = 0x6;
+ internal const int CV_U2 = 0x7;
+ internal const int CV_I4 = 0x8;
+ internal const int CV_U4 = 0x9;
+ internal const int CV_I8 = 0xa;
+ internal const int CV_U8 = 0xb;
+ internal const int CV_R4 = 0xc;
+ internal const int CV_R8 = 0xd;
+ internal const int CV_STRING = 0xe;
+ internal const int CV_PTR = 0xf;
internal const int CV_DATETIME = 0x10;
internal const int CV_TIMESPAN = 0x11;
- internal const int CV_OBJECT=0x12;
+ internal const int CV_OBJECT = 0x12;
internal const int CV_DECIMAL = 0x13;
- internal const int CV_ENUM=0x15;
- internal const int CV_MISSING=0x16;
- internal const int CV_NULL=0x17;
- internal const int CV_LAST=0x18;
+ internal const int CV_ENUM = 0x15;
+ internal const int CV_MISSING = 0x16;
+ internal const int CV_NULL = 0x17;
+ internal const int CV_LAST = 0x18;
- internal const int TypeCodeBitMask=0xffff;
- internal const int VTBitMask=unchecked((int)0xff000000);
- internal const int VTBitShift=24;
- internal const int ArrayBitMask =0x10000;
+ internal const int TypeCodeBitMask = 0xffff;
+ internal const int VTBitMask = unchecked((int)0xff000000);
+ internal const int VTBitShift = 24;
+ internal const int ArrayBitMask = 0x10000;
// Enum enum and Mask
- internal const int EnumI1 =0x100000;
- internal const int EnumU1 =0x200000;
- internal const int EnumI2 =0x300000;
- internal const int EnumU2 =0x400000;
- internal const int EnumI4 =0x500000;
- internal const int EnumU4 =0x600000;
- internal const int EnumI8 =0x700000;
- internal const int EnumU8 =0x800000;
- internal const int EnumMask =0xF00000;
-
- internal static readonly Type [] ClassTypes = {
+ internal const int EnumI1 = 0x100000;
+ internal const int EnumU1 = 0x200000;
+ internal const int EnumI2 = 0x300000;
+ internal const int EnumU2 = 0x400000;
+ internal const int EnumI4 = 0x500000;
+ internal const int EnumU4 = 0x600000;
+ internal const int EnumI8 = 0x700000;
+ internal const int EnumU8 = 0x800000;
+ internal const int EnumMask = 0xF00000;
+
+ internal static readonly Type[] ClassTypes = {
typeof(System.Empty),
typeof(void),
typeof(Boolean),
@@ -122,11 +123,11 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern double GetR8FromVar();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern float GetR4FromVar();
+ internal extern float GetR4FromVar();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern void SetFieldsR4(float val);
+ internal extern void SetFieldsR4(float val);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern void SetFieldsR8(double val);
+ internal extern void SetFieldsR8(double val);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern void SetFieldsObject(Object val);
@@ -135,159 +136,181 @@ namespace System {
// Ends up only taking about 1/8 the time of the ECALL version.
internal long GetI8FromVar()
{
- return ((long)m_data2<<32 | ((long)m_data1 & 0xFFFFFFFFL));
+ return ((long)m_data2 << 32 | ((long)m_data1 & 0xFFFFFFFFL));
}
//
// Constructors
//
- internal Variant(int flags, Object or, int data1, int data2) {
+ internal Variant(int flags, Object or, int data1, int data2)
+ {
m_flags = flags;
- m_objref=or;
- m_data1=data1;
- m_data2=data2;
+ m_objref = or;
+ m_data1 = data1;
+ m_data2 = data2;
}
- public Variant(bool val) {
- m_objref= null;
+ public Variant(bool val)
+ {
+ m_objref = null;
m_flags = CV_BOOLEAN;
- m_data1 = (val)?Boolean.True:Boolean.False;
+ m_data1 = (val) ? Boolean.True : Boolean.False;
m_data2 = 0;
}
- public Variant(sbyte val) {
- m_objref=null;
- m_flags=CV_I1;
- m_data1=(int)val;
- m_data2=(int)(((long)val)>>32);
+ public Variant(sbyte val)
+ {
+ m_objref = null;
+ m_flags = CV_I1;
+ m_data1 = (int)val;
+ m_data2 = (int)(((long)val) >> 32);
}
- public Variant(byte val) {
- m_objref=null;
- m_flags=CV_U1;
- m_data1=(int)val;
- m_data2=0;
+ public Variant(byte val)
+ {
+ m_objref = null;
+ m_flags = CV_U1;
+ m_data1 = (int)val;
+ m_data2 = 0;
}
- public Variant(short val) {
- m_objref=null;
- m_flags=CV_I2;
- m_data1=(int)val;
- m_data2=(int)(((long)val)>>32);
+ public Variant(short val)
+ {
+ m_objref = null;
+ m_flags = CV_I2;
+ m_data1 = (int)val;
+ m_data2 = (int)(((long)val) >> 32);
}
- public Variant(ushort val) {
- m_objref=null;
- m_flags=CV_U2;
- m_data1=(int)val;
- m_data2=0;
+ public Variant(ushort val)
+ {
+ m_objref = null;
+ m_flags = CV_U2;
+ m_data1 = (int)val;
+ m_data2 = 0;
}
- public Variant(char val) {
- m_objref=null;
- m_flags=CV_CHAR;
- m_data1=(int)val;
- m_data2=0;
+ public Variant(char val)
+ {
+ m_objref = null;
+ m_flags = CV_CHAR;
+ m_data1 = (int)val;
+ m_data2 = 0;
}
- public Variant(int val) {
- m_objref=null;
- m_flags=CV_I4;
- m_data1=val;
- m_data2=val >> 31;
+ public Variant(int val)
+ {
+ m_objref = null;
+ m_flags = CV_I4;
+ m_data1 = val;
+ m_data2 = val >> 31;
}
- public Variant(uint val) {
- m_objref=null;
- m_flags=CV_U4;
- m_data1=(int)val;
- m_data2=0;
+ public Variant(uint val)
+ {
+ m_objref = null;
+ m_flags = CV_U4;
+ m_data1 = (int)val;
+ m_data2 = 0;
}
- public Variant(long val) {
- m_objref=null;
- m_flags=CV_I8;
+ public Variant(long val)
+ {
+ m_objref = null;
+ m_flags = CV_I8;
m_data1 = (int)val;
m_data2 = (int)(val >> 32);
}
- public Variant(ulong val) {
- m_objref=null;
- m_flags=CV_U8;
+ public Variant(ulong val)
+ {
+ m_objref = null;
+ m_flags = CV_U8;
m_data1 = (int)val;
m_data2 = (int)(val >> 32);
}
- public Variant(float val) {
- m_objref=null;
- m_flags=CV_R4;
- m_data1=0;
- m_data2=0;
+ public Variant(float val)
+ {
+ m_objref = null;
+ m_flags = CV_R4;
+ m_data1 = 0;
+ m_data2 = 0;
SetFieldsR4(val);
}
- public Variant(double val) {
- m_objref=null;
- m_flags=CV_R8;
- m_data1=0;
- m_data2=0;
+ public Variant(double val)
+ {
+ m_objref = null;
+ m_flags = CV_R8;
+ m_data1 = 0;
+ m_data2 = 0;
SetFieldsR8(val);
}
- public Variant(DateTime val) {
- m_objref=null;
- m_flags=CV_DATETIME;
+ public Variant(DateTime val)
+ {
+ m_objref = null;
+ m_flags = CV_DATETIME;
ulong ticks = (ulong)val.Ticks;
m_data1 = (int)ticks;
- m_data2 = (int)(ticks>>32);
+ m_data2 = (int)(ticks >> 32);
}
- public Variant(Decimal val) {
+ public Variant(Decimal val)
+ {
m_objref = (Object)val;
m_flags = CV_DECIMAL;
- m_data1=0;
- m_data2=0;
+ m_data1 = 0;
+ m_data2 = 0;
}
- public Variant(Object obj) {
- m_data1=0;
- m_data2=0;
+ public Variant(Object obj)
+ {
+ m_data1 = 0;
+ m_data2 = 0;
VarEnum vt = VarEnum.VT_EMPTY;
- if (obj is DateTime) {
- m_objref=null;
- m_flags=CV_DATETIME;
+ if (obj is DateTime)
+ {
+ m_objref = null;
+ m_flags = CV_DATETIME;
ulong ticks = (ulong)((DateTime)obj).Ticks;
m_data1 = (int)ticks;
- m_data2 = (int)(ticks>>32);
+ m_data2 = (int)(ticks >> 32);
return;
}
- if (obj is String) {
- m_flags=CV_STRING;
- m_objref=obj;
+ if (obj is String)
+ {
+ m_flags = CV_STRING;
+ m_objref = obj;
return;
}
- if (obj == null) {
+ if (obj == null)
+ {
this = Empty;
return;
}
- if (obj == System.DBNull.Value) {
+ if (obj == System.DBNull.Value)
+ {
this = DBNull;
return;
}
- if (obj == Type.Missing) {
+ if (obj == Type.Missing)
+ {
this = Missing;
return;
}
- if (obj is Array) {
- m_flags=CV_OBJECT | ArrayBitMask;
- m_objref=obj;
+ if (obj is Array)
+ {
+ m_flags = CV_OBJECT | ArrayBitMask;
+ m_objref = obj;
return;
}
@@ -336,55 +359,59 @@ namespace System {
//This is a family-only accessor for the CVType.
//This is never to be exposed externally.
- internal int CVType {
- get {
- return (m_flags&TypeCodeBitMask);
+ internal int CVType
+ {
+ get
+ {
+ return (m_flags & TypeCodeBitMask);
}
}
- public Object ToObject() {
- switch (CVType) {
- case CV_EMPTY:
- return null;
- case CV_BOOLEAN:
- return (Object)(m_data1!=0);
- case CV_I1:
- return (Object)((sbyte)m_data1);
- case CV_U1:
- return (Object)((byte)m_data1);
- case CV_CHAR:
- return (Object)((char)m_data1);
- case CV_I2:
- return (Object)((short)m_data1);
- case CV_U2:
- return (Object)((ushort)m_data1);
- case CV_I4:
- return (Object)(m_data1);
- case CV_U4:
- return (Object)((uint)m_data1);
- case CV_I8:
- return (Object)(GetI8FromVar());
- case CV_U8:
- return (Object)((ulong)GetI8FromVar());
- case CV_R4:
- return (Object)(GetR4FromVar());
- case CV_R8:
- return (Object)(GetR8FromVar());
- case CV_DATETIME:
- return new DateTime(GetI8FromVar());
- case CV_TIMESPAN:
- return new TimeSpan(GetI8FromVar());
- case CV_ENUM:
- return BoxEnum();
- case CV_MISSING:
- return Type.Missing;
- case CV_NULL:
- return System.DBNull.Value;
- case CV_DECIMAL:
- case CV_STRING:
- case CV_OBJECT:
- default:
- return m_objref;
+ public Object ToObject()
+ {
+ switch (CVType)
+ {
+ case CV_EMPTY:
+ return null;
+ case CV_BOOLEAN:
+ return (Object)(m_data1 != 0);
+ case CV_I1:
+ return (Object)((sbyte)m_data1);
+ case CV_U1:
+ return (Object)((byte)m_data1);
+ case CV_CHAR:
+ return (Object)((char)m_data1);
+ case CV_I2:
+ return (Object)((short)m_data1);
+ case CV_U2:
+ return (Object)((ushort)m_data1);
+ case CV_I4:
+ return (Object)(m_data1);
+ case CV_U4:
+ return (Object)((uint)m_data1);
+ case CV_I8:
+ return (Object)(GetI8FromVar());
+ case CV_U8:
+ return (Object)((ulong)GetI8FromVar());
+ case CV_R4:
+ return (Object)(GetR4FromVar());
+ case CV_R8:
+ return (Object)(GetR8FromVar());
+ case CV_DATETIME:
+ return new DateTime(GetI8FromVar());
+ case CV_TIMESPAN:
+ return new TimeSpan(GetI8FromVar());
+ case CV_ENUM:
+ return BoxEnum();
+ case CV_MISSING:
+ return Type.Missing;
+ case CV_NULL:
+ return System.DBNull.Value;
+ case CV_DECIMAL:
+ case CV_STRING:
+ case CV_OBJECT:
+ default:
+ return m_objref;
}
}
@@ -488,7 +515,7 @@ namespace System {
break;
default:
- throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnknownTypeCode", ic.GetTypeCode()));
+ throw new NotSupportedException(SR.Format(SR.NotSupported_UnknownTypeCode, ic.GetTypeCode()));
}
}
}
@@ -534,12 +561,12 @@ namespace System {
}
else
{
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
+ throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant);
}
break;
default:
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
+ throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant);
}
}
else
@@ -643,7 +670,7 @@ namespace System {
break;
default:
- throw new InvalidCastException(Environment.GetResourceString("InvalidCast_CannotCoerceByRefVariant"));
+ throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant);
}
}
}
diff --git a/src/mscorlib/src/System/Version.cs b/src/mscorlib/src/System/Version.cs
deleted file mode 100644
index 7c58d3c0c4..0000000000
--- a/src/mscorlib/src/System/Version.cs
+++ /dev/null
@@ -1,448 +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:
-**
-**
-===========================================================*/
-namespace System {
-
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
- using System.Text;
- using CultureInfo = System.Globalization.CultureInfo;
- using NumberStyles = System.Globalization.NumberStyles;
-
- // A Version object contains four hierarchical numeric components: major, minor,
- // build and revision. Build and revision may be unspecified, which is represented
- // internally as a -1. By definition, an unspecified component matches anything
- // (both unspecified and specified), and an unspecified component is "less than" any
- // specified component.
-
- [Serializable]
- public sealed class Version : ICloneable, IComparable
- , IComparable<Version>, IEquatable<Version>
- {
- // AssemblyName depends on the order staying the same
- private readonly int _Major;
- private readonly int _Minor;
- private readonly int _Build = -1;
- private readonly int _Revision = -1;
-
- public Version(int major, int minor, int build, int revision) {
- if (major < 0)
- throw new ArgumentOutOfRangeException(nameof(major),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- if (minor < 0)
- throw new ArgumentOutOfRangeException(nameof(minor),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- if (build < 0)
- throw new ArgumentOutOfRangeException(nameof(build),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- if (revision < 0)
- throw new ArgumentOutOfRangeException(nameof(revision),Environment.GetResourceString("ArgumentOutOfRange_Version"));
- Contract.EndContractBlock();
-
- _Major = major;
- _Minor = minor;
- _Build = build;
- _Revision = revision;
- }
-
- public Version(int major, int minor, int build) {
- if (major < 0)
- throw new ArgumentOutOfRangeException(nameof(major),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- if (minor < 0)
- throw new ArgumentOutOfRangeException(nameof(minor),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- if (build < 0)
- throw new ArgumentOutOfRangeException(nameof(build),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- Contract.EndContractBlock();
-
- _Major = major;
- _Minor = minor;
- _Build = build;
- }
-
- public Version(int major, int minor) {
- if (major < 0)
- throw new ArgumentOutOfRangeException(nameof(major),Environment.GetResourceString("ArgumentOutOfRange_Version"));
-
- if (minor < 0)
- throw new ArgumentOutOfRangeException(nameof(minor),Environment.GetResourceString("ArgumentOutOfRange_Version"));
- Contract.EndContractBlock();
-
- _Major = major;
- _Minor = minor;
- }
-
- public Version(String version) {
- Version v = Version.Parse(version);
- _Major = v.Major;
- _Minor = v.Minor;
- _Build = v.Build;
- _Revision = v.Revision;
- }
-
- public Version()
- {
- _Major = 0;
- _Minor = 0;
- }
-
- private Version(Version version)
- {
- Debug.Assert(version != null);
-
- _Major = version._Major;
- _Minor = version._Minor;
- _Build = version._Build;
- _Revision = version._Revision;
- }
-
- // Properties for setting and getting version numbers
- public int Major {
- get { return _Major; }
- }
-
- public int Minor {
- get { return _Minor; }
- }
-
- public int Build {
- get { return _Build; }
- }
-
- public int Revision {
- get { return _Revision; }
- }
-
- public short MajorRevision {
- get { return (short)(_Revision >> 16); }
- }
-
- public short MinorRevision {
- get { return (short)(_Revision & 0xFFFF); }
- }
-
- public Object Clone() {
- return new Version(this);
- }
-
- public int CompareTo(Object version)
- {
- if (version == null)
- {
- return 1;
- }
-
- Version v = version as Version;
- if (v == null)
- {
- throw new ArgumentException(Environment.GetResourceString("Arg_MustBeVersion"));
- }
-
- return CompareTo(v);
- }
-
- public int CompareTo(Version value)
- {
- return
- object.ReferenceEquals(value, this) ? 0 :
- object.ReferenceEquals(value, null) ? 1 :
- _Major != value._Major ? (_Major > value._Major ? 1 : -1) :
- _Minor != value._Minor ? (_Minor > value._Minor ? 1 : -1) :
- _Build != value._Build ? (_Build > value._Build ? 1 : -1) :
- _Revision != value._Revision ? (_Revision > value._Revision ? 1 : -1) :
- 0;
- }
-
- public override bool Equals(Object obj) {
- return Equals(obj as Version);
- }
-
- public bool Equals(Version obj)
- {
- return object.ReferenceEquals(obj, this) ||
- (!object.ReferenceEquals(obj, null) &&
- _Major == obj._Major &&
- _Minor == obj._Minor &&
- _Build == obj._Build &&
- _Revision == obj._Revision);
- }
-
- public override int GetHashCode()
- {
- // Let's assume that most version numbers will be pretty small and just
- // OR some lower order bits together.
-
- int accumulator = 0;
-
- accumulator |= (this._Major & 0x0000000F) << 28;
- accumulator |= (this._Minor & 0x000000FF) << 20;
- accumulator |= (this._Build & 0x000000FF) << 12;
- accumulator |= (this._Revision & 0x00000FFF);
-
- return accumulator;
- }
-
- public override String ToString() {
- if (_Build == -1) return(ToString(2));
- if (_Revision == -1) return(ToString(3));
- return(ToString(4));
- }
-
- public String ToString(int fieldCount) {
- StringBuilder sb;
- switch (fieldCount) {
- 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(Environment.GetResourceString("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 (_Revision == -1)
- throw new ArgumentException(Environment.GetResourceString("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);
- }
-
- throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper", "0", "4"), nameof(fieldCount));
- }
- }
-
- //
- // AppendPositiveNumber 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)
- {
- 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));
- } while (num > 0);
- }
-
- public static Version Parse(string input) {
- if (input == null) {
- 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;
- }
-
- 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;
- }
-
- private static bool TryParseVersion(string version, ref VersionResult result) {
- int major, minor, build, revision;
-
- if ((Object)version == null) {
- result.SetFailure(ParseFailureKind.ArgumentNullException);
- return false;
- }
-
- String[] parsedComponents = version.Split('.');
- int parsedComponentsLength = parsedComponents.Length;
- if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4)) {
- result.SetFailure(ParseFailureKind.ArgumentException);
- return false;
- }
-
- if (!TryParseComponent(parsedComponents[0], nameof(version), ref result, out major)) {
- return false;
- }
-
- if (!TryParseComponent(parsedComponents[1], nameof(version), ref result, out minor)) {
- return false;
- }
-
- parsedComponentsLength -= 2;
-
- if (parsedComponentsLength > 0) {
- if (!TryParseComponent(parsedComponents[2], "build", ref result, out build)) {
- return false;
- }
-
- parsedComponentsLength--;
-
- if (parsedComponentsLength > 0) {
- if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision)) {
- return false;
- } else {
- result.m_parsedVersion = new Version(major, minor, build, revision);
- }
- } else {
- result.m_parsedVersion = new Version(major, minor, build);
- }
- } else {
- result.m_parsedVersion = new Version(major, minor);
- }
-
- return true;
- }
-
- private static bool TryParseComponent(string component, string componentName, ref VersionResult result, out int parsedComponent) {
- if (!Int32.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent)) {
- result.SetFailure(ParseFailureKind.FormatException, component);
- return false;
- }
-
- if (parsedComponent < 0) {
- result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName);
- return false;
- }
-
- return true;
- }
-
- public static bool operator ==(Version v1, Version v2) {
- if (Object.ReferenceEquals(v1, null)) {
- return Object.ReferenceEquals(v2, null);
- }
-
- return v1.Equals(v2);
- }
-
- public static bool operator !=(Version v1, Version v2) {
- return !(v1 == v2);
- }
-
- public static bool operator <(Version v1, Version v2) {
- if ((Object) v1 == null)
- throw new ArgumentNullException(nameof(v1));
- Contract.EndContractBlock();
- return (v1.CompareTo(v2) < 0);
- }
-
- public static bool operator <=(Version v1, Version v2) {
- if ((Object) v1 == null)
- throw new ArgumentNullException(nameof(v1));
- Contract.EndContractBlock();
- return (v1.CompareTo(v2) <= 0);
- }
-
- public static bool operator >(Version v1, Version v2) {
- return (v2 < v1);
- }
-
- public static bool operator >=(Version v1, Version v2) {
- return (v2 <= v1);
- }
-
- 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(Environment.GetResourceString("Arg_VersionString"));
- case ParseFailureKind.ArgumentOutOfRangeException:
- return new ArgumentOutOfRangeException(m_exceptionArgument, Environment.GetResourceString("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(Environment.GetResourceString("Format_InvalidString"));
- default:
- Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
- return new ArgumentException(Environment.GetResourceString("Arg_VersionString"));
- }
- }
-
- }
- }
-}
diff --git a/src/mscorlib/src/System/Void.cs b/src/mscorlib/src/System/Void.cs
deleted file mode 100644
index 5c20f634fc..0000000000
--- a/src/mscorlib/src/System/Void.cs
+++ /dev/null
@@ -1,17 +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.
-
-////////////////////////////////////////////////////////////////////////////////
-// Void
-// This class represents the void return type
-////////////////////////////////////////////////////////////////////////////////
-
-namespace System
-{
- // This class represents the void return type
- [Serializable]
- public struct Void
- {
- }
-}
diff --git a/src/mscorlib/src/System/WeakReference.cs b/src/mscorlib/src/System/WeakReference.cs
index 6600d15855..60878b8e1c 100644
--- a/src/mscorlib/src/System/WeakReference.cs
+++ b/src/mscorlib/src/System/WeakReference.cs
@@ -8,18 +8,19 @@
** Purpose: A wrapper for establishing a WeakReference to an Object.
**
===========================================================*/
-namespace System {
-
- using System;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics;
- using System.Diagnostics.Contracts;
+using System;
+using System.Runtime.Serialization;
+using System.Security;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
[Serializable]
- public class WeakReference : ISerializable
+ public class WeakReference : ISerializable
{
// If you fix bugs here, please fix them in WeakReference<T> at the same time.
@@ -27,7 +28,8 @@ namespace System {
internal IntPtr m_handle;
// Migrating InheritanceDemands requires this default ctor, so we can mark it SafeCritical
- protected WeakReference() {
+ protected WeakReference()
+ {
Debug.Assert(false, "WeakReference's protected default ctor should never be used!");
throw new NotImplementedException();
}
@@ -35,40 +37,46 @@ namespace System {
// Creates a new WeakReference that keeps track of target.
// Assumes a Short Weak Reference (ie TrackResurrection is false.)
//
- public WeakReference(Object target)
- : this(target, false) {
+ public WeakReference(Object target)
+ : this(target, false)
+ {
}
-
+
//Creates a new WeakReference that keeps track of target.
//
- public WeakReference(Object target, bool trackResurrection) {
+ public WeakReference(Object target, bool trackResurrection)
+ {
Create(target, trackResurrection);
}
- protected WeakReference(SerializationInfo info, StreamingContext context) {
- if (info==null) {
+ protected WeakReference(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
- Object target = info.GetValue("TrackedObject",typeof(Object));
+ Object target = info.GetValue("TrackedObject", typeof(Object));
bool trackResurrection = info.GetBoolean("TrackResurrection");
Create(target, trackResurrection);
}
-
+
//Determines whether or not this instance of WeakReference still refers to an object
//that has not been collected.
//
- public extern virtual bool IsAlive {
+ public extern virtual bool IsAlive
+ {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
- }
-
+ }
+
//Returns a boolean indicating whether or not we're tracking objects until they're collected (true)
//or just until they're finalized (false).
//
- public virtual bool TrackResurrection {
+ public virtual bool TrackResurrection
+ {
// We need to call IsTrackResurrection non-virtually in GetObjectData, and so the virtual property cannot be FCall directly
get { return IsTrackResurrection(); }
}
@@ -76,13 +84,14 @@ namespace System {
//Gets the Object stored in the handle if it's accessible.
// Or sets it.
//
- public extern virtual Object Target {
+ public extern virtual Object Target
+ {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
get;
[MethodImplAttribute(MethodImplOptions.InternalCall)]
set;
}
-
+
// Free all system resources associated with this reference.
//
// Note: The WeakReference finalizer is not actually run, but
@@ -94,7 +103,8 @@ namespace System {
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info==null) {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -108,5 +118,4 @@ namespace System {
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool IsTrackResurrection();
}
-
}
diff --git a/src/mscorlib/src/System/WeakReferenceOfT.cs b/src/mscorlib/src/System/WeakReferenceOfT.cs
index 0972e5fb9e..fbb6f09098 100644
--- a/src/mscorlib/src/System/WeakReferenceOfT.cs
+++ b/src/mscorlib/src/System/WeakReferenceOfT.cs
@@ -8,19 +8,20 @@
** Purpose: A wrapper for establishing a WeakReference to a generic type.
**
===========================================================*/
+
+using System;
+using System.Runtime.Serialization;
+using System.Security;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+using System.Diagnostics.Contracts;
+
namespace System
{
- using System;
- using System.Runtime.Serialization;
- using System.Security;
- using System.Runtime;
- using System.Runtime.CompilerServices;
- using System.Runtime.Versioning;
- using System.Diagnostics.Contracts;
-
[Serializable]
// This class is sealed to mitigate security issues caused by Object::MemberwiseClone.
- public sealed class WeakReference<T> : ISerializable
+ public sealed class WeakReference<T> : ISerializable
where T : class
{
// If you fix bugs here, please fix them in WeakReference at the same time.
@@ -45,7 +46,8 @@ namespace System
internal WeakReference(SerializationInfo info, StreamingContext context)
{
- if (info == null) {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
@@ -97,7 +99,8 @@ namespace System
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null) {
+ if (info == null)
+ {
throw new ArgumentNullException(nameof(info));
}
Contract.EndContractBlock();
diff --git a/src/mscorlib/src/System/XmlIgnoreMemberAttribute.cs b/src/mscorlib/src/System/XmlIgnoreMemberAttribute.cs
deleted file mode 100644
index 04a8e688e6..0000000000
--- a/src/mscorlib/src/System/XmlIgnoreMemberAttribute.cs
+++ /dev/null
@@ -1,21 +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: Attribute for properties/members that the Xml Serializer should
-** ignore.
-**
-**
-=============================================================================*/
-
-namespace System
-{
- [AttributeUsage(AttributeTargets.Property|AttributeTargets.Field)]
- internal sealed class XmlIgnoreMemberAttribute : Attribute
- {
- }
-}
diff --git a/src/mscorlib/src/System/__ComObject.cs b/src/mscorlib/src/System/__ComObject.cs
index 86800a51f8..412b763ab1 100644
--- a/src/mscorlib/src/System/__ComObject.cs
+++ b/src/mscorlib/src/System/__ComObject.cs
@@ -12,16 +12,17 @@
**
**
===========================================================*/
+
+using System;
+using System.Collections;
+using System.Threading;
+using System.Runtime.InteropServices;
+using System.Runtime.InteropServices.WindowsRuntime;
+using System.Runtime.CompilerServices;
+using System.Reflection;
+
namespace System
{
- using System;
- using System.Collections;
- using System.Threading;
- using System.Runtime.InteropServices;
- using System.Runtime.InteropServices.WindowsRuntime;
- using System.Runtime.CompilerServices;
- using System.Reflection;
-
internal class __ComObject : MarshalByRefObject
{
private Hashtable m_ObjectToDataMap;
@@ -30,7 +31,7 @@ namespace System
** default constructor
** can't instantiate this directly
=============================================================*/
- protected __ComObject ()
+ protected __ComObject()
{
}
@@ -52,9 +53,9 @@ namespace System
if (stringableType != null)
{
return stringableType.ToString();
- }
+ }
}
-
+
return base.ToString();
}
@@ -67,7 +68,7 @@ namespace System
Object data = null;
// Synchronize access to the map.
- lock(this)
+ lock (this)
{
// If the map hasn't been allocated, then there can be no data for the specified key.
if (m_ObjectToDataMap != null)
@@ -79,7 +80,7 @@ namespace System
return data;
}
-
+
//====================================================================
// This method sets the data for the specified key on the current
// __ComObject.
@@ -89,7 +90,7 @@ namespace System
bool bAdded = false;
// Synchronize access to the map.
- lock(this)
+ lock (this)
{
// If the map hasn't been allocated yet, allocate it.
if (m_ObjectToDataMap == null)
@@ -113,9 +114,8 @@ namespace System
internal void ReleaseAllData()
{
// Synchronize access to the map.
- lock(this)
+ lock (this)
{
-
// If the map hasn't been allocated, then there is nothing to do.
if (m_ObjectToDataMap != null)
{
@@ -123,7 +123,7 @@ namespace System
{
// Note: the value could be an object[]
// We are fine for now as object[] doesn't implement IDisposable nor derive from __ComObject
-
+
// If the object implements IDisposable, then call Dispose on it.
IDisposable DisposableObj = o as IDisposable;
if (DisposableObj != null)
@@ -170,7 +170,7 @@ namespace System
private Object CreateEventProvider(RuntimeType t)
{
// Create the event provider for the specified type.
- Object EvProvider = Activator.CreateInstance(t, Activator.ConstructorDefault | BindingFlags.NonPublic, null, new Object[]{this}, null);
+ Object EvProvider = Activator.CreateInstance(t, Activator.ConstructorDefault | BindingFlags.NonPublic, null, new Object[] { this }, null);
// Attempt to cache the wrapper on the object.
if (!SetData(t, EvProvider))
diff --git a/src/mscorlib/src/System/__Filters.cs b/src/mscorlib/src/System/__Filters.cs
deleted file mode 100644
index aabb52d803..0000000000
--- a/src/mscorlib/src/System/__Filters.cs
+++ /dev/null
@@ -1,155 +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.
-
-//
-// This class defines the delegate methods for the COM+ implemented filters.
-//
-//
-//
-
-namespace System {
- using System;
- using System.Reflection;
- using System.Globalization;
- [Serializable]
- internal class __Filters {
-
- // Filters...
- // The following are the built in filters defined for this class. These
- // should really be defined as static methods. They are used in as delegates
- // which currently doesn't support static methods. We will change this
- // once the compiler supports delegates.
- //
- // Note that it is not possible to make this class static as suggested by
- // the above comment anymore because of it got marked serializable.
-
- internal static readonly __Filters Instance = new __Filters();
-
- // FilterAttribute
- // This method will search for a member based upon the attribute passed in.
- // filterCriteria -- an Int32 representing the attribute
- internal virtual bool FilterAttribute(MemberInfo m,Object filterCriteria)
- {
- // Check that the criteria object is an Integer object
- if (filterCriteria == null)
- throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritInt"));
-
- switch (m.MemberType)
- {
- case MemberTypes.Constructor:
- case MemberTypes.Method: {
-
- MethodAttributes criteria = 0;
- try {
- int i = (int) filterCriteria;
- criteria = (MethodAttributes) i;
- }
- catch {
- throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritInt"));
- }
-
-
- MethodAttributes attr;
- if (m.MemberType == MemberTypes.Method)
- attr = ((MethodInfo) m).Attributes;
- else
- attr = ((ConstructorInfo) m).Attributes;
-
- if (((criteria & MethodAttributes.MemberAccessMask) != 0) && (attr & MethodAttributes.MemberAccessMask) != (criteria & MethodAttributes.MemberAccessMask))
- return false;
- if (((criteria & MethodAttributes.Static) != 0) && (attr & MethodAttributes.Static) == 0)
- return false;
- if (((criteria & MethodAttributes.Final) != 0) && (attr & MethodAttributes.Final) == 0)
- return false;
- if (((criteria & MethodAttributes.Virtual) != 0) && (attr & MethodAttributes.Virtual) == 0)
- return false;
- if (((criteria & MethodAttributes.Abstract) != 0) && (attr & MethodAttributes.Abstract) == 0)
- return false;
- if (((criteria & MethodAttributes.SpecialName) != 0) && (attr & MethodAttributes.SpecialName) == 0)
- return false;
- return true;
- }
- case MemberTypes.Field:
- {
- FieldAttributes criteria = 0;
- try {
- int i = (int) filterCriteria;
- criteria = (FieldAttributes) i;
- }
- catch {
- throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritInt"));
- }
-
- FieldAttributes attr = ((FieldInfo) m).Attributes;
- if (((criteria & FieldAttributes.FieldAccessMask) != 0) && (attr & FieldAttributes.FieldAccessMask) != (criteria & FieldAttributes.FieldAccessMask))
- return false;
- if (((criteria & FieldAttributes.Static) != 0) && (attr & FieldAttributes.Static) == 0)
- return false;
- if (((criteria & FieldAttributes.InitOnly) != 0) && (attr & FieldAttributes.InitOnly) == 0)
- return false;
- if (((criteria & FieldAttributes.Literal) != 0) && (attr & FieldAttributes.Literal) == 0)
- return false;
- if (((criteria & FieldAttributes.NotSerialized) != 0) && (attr & FieldAttributes.NotSerialized) == 0)
- return false;
- if (((criteria & FieldAttributes.PinvokeImpl) != 0) && (attr & FieldAttributes.PinvokeImpl) == 0)
- return false;
- return true;
- }
- }
-
- return false;
- }
- // FilterName
- // This method will filter based upon the name. A partial wildcard
- // at the end of the string is supported.
- // filterCriteria -- This is the string name
- internal virtual bool FilterName(MemberInfo m,Object filterCriteria)
- {
- // Check that the criteria object is a String object
- if(filterCriteria == null || !(filterCriteria is String))
- throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritString"));
-
- // At the moment this fails if its done on a single line....
- String str = ((String) filterCriteria);
- str = str.Trim();
-
- String name = m.Name;
- // Get the nested class name only, as opposed to the mangled one
- if (m.MemberType == MemberTypes.NestedType)
- name = name.Substring(name.LastIndexOf('+') + 1);
- // Check to see if this is a prefix or exact match requirement
- if (str.Length > 0 && str[str.Length - 1] == '*') {
- str = str.Substring(0, str.Length - 1);
- return (name.StartsWith(str, StringComparison.Ordinal));
- }
-
- return (name.Equals(str));
- }
-
- // FilterIgnoreCase
- // This delegate will do a name search but does it with the
- // ignore case specified.
- internal virtual bool FilterIgnoreCase(MemberInfo m,Object filterCriteria)
- {
- // Check that the criteria object is a String object
- if(filterCriteria == null || !(filterCriteria is String))
- throw new InvalidFilterCriteriaException(Environment.GetResourceString("RFLCT.FltCritString"));
-
- String str = (String) filterCriteria;
- str = str.Trim();
-
- String name = m.Name;
- // Get the nested class name only, as opposed to the mangled one
- if (m.MemberType == MemberTypes.NestedType)
- name = name.Substring(name.LastIndexOf('+') + 1);
- // Check to see if this is a prefix or exact match requirement
- if (str.Length > 0 && str[str.Length - 1] == '*') {
- str = str.Substring(0, str.Length - 1);
- return (String.Compare(name,0,str,0,str.Length,StringComparison.OrdinalIgnoreCase)==0);
- }
-
- return (String.Compare(str,name, StringComparison.OrdinalIgnoreCase) == 0);
- }
- }
-}
diff --git a/src/mscorlib/src/System/__HResults.cs b/src/mscorlib/src/System/__HResults.cs
index d1f21e22ae..e4183f637a 100644
--- a/src/mscorlib/src/System/__HResults.cs
+++ b/src/mscorlib/src/System/__HResults.cs
@@ -9,116 +9,117 @@
//
//
//===========================================================================*/
-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.
-
- using 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.
+
+using System;
+
+namespace System
+{
internal static 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_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_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_BADIMAGEFORMAT = unchecked((int)0x8007000B);
- internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
- 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_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_BADIMAGEFORMAT = unchecked((int)0x8007000B);
+ internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
+ 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_TIMEOUT = unchecked((int)0x80131505);
+ internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605);
internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO
internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529);
- 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_FORMAT = unchecked((int)0x80131537);
- internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
+ 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_FORMAT = unchecked((int)0x80131537);
+ 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_INVALIDCAST = unchecked((int)0x80004002);
+ 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_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_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_MISSINGMETHOD = unchecked((int)0x80131513);
internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536);
- internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514);
+ 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_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_RANK = unchecked((int)0x80131517);
- internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602);
+ internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E);
+ internal const int COR_E_OVERFLOW = unchecked((int)0x80131516);
+ 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);
- internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538);
- internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533);
+ internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538);
+ 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_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_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_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_THREADSTATE = unchecked((int)0x80131520);
- internal const int COR_E_THREADSTOP = unchecked((int)0x80131521);
+ internal const int COR_E_THREADABORTED = unchecked((int)0x80131530);
+ internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519);
+ 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_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_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_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_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 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);
diff --git a/src/mscorlib/src/mscorlib.Friends.cs b/src/mscorlib/src/mscorlib.Friends.cs
index 0e57812638..b02b4829d9 100644
--- a/src/mscorlib/src/mscorlib.Friends.cs
+++ b/src/mscorlib/src/mscorlib.Friends.cs
@@ -1,17 +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.CompilerServices;
-// We need this to be able to typeforward to internal types
-[assembly: InternalsVisibleTo("mscorlib, PublicKey=00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab", AllInternalsVisible=false)]
+using System.Runtime.CompilerServices;
// For now we are only moving to using this file over AssemblyAttributes.cspp in CoreSys, ideally we would move away from the centralized
// AssemblyAttributes.cspp model for the other build types at a future point in time.
// Depends on things like SuppressUnmanagedCodeAttribute and WindowsRuntimeImportAttribute
-[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)]
+[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime, PublicKey=00000000000000000400000000000000", AllInternalsVisible = false)]
// Depends on WindowsRuntimeImportAttribute
-[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime.UI.Xaml, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)]
+[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime.UI.Xaml, PublicKey=00000000000000000400000000000000", AllInternalsVisible = false)]